1//===-- RegisterContextLLDB.cpp --------------------------------*- C++ -*-===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10
11#include "lldb/lldb-private.h"
12#include "lldb/Core/Address.h"
13#include "lldb/Core/AddressRange.h"
14#include "lldb/Core/DataBufferHeap.h"
15#include "lldb/Core/Log.h"
16#include "lldb/Core/Module.h"
17#include "lldb/Core/RegisterValue.h"
18#include "lldb/Core/Value.h"
19#include "lldb/Expression/DWARFExpression.h"
20#include "lldb/Symbol/DWARFCallFrameInfo.h"
21#include "lldb/Symbol/FuncUnwinders.h"
22#include "lldb/Symbol/Function.h"
23#include "lldb/Symbol/ObjectFile.h"
24#include "lldb/Symbol/Symbol.h"
25#include "lldb/Symbol/SymbolContext.h"
26#include "lldb/Target/ABI.h"
27#include "lldb/Target/DynamicLoader.h"
28#include "lldb/Target/ExecutionContext.h"
29#include "lldb/Target/Platform.h"
30#include "lldb/Target/Process.h"
31#include "lldb/Target/SectionLoadList.h"
32#include "lldb/Target/StackFrame.h"
33#include "lldb/Target/Target.h"
34#include "lldb/Target/Thread.h"
35
36#include "RegisterContextLLDB.h"
37
38using namespace lldb;
39using namespace lldb_private;
40
41RegisterContextLLDB::RegisterContextLLDB
42(
43    Thread& thread,
44    const SharedPtr &next_frame,
45    SymbolContext& sym_ctx,
46    uint32_t frame_number,
47    UnwindLLDB& unwind_lldb
48) :
49    RegisterContext (thread, frame_number),
50    m_thread(thread),
51    m_fast_unwind_plan_sp (),
52    m_full_unwind_plan_sp (),
53    m_fallback_unwind_plan_sp (),
54    m_all_registers_available(false),
55    m_frame_type (-1),
56    m_cfa (LLDB_INVALID_ADDRESS),
57    m_start_pc (),
58    m_current_pc (),
59    m_current_offset (0),
60    m_current_offset_backed_up_one (0),
61    m_sym_ctx(sym_ctx),
62    m_sym_ctx_valid (false),
63    m_frame_number (frame_number),
64    m_registers(),
65    m_parent_unwind (unwind_lldb)
66{
67    m_sym_ctx.Clear(false);
68    m_sym_ctx_valid = false;
69
70    if (IsFrameZero ())
71    {
72        InitializeZerothFrame ();
73    }
74    else
75    {
76        InitializeNonZerothFrame ();
77    }
78
79    // This same code exists over in the GetFullUnwindPlanForFrame() but it may not have been executed yet
80    if (IsFrameZero()
81        || next_frame->m_frame_type == eTrapHandlerFrame
82        || next_frame->m_frame_type == eDebuggerFrame)
83    {
84        m_all_registers_available = true;
85    }
86}
87
88bool
89RegisterContextLLDB::IsUnwindPlanValidForCurrentPC(lldb::UnwindPlanSP unwind_plan_sp, int &valid_pc_offset)
90{
91    if (!unwind_plan_sp)
92        return false;
93
94    // check if m_current_pc is valid
95    if (unwind_plan_sp->PlanValidAtAddress(m_current_pc))
96    {
97        // yes - current offset can be used as is
98        valid_pc_offset = m_current_offset;
99        return true;
100    }
101
102    // if m_current_offset <= 0, we've got nothing else to try
103    if (m_current_offset <= 0)
104        return false;
105
106    // check pc - 1 to see if it's valid
107    Address pc_minus_one (m_current_pc);
108    pc_minus_one.SetOffset(m_current_pc.GetOffset() - 1);
109    if (unwind_plan_sp->PlanValidAtAddress(pc_minus_one))
110    {
111        // *valid_pc_offset = m_current_offset - 1;
112        valid_pc_offset = m_current_pc.GetOffset() - 1;
113        return true;
114    }
115
116    return false;
117}
118
119// Initialize a RegisterContextLLDB which is the first frame of a stack -- the zeroth frame or currently
120// executing frame.
121
122void
123RegisterContextLLDB::InitializeZerothFrame()
124{
125    Log *log(GetLogIfAllCategoriesSet (LIBLLDB_LOG_UNWIND));
126    ExecutionContext exe_ctx(m_thread.shared_from_this());
127    RegisterContextSP reg_ctx_sp = m_thread.GetRegisterContext();
128
129    if (reg_ctx_sp.get() == NULL)
130    {
131        m_frame_type = eNotAValidFrame;
132        UnwindLogMsg ("frame does not have a register context");
133        return;
134    }
135
136    addr_t current_pc = reg_ctx_sp->GetPC();
137
138    if (current_pc == LLDB_INVALID_ADDRESS)
139    {
140        m_frame_type = eNotAValidFrame;
141        UnwindLogMsg ("frame does not have a pc");
142        return;
143    }
144
145    Process *process = exe_ctx.GetProcessPtr();
146
147    // Let ABIs fixup code addresses to make sure they are valid. In ARM ABIs
148    // this will strip bit zero in case we read a PC from memory or from the LR.
149    // (which would be a no-op in frame 0 where we get it from the register set,
150    // but still a good idea to make the call here for other ABIs that may exist.)
151    ABI *abi = process->GetABI().get();
152    if (abi)
153        current_pc = abi->FixCodeAddress(current_pc);
154
155    // Initialize m_current_pc, an Address object, based on current_pc, an addr_t.
156    m_current_pc.SetLoadAddress (current_pc, &process->GetTarget());
157
158    // If we don't have a Module for some reason, we're not going to find symbol/function information - just
159    // stick in some reasonable defaults and hope we can unwind past this frame.
160    ModuleSP pc_module_sp (m_current_pc.GetModule());
161    if (!m_current_pc.IsValid() || !pc_module_sp)
162    {
163        UnwindLogMsg ("using architectural default unwind method");
164    }
165
166    // We require that eSymbolContextSymbol be successfully filled in or this context is of no use to us.
167    if (pc_module_sp.get()
168        && (pc_module_sp->ResolveSymbolContextForAddress (m_current_pc, eSymbolContextFunction| eSymbolContextSymbol, m_sym_ctx) & eSymbolContextSymbol) == eSymbolContextSymbol)
169    {
170        m_sym_ctx_valid = true;
171    }
172
173    AddressRange addr_range;
174    m_sym_ctx.GetAddressRange (eSymbolContextFunction | eSymbolContextSymbol, 0, false, addr_range);
175
176    if (IsTrapHandlerSymbol (process, m_sym_ctx))
177    {
178        m_frame_type = eTrapHandlerFrame;
179    }
180    else
181    {
182        // FIXME:  Detect eDebuggerFrame here.
183        m_frame_type = eNormalFrame;
184    }
185
186    // If we were able to find a symbol/function, set addr_range to the bounds of that symbol/function.
187    // else treat the current pc value as the start_pc and record no offset.
188    if (addr_range.GetBaseAddress().IsValid())
189    {
190        m_start_pc = addr_range.GetBaseAddress();
191        if (m_current_pc.GetSection() == m_start_pc.GetSection())
192        {
193            m_current_offset = m_current_pc.GetOffset() - m_start_pc.GetOffset();
194        }
195        else if (m_current_pc.GetModule() == m_start_pc.GetModule())
196        {
197            // This means that whatever symbol we kicked up isn't really correct
198            // --- we should not cross section boundaries ... We really should NULL out
199            // the function/symbol in this case unless there is a bad assumption
200            // here due to inlined functions?
201            m_current_offset = m_current_pc.GetFileAddress() - m_start_pc.GetFileAddress();
202        }
203        m_current_offset_backed_up_one = m_current_offset;
204    }
205    else
206    {
207        m_start_pc = m_current_pc;
208        m_current_offset = -1;
209        m_current_offset_backed_up_one = -1;
210    }
211
212    // We've set m_frame_type and m_sym_ctx before these calls.
213
214    m_fast_unwind_plan_sp = GetFastUnwindPlanForFrame ();
215    m_full_unwind_plan_sp = GetFullUnwindPlanForFrame ();
216
217    UnwindPlan::RowSP active_row;
218    int cfa_offset = 0;
219    int row_register_kind = -1;
220    if (m_full_unwind_plan_sp && m_full_unwind_plan_sp->PlanValidAtAddress (m_current_pc))
221    {
222        active_row = m_full_unwind_plan_sp->GetRowForFunctionOffset (m_current_offset);
223        row_register_kind = m_full_unwind_plan_sp->GetRegisterKind ();
224        if (active_row.get() && log)
225        {
226            StreamString active_row_strm;
227            active_row->Dump(active_row_strm, m_full_unwind_plan_sp.get(), &m_thread, m_start_pc.GetLoadAddress(exe_ctx.GetTargetPtr()));
228            UnwindLogMsg ("%s", active_row_strm.GetString().c_str());
229        }
230    }
231
232    if (!active_row.get())
233    {
234        UnwindLogMsg ("could not find an unwindplan row for this frame's pc");
235        m_frame_type = eNotAValidFrame;
236        return;
237    }
238
239
240    addr_t cfa_regval = LLDB_INVALID_ADDRESS;
241    if (!ReadGPRValue (row_register_kind, active_row->GetCFARegister(), cfa_regval))
242    {
243        UnwindLogMsg ("could not read CFA register for this frame.");
244        m_frame_type = eNotAValidFrame;
245        return;
246    }
247
248    cfa_offset = active_row->GetCFAOffset ();
249    m_cfa = cfa_regval + cfa_offset;
250
251    UnwindLogMsg ("cfa_regval = 0x%16.16" PRIx64 " (cfa_regval = 0x%16.16" PRIx64 ", cfa_offset = %i)", m_cfa, cfa_regval, cfa_offset);
252    UnwindLogMsg ("initialized frame current pc is 0x%" PRIx64 " cfa is 0x%" PRIx64 " using %s UnwindPlan",
253            (uint64_t) m_current_pc.GetLoadAddress (exe_ctx.GetTargetPtr()),
254            (uint64_t) m_cfa,
255            m_full_unwind_plan_sp->GetSourceName().GetCString());
256}
257
258// Initialize a RegisterContextLLDB for the non-zeroth frame -- rely on the RegisterContextLLDB "below" it
259// to provide things like its current pc value.
260
261void
262RegisterContextLLDB::InitializeNonZerothFrame()
263{
264    Log *log(GetLogIfAllCategoriesSet (LIBLLDB_LOG_UNWIND));
265    if (IsFrameZero ())
266    {
267        m_frame_type = eNotAValidFrame;
268        UnwindLogMsg ("non-zeroth frame tests positive for IsFrameZero -- that shouldn't happen.");
269        return;
270    }
271
272    if (!GetNextFrame().get() || !GetNextFrame()->IsValid())
273    {
274        m_frame_type = eNotAValidFrame;
275        UnwindLogMsg ("Could not get next frame, marking this frame as invalid.");
276        return;
277    }
278    if (!m_thread.GetRegisterContext())
279    {
280        m_frame_type = eNotAValidFrame;
281        UnwindLogMsg ("Could not get register context for this thread, marking this frame as invalid.");
282        return;
283    }
284
285    addr_t pc;
286    if (!ReadGPRValue (eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC, pc))
287    {
288        UnwindLogMsg ("could not get pc value");
289        m_frame_type = eNotAValidFrame;
290        return;
291    }
292
293    if (log)
294    {
295        UnwindLogMsg ("pc = 0x%16.16" PRIx64, pc);
296        addr_t reg_val;
297        if (ReadGPRValue (eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FP, reg_val))
298            UnwindLogMsg ("fp = 0x%16.16" PRIx64, reg_val);
299        if (ReadGPRValue (eRegisterKindGeneric, LLDB_REGNUM_GENERIC_SP, reg_val))
300            UnwindLogMsg ("sp = 0x%16.16" PRIx64, reg_val);
301    }
302
303    // A pc of 0x0 means it's the end of the stack crawl
304    if (pc == 0)
305    {
306        m_frame_type = eNotAValidFrame;
307        UnwindLogMsg ("this frame has a pc of 0x0");
308        return;
309    }
310
311    ExecutionContext exe_ctx(m_thread.shared_from_this());
312    Process *process = exe_ctx.GetProcessPtr();
313    // Let ABIs fixup code addresses to make sure they are valid. In ARM ABIs
314    // this will strip bit zero in case we read a PC from memory or from the LR.
315    ABI *abi = process->GetABI().get();
316    if (abi)
317        pc = abi->FixCodeAddress(pc);
318
319    m_current_pc.SetLoadAddress (pc, &process->GetTarget());
320
321    // If we don't have a Module for some reason, we're not going to find symbol/function information - just
322    // stick in some reasonable defaults and hope we can unwind past this frame.
323    ModuleSP pc_module_sp (m_current_pc.GetModule());
324    if (!m_current_pc.IsValid() || !pc_module_sp)
325    {
326        UnwindLogMsg ("using architectural default unwind method");
327
328        // Test the pc value to see if we know it's in an unmapped/non-executable region of memory.
329        uint32_t permissions;
330        if (process->GetLoadAddressPermissions(pc, permissions)
331            && (permissions & ePermissionsExecutable) == 0)
332        {
333            // If this is the second frame off the stack, we may have unwound the first frame
334            // incorrectly.  But using the architecture default unwind plan may get us back on
335            // track -- albeit possibly skipping a real frame.  Give this frame a clearly-invalid
336            // pc and see if we can get any further.
337            if (GetNextFrame().get() && GetNextFrame()->IsValid() && GetNextFrame()->IsFrameZero())
338            {
339                UnwindLogMsg ("had a pc of 0x%" PRIx64 " which is not in executable memory but on frame 1 -- allowing it once.",
340                         (uint64_t) pc);
341                m_frame_type = eSkipFrame;
342            }
343            else
344            {
345                // anywhere other than the second frame, a non-executable pc means we're off in the weeds -- stop now.
346                m_frame_type = eNotAValidFrame;
347                UnwindLogMsg ("pc is in a non-executable section of memory and this isn't the 2nd frame in the stack walk.");
348                return;
349            }
350        }
351
352        if (abi)
353        {
354            m_fast_unwind_plan_sp.reset ();
355            m_full_unwind_plan_sp.reset (new UnwindPlan (lldb::eRegisterKindGeneric));
356            abi->CreateDefaultUnwindPlan(*m_full_unwind_plan_sp);
357            if (m_frame_type != eSkipFrame)  // don't override eSkipFrame
358            {
359                m_frame_type = eNormalFrame;
360            }
361            m_all_registers_available = false;
362            m_current_offset = -1;
363            m_current_offset_backed_up_one = -1;
364            addr_t cfa_regval = LLDB_INVALID_ADDRESS;
365            int row_register_kind = m_full_unwind_plan_sp->GetRegisterKind ();
366            UnwindPlan::RowSP row = m_full_unwind_plan_sp->GetRowForFunctionOffset(0);
367            if (row.get())
368            {
369                uint32_t cfa_regnum = row->GetCFARegister();
370                int cfa_offset = row->GetCFAOffset();
371                if (!ReadGPRValue (row_register_kind, cfa_regnum, cfa_regval))
372                {
373                    UnwindLogMsg ("failed to get cfa value");
374                    if (m_frame_type != eSkipFrame)   // don't override eSkipFrame
375                    {
376                        m_frame_type = eNormalFrame;
377                    }
378                    return;
379                }
380                m_cfa = cfa_regval + cfa_offset;
381
382                // A couple of sanity checks..
383                if (cfa_regval == LLDB_INVALID_ADDRESS || cfa_regval == 0 || cfa_regval == 1)
384                {
385                    UnwindLogMsg ("could not find a valid cfa address");
386                    m_frame_type = eNotAValidFrame;
387                    return;
388                }
389
390                // cfa_regval should point into the stack memory; if we can query memory region permissions,
391                // see if the memory is allocated & readable.
392                if (process->GetLoadAddressPermissions(cfa_regval, permissions)
393                    && (permissions & ePermissionsReadable) == 0)
394                {
395                    m_frame_type = eNotAValidFrame;
396                    UnwindLogMsg ("the CFA points to a region of memory that is not readable");
397                    return;
398                }
399            }
400            else
401            {
402                UnwindLogMsg ("could not find a row for function offset zero");
403                m_frame_type = eNotAValidFrame;
404                return;
405            }
406
407            UnwindLogMsg ("initialized frame cfa is 0x%" PRIx64, (uint64_t) m_cfa);
408            return;
409        }
410        m_frame_type = eNotAValidFrame;
411        UnwindLogMsg ("could not find any symbol for this pc, or a default unwind plan, to continue unwind.");
412        return;
413    }
414
415    bool resolve_tail_call_address = true; // m_current_pc can be one past the address range of the function...
416                                           // This will handle the case where the saved pc does not point to
417                                           // a function/symbol because it is beyond the bounds of the correct
418                                           // function and there's no symbol there.  ResolveSymbolContextForAddress
419                                           // will fail to find a symbol, back up the pc by 1 and re-search.
420    uint32_t resolved_scope = pc_module_sp->ResolveSymbolContextForAddress (m_current_pc,
421                                                                            eSymbolContextFunction | eSymbolContextSymbol,
422                                                                            m_sym_ctx, resolve_tail_call_address);
423
424    // We require that eSymbolContextSymbol be successfully filled in or this context is of no use to us.
425    if ((resolved_scope & eSymbolContextSymbol) == eSymbolContextSymbol)
426    {
427        m_sym_ctx_valid = true;
428    }
429
430    AddressRange addr_range;
431    if (!m_sym_ctx.GetAddressRange (eSymbolContextFunction | eSymbolContextSymbol, 0, false, addr_range))
432    {
433        m_sym_ctx_valid = false;
434    }
435
436    bool decr_pc_and_recompute_addr_range = false;
437
438    // If the symbol lookup failed...
439    if (m_sym_ctx_valid == false)
440       decr_pc_and_recompute_addr_range = true;
441
442    // Or if we're in the middle of the stack (and not "above" an asynchronous event like sigtramp),
443    // and our "current" pc is the start of a function...
444    if (m_sym_ctx_valid
445        && GetNextFrame()->m_frame_type != eTrapHandlerFrame
446        && GetNextFrame()->m_frame_type != eDebuggerFrame
447        && addr_range.GetBaseAddress().IsValid()
448        && addr_range.GetBaseAddress().GetSection() == m_current_pc.GetSection()
449        && addr_range.GetBaseAddress().GetOffset() == m_current_pc.GetOffset())
450    {
451        decr_pc_and_recompute_addr_range = true;
452    }
453
454    // We need to back up the pc by 1 byte and re-search for the Symbol to handle the case where the "saved pc"
455    // value is pointing to the next function, e.g. if a function ends with a CALL instruction.
456    // FIXME this may need to be an architectural-dependent behavior; if so we'll need to add a member function
457    // to the ABI plugin and consult that.
458    if (decr_pc_and_recompute_addr_range)
459    {
460        Address temporary_pc(m_current_pc);
461        temporary_pc.SetOffset(m_current_pc.GetOffset() - 1);
462        m_sym_ctx.Clear(false);
463        m_sym_ctx_valid = false;
464        if ((pc_module_sp->ResolveSymbolContextForAddress (temporary_pc, eSymbolContextFunction| eSymbolContextSymbol, m_sym_ctx) & eSymbolContextSymbol) == eSymbolContextSymbol)
465        {
466            m_sym_ctx_valid = true;
467        }
468        if (!m_sym_ctx.GetAddressRange (eSymbolContextFunction | eSymbolContextSymbol, 0, false,  addr_range))
469        {
470            m_sym_ctx_valid = false;
471        }
472    }
473
474    // If we were able to find a symbol/function, set addr_range_ptr to the bounds of that symbol/function.
475    // else treat the current pc value as the start_pc and record no offset.
476    if (addr_range.GetBaseAddress().IsValid())
477    {
478        m_start_pc = addr_range.GetBaseAddress();
479        m_current_offset = m_current_pc.GetOffset() - m_start_pc.GetOffset();
480        m_current_offset_backed_up_one = m_current_offset;
481        if (decr_pc_and_recompute_addr_range && m_current_offset_backed_up_one > 0)
482        {
483            m_current_offset_backed_up_one--;
484            if (m_sym_ctx_valid)
485                m_current_pc.SetOffset(m_current_pc.GetOffset() - 1);
486        }
487    }
488    else
489    {
490        m_start_pc = m_current_pc;
491        m_current_offset = -1;
492        m_current_offset_backed_up_one = -1;
493    }
494
495    if (IsTrapHandlerSymbol (process, m_sym_ctx))
496    {
497        m_frame_type = eTrapHandlerFrame;
498    }
499    else
500    {
501        // FIXME:  Detect eDebuggerFrame here.
502        if (m_frame_type != eSkipFrame) // don't override eSkipFrame
503        {
504            m_frame_type = eNormalFrame;
505        }
506    }
507
508    // We've set m_frame_type and m_sym_ctx before this call.
509    m_fast_unwind_plan_sp = GetFastUnwindPlanForFrame ();
510
511    UnwindPlan::RowSP active_row;
512    int cfa_offset = 0;
513    int row_register_kind = -1;
514
515    // Try to get by with just the fast UnwindPlan if possible - the full UnwindPlan may be expensive to get
516    // (e.g. if we have to parse the entire eh_frame section of an ObjectFile for the first time.)
517
518    if (m_fast_unwind_plan_sp && m_fast_unwind_plan_sp->PlanValidAtAddress (m_current_pc))
519    {
520        active_row = m_fast_unwind_plan_sp->GetRowForFunctionOffset (m_current_offset);
521        row_register_kind = m_fast_unwind_plan_sp->GetRegisterKind ();
522        if (active_row.get() && log)
523        {
524            StreamString active_row_strm;
525            active_row->Dump(active_row_strm, m_fast_unwind_plan_sp.get(), &m_thread, m_start_pc.GetLoadAddress(exe_ctx.GetTargetPtr()));
526            UnwindLogMsg ("active row: %s", active_row_strm.GetString().c_str());
527        }
528    }
529    else
530    {
531        m_full_unwind_plan_sp = GetFullUnwindPlanForFrame ();
532        int valid_offset = -1;
533        if (IsUnwindPlanValidForCurrentPC(m_full_unwind_plan_sp, valid_offset))
534        {
535            active_row = m_full_unwind_plan_sp->GetRowForFunctionOffset (valid_offset);
536            row_register_kind = m_full_unwind_plan_sp->GetRegisterKind ();
537            if (active_row.get() && log)
538            {
539                StreamString active_row_strm;
540                active_row->Dump(active_row_strm, m_full_unwind_plan_sp.get(), &m_thread, m_start_pc.GetLoadAddress(exe_ctx.GetTargetPtr()));
541                UnwindLogMsg ("active row: %s", active_row_strm.GetString().c_str());
542            }
543        }
544    }
545
546    if (!active_row.get())
547    {
548        m_frame_type = eNotAValidFrame;
549        UnwindLogMsg ("could not find unwind row for this pc");
550        return;
551    }
552
553    addr_t cfa_regval = LLDB_INVALID_ADDRESS;
554    if (!ReadGPRValue (row_register_kind, active_row->GetCFARegister(), cfa_regval))
555    {
556        UnwindLogMsg ("failed to get cfa reg %d/%d", row_register_kind, active_row->GetCFARegister());
557        m_frame_type = eNotAValidFrame;
558        return;
559    }
560
561    cfa_offset = active_row->GetCFAOffset ();
562    m_cfa = cfa_regval + cfa_offset;
563
564    UnwindLogMsg ("cfa_regval = 0x%16.16" PRIx64 " (cfa_regval = 0x%16.16" PRIx64 ", cfa_offset = %i)", m_cfa, cfa_regval, cfa_offset);
565
566    // A couple of sanity checks..
567    if (cfa_regval == LLDB_INVALID_ADDRESS || cfa_regval == 0 || cfa_regval == 1)
568    {
569        UnwindLogMsg ("could not find a valid cfa address");
570        m_frame_type = eNotAValidFrame;
571        return;
572    }
573
574    // If we have a bad stack setup, we can get the same CFA value multiple times -- or even
575    // more devious, we can actually oscillate between two CFA values.  Detect that here and
576    // break out to avoid a possible infinite loop in lldb trying to unwind the stack.
577    addr_t next_frame_cfa;
578    addr_t next_next_frame_cfa = LLDB_INVALID_ADDRESS;
579    if (GetNextFrame().get() && GetNextFrame()->GetCFA(next_frame_cfa))
580    {
581        bool repeating_frames = false;
582        if (next_frame_cfa == m_cfa)
583        {
584            repeating_frames = true;
585        }
586        else
587        {
588            if (GetNextFrame()->GetNextFrame() && GetNextFrame()->GetNextFrame()->GetCFA(next_next_frame_cfa)
589                && next_next_frame_cfa == m_cfa)
590            {
591                repeating_frames = true;
592            }
593        }
594        if (repeating_frames && abi->FunctionCallsChangeCFA())
595        {
596            UnwindLogMsg ("same CFA address as next frame, assuming the unwind is looping - stopping");
597            m_frame_type = eNotAValidFrame;
598            return;
599        }
600    }
601
602    UnwindLogMsg ("initialized frame current pc is 0x%" PRIx64 " cfa is 0x%" PRIx64,
603            (uint64_t) m_current_pc.GetLoadAddress (exe_ctx.GetTargetPtr()), (uint64_t) m_cfa);
604}
605
606
607bool
608RegisterContextLLDB::IsFrameZero () const
609{
610    return m_frame_number == 0;
611}
612
613
614// Find a fast unwind plan for this frame, if possible.
615//
616// On entry to this method,
617//
618//   1. m_frame_type should already be set to eTrapHandlerFrame/eDebuggerFrame if either of those are correct,
619//   2. m_sym_ctx should already be filled in, and
620//   3. m_current_pc should have the current pc value for this frame
621//   4. m_current_offset_backed_up_one should have the current byte offset into the function, maybe backed up by 1, -1 if unknown
622
623UnwindPlanSP
624RegisterContextLLDB::GetFastUnwindPlanForFrame ()
625{
626    UnwindPlanSP unwind_plan_sp;
627    ModuleSP pc_module_sp (m_current_pc.GetModule());
628
629    if (!m_current_pc.IsValid() || !pc_module_sp || pc_module_sp->GetObjectFile() == NULL)
630        return unwind_plan_sp;
631
632    if (IsFrameZero ())
633        return unwind_plan_sp;
634
635    FuncUnwindersSP func_unwinders_sp (pc_module_sp->GetObjectFile()->GetUnwindTable().GetFuncUnwindersContainingAddress (m_current_pc, m_sym_ctx));
636    if (!func_unwinders_sp)
637        return unwind_plan_sp;
638
639    // If we're in _sigtramp(), unwinding past this frame requires special knowledge.
640    if (m_frame_type == eTrapHandlerFrame || m_frame_type == eDebuggerFrame)
641        return unwind_plan_sp;
642
643    unwind_plan_sp = func_unwinders_sp->GetUnwindPlanFastUnwind (m_thread);
644    if (unwind_plan_sp)
645    {
646        if (unwind_plan_sp->PlanValidAtAddress (m_current_pc))
647        {
648            Log *log(GetLogIfAllCategoriesSet (LIBLLDB_LOG_UNWIND));
649            if (log && log->GetVerbose())
650            {
651                if (m_fast_unwind_plan_sp)
652                    UnwindLogMsgVerbose ("frame, and has a fast UnwindPlan");
653                else
654                    UnwindLogMsgVerbose ("frame");
655            }
656            m_frame_type = eNormalFrame;
657            return unwind_plan_sp;
658        }
659        else
660        {
661            unwind_plan_sp.reset();
662        }
663    }
664    return unwind_plan_sp;
665}
666
667// On entry to this method,
668//
669//   1. m_frame_type should already be set to eTrapHandlerFrame/eDebuggerFrame if either of those are correct,
670//   2. m_sym_ctx should already be filled in, and
671//   3. m_current_pc should have the current pc value for this frame
672//   4. m_current_offset_backed_up_one should have the current byte offset into the function, maybe backed up by 1, -1 if unknown
673
674UnwindPlanSP
675RegisterContextLLDB::GetFullUnwindPlanForFrame ()
676{
677    UnwindPlanSP unwind_plan_sp;
678    UnwindPlanSP arch_default_unwind_plan_sp;
679    ExecutionContext exe_ctx(m_thread.shared_from_this());
680    Process *process = exe_ctx.GetProcessPtr();
681    ABI *abi = process ? process->GetABI().get() : NULL;
682    if (abi)
683    {
684        arch_default_unwind_plan_sp.reset (new UnwindPlan (lldb::eRegisterKindGeneric));
685        abi->CreateDefaultUnwindPlan(*arch_default_unwind_plan_sp);
686    }
687    else
688    {
689        UnwindLogMsg ("unable to get architectural default UnwindPlan from ABI plugin");
690    }
691
692    bool behaves_like_zeroth_frame = false;
693    if (IsFrameZero ()
694        || GetNextFrame()->m_frame_type == eTrapHandlerFrame
695        || GetNextFrame()->m_frame_type == eDebuggerFrame)
696    {
697        behaves_like_zeroth_frame = true;
698        // If this frame behaves like a 0th frame (currently executing or
699        // interrupted asynchronously), all registers can be retrieved.
700        m_all_registers_available = true;
701    }
702
703    // If we've done a jmp 0x0 / bl 0x0 (called through a null function pointer) so the pc is 0x0
704    // in the zeroth frame, we need to use the "unwind at first instruction" arch default UnwindPlan
705    // Also, if this Process can report on memory region attributes, any non-executable region means
706    // we jumped through a bad function pointer - handle the same way as 0x0.
707    // Note, if we have a symbol context & a symbol, we don't want to follow this code path.  This is
708    // for jumping to memory regions without any information available.
709
710    if ((!m_sym_ctx_valid || m_sym_ctx.symbol == NULL) && behaves_like_zeroth_frame && m_current_pc.IsValid())
711    {
712        uint32_t permissions;
713        addr_t current_pc_addr = m_current_pc.GetLoadAddress (exe_ctx.GetTargetPtr());
714        if (current_pc_addr == 0
715            || (process->GetLoadAddressPermissions (current_pc_addr, permissions)
716                && (permissions & ePermissionsExecutable) == 0))
717        {
718            unwind_plan_sp.reset (new UnwindPlan (lldb::eRegisterKindGeneric));
719            abi->CreateFunctionEntryUnwindPlan(*unwind_plan_sp);
720            m_frame_type = eNormalFrame;
721            return unwind_plan_sp;
722        }
723    }
724
725    // No Module for the current pc, try using the architecture default unwind.
726    ModuleSP pc_module_sp (m_current_pc.GetModule());
727    if (!m_current_pc.IsValid() || !pc_module_sp || pc_module_sp->GetObjectFile() == NULL)
728    {
729        m_frame_type = eNormalFrame;
730        return arch_default_unwind_plan_sp;
731    }
732
733    FuncUnwindersSP func_unwinders_sp;
734    if (m_sym_ctx_valid)
735    {
736        func_unwinders_sp = pc_module_sp->GetObjectFile()->GetUnwindTable().GetFuncUnwindersContainingAddress (m_current_pc, m_sym_ctx);
737    }
738
739    // No FuncUnwinders available for this pc (i.e. a stripped function symbol and -fomit-frame-pointer).
740    // Try using the eh_frame information relative to the current PC,
741    // and finally fall back on the architectural default unwind.
742    if (!func_unwinders_sp)
743    {
744        DWARFCallFrameInfo *eh_frame = pc_module_sp && pc_module_sp->GetObjectFile() ?
745            pc_module_sp->GetObjectFile()->GetUnwindTable().GetEHFrameInfo() : nullptr;
746
747        m_frame_type = eNormalFrame;
748        if (eh_frame && m_current_pc.IsValid())
749        {
750            unwind_plan_sp.reset (new UnwindPlan (lldb::eRegisterKindGeneric));
751            // Even with -fomit-frame-pointer, we can try eh_frame to get back on track.
752            if (eh_frame->GetUnwindPlan (m_current_pc, *unwind_plan_sp))
753                return unwind_plan_sp;
754            else
755                unwind_plan_sp.reset();
756        }
757        return arch_default_unwind_plan_sp;
758    }
759
760    // If we're in _sigtramp(), unwinding past this frame requires special knowledge.  On Mac OS X this knowledge
761    // is properly encoded in the eh_frame section, so prefer that if available.
762    // On other platforms we may need to provide a platform-specific UnwindPlan which encodes the details of
763    // how to unwind out of sigtramp.
764    if (m_frame_type == eTrapHandlerFrame)
765    {
766        m_fast_unwind_plan_sp.reset();
767        unwind_plan_sp = func_unwinders_sp->GetUnwindPlanAtCallSite (m_current_offset_backed_up_one);
768        if (unwind_plan_sp && unwind_plan_sp->PlanValidAtAddress (m_current_pc) && unwind_plan_sp->GetSourcedFromCompiler() == eLazyBoolYes)
769        {
770            return unwind_plan_sp;
771        }
772    }
773
774    // Ask the DynamicLoader if the eh_frame CFI should be trusted in this frame even when it's frame zero
775    // This comes up if we have hand-written functions in a Module and hand-written eh_frame.  The assembly
776    // instruction inspection may fail and the eh_frame CFI were probably written with some care to do the
777    // right thing.  It'd be nice if there was a way to ask the eh_frame directly if it is asynchronous
778    // (can be trusted at every instruction point) or synchronous (the normal case - only at call sites).
779    // But there is not.
780    if (process && process->GetDynamicLoader() && process->GetDynamicLoader()->AlwaysRelyOnEHUnwindInfo (m_sym_ctx))
781    {
782        unwind_plan_sp = func_unwinders_sp->GetUnwindPlanAtCallSite (m_current_offset_backed_up_one);
783        if (unwind_plan_sp && unwind_plan_sp->PlanValidAtAddress (m_current_pc))
784        {
785            UnwindLogMsgVerbose ("frame uses %s for full UnwindPlan because the DynamicLoader suggested we prefer it",
786                           unwind_plan_sp->GetSourceName().GetCString());
787            return unwind_plan_sp;
788        }
789    }
790
791    // Typically the NonCallSite UnwindPlan is the unwind created by inspecting the assembly language instructions
792    if (behaves_like_zeroth_frame)
793    {
794        unwind_plan_sp = func_unwinders_sp->GetUnwindPlanAtNonCallSite (m_thread);
795        if (unwind_plan_sp && unwind_plan_sp->PlanValidAtAddress (m_current_pc))
796        {
797            if (unwind_plan_sp->GetSourcedFromCompiler() == eLazyBoolNo)
798            {
799                // We probably have an UnwindPlan created by inspecting assembly instructions, and we probably
800                // don't have any eh_frame instructions available.
801                // The assembly profilers work really well with compiler-generated functions but hand-written
802                // assembly can be problematic.  We'll set the architecture default UnwindPlan as our fallback
803                // UnwindPlan in case this doesn't work out when we try to unwind.
804                m_fallback_unwind_plan_sp = arch_default_unwind_plan_sp;
805            }
806            UnwindLogMsgVerbose ("frame uses %s for full UnwindPlan", unwind_plan_sp->GetSourceName().GetCString());
807            return unwind_plan_sp;
808        }
809    }
810
811    // Typically this is unwind info from an eh_frame section intended for exception handling; only valid at call sites
812    unwind_plan_sp = func_unwinders_sp->GetUnwindPlanAtCallSite (m_current_offset_backed_up_one);
813    int valid_offset = -1;
814    if (IsUnwindPlanValidForCurrentPC(unwind_plan_sp, valid_offset))
815    {
816        UnwindLogMsgVerbose ("frame uses %s for full UnwindPlan", unwind_plan_sp->GetSourceName().GetCString());
817        return unwind_plan_sp;
818    }
819
820    // We'd prefer to use an UnwindPlan intended for call sites when we're at a call site but if we've
821    // struck out on that, fall back to using the non-call-site assembly inspection UnwindPlan if possible.
822    unwind_plan_sp = func_unwinders_sp->GetUnwindPlanAtNonCallSite (m_thread);
823    if (unwind_plan_sp->GetSourcedFromCompiler() == eLazyBoolNo)
824    {
825        // We probably have an UnwindPlan created by inspecting assembly instructions, and we probably
826        // don't have any eh_frame instructions available.
827        // The assembly profilers work really well with compiler-generated functions but hand-written
828        // assembly can be problematic.  We'll set the architecture default UnwindPlan as our fallback
829        // UnwindPlan in case this doesn't work out when we try to unwind.
830        m_fallback_unwind_plan_sp = arch_default_unwind_plan_sp;
831    }
832
833    if (IsUnwindPlanValidForCurrentPC(unwind_plan_sp, valid_offset))
834    {
835        UnwindLogMsgVerbose ("frame uses %s for full UnwindPlan", unwind_plan_sp->GetSourceName().GetCString());
836        return unwind_plan_sp;
837    }
838
839    // If we're on the first instruction of a function, and we have an architectural default UnwindPlan
840    // for the initial instruction of a function, use that.
841    if (m_current_offset_backed_up_one == 0)
842    {
843        unwind_plan_sp = func_unwinders_sp->GetUnwindPlanArchitectureDefaultAtFunctionEntry (m_thread);
844        if (unwind_plan_sp)
845        {
846            UnwindLogMsgVerbose ("frame uses %s for full UnwindPlan", unwind_plan_sp->GetSourceName().GetCString());
847            return unwind_plan_sp;
848        }
849    }
850
851    // If nothing else, use the architectural default UnwindPlan and hope that does the job.
852    if (arch_default_unwind_plan_sp)
853        UnwindLogMsgVerbose ("frame uses %s for full UnwindPlan", arch_default_unwind_plan_sp->GetSourceName().GetCString());
854    else
855        UnwindLogMsg ("Unable to find any UnwindPlan for full unwind of this frame.");
856
857    return arch_default_unwind_plan_sp;
858}
859
860
861void
862RegisterContextLLDB::InvalidateAllRegisters ()
863{
864    m_frame_type = eNotAValidFrame;
865}
866
867size_t
868RegisterContextLLDB::GetRegisterCount ()
869{
870    return m_thread.GetRegisterContext()->GetRegisterCount();
871}
872
873const RegisterInfo *
874RegisterContextLLDB::GetRegisterInfoAtIndex (size_t reg)
875{
876    return m_thread.GetRegisterContext()->GetRegisterInfoAtIndex (reg);
877}
878
879size_t
880RegisterContextLLDB::GetRegisterSetCount ()
881{
882    return m_thread.GetRegisterContext()->GetRegisterSetCount ();
883}
884
885const RegisterSet *
886RegisterContextLLDB::GetRegisterSet (size_t reg_set)
887{
888    return m_thread.GetRegisterContext()->GetRegisterSet (reg_set);
889}
890
891uint32_t
892RegisterContextLLDB::ConvertRegisterKindToRegisterNumber (uint32_t kind, uint32_t num)
893{
894    return m_thread.GetRegisterContext()->ConvertRegisterKindToRegisterNumber (kind, num);
895}
896
897bool
898RegisterContextLLDB::ReadRegisterValueFromRegisterLocation (lldb_private::UnwindLLDB::RegisterLocation regloc,
899                                                            const RegisterInfo *reg_info,
900                                                            RegisterValue &value)
901{
902    if (!IsValid())
903        return false;
904    bool success = false;
905
906    switch (regloc.type)
907    {
908    case UnwindLLDB::RegisterLocation::eRegisterInRegister:
909        {
910            const RegisterInfo *other_reg_info = GetRegisterInfoAtIndex(regloc.location.register_number);
911
912            if (!other_reg_info)
913                return false;
914
915            if (IsFrameZero ())
916            {
917                success = m_thread.GetRegisterContext()->ReadRegister (other_reg_info, value);
918            }
919            else
920            {
921                success = GetNextFrame()->ReadRegister (other_reg_info, value);
922            }
923        }
924        break;
925    case UnwindLLDB::RegisterLocation::eRegisterValueInferred:
926        success = value.SetUInt (regloc.location.inferred_value, reg_info->byte_size);
927        break;
928
929    case UnwindLLDB::RegisterLocation::eRegisterNotSaved:
930        break;
931    case UnwindLLDB::RegisterLocation::eRegisterSavedAtHostMemoryLocation:
932        assert ("FIXME debugger inferior function call unwind");
933        break;
934    case UnwindLLDB::RegisterLocation::eRegisterSavedAtMemoryLocation:
935        {
936            Error error (ReadRegisterValueFromMemory(reg_info,
937                                                     regloc.location.target_memory_location,
938                                                     reg_info->byte_size,
939                                                     value));
940            success = error.Success();
941        }
942        break;
943    default:
944        assert ("Unknown RegisterLocation type.");
945        break;
946    }
947    return success;
948}
949
950bool
951RegisterContextLLDB::WriteRegisterValueToRegisterLocation (lldb_private::UnwindLLDB::RegisterLocation regloc,
952                                                           const RegisterInfo *reg_info,
953                                                           const RegisterValue &value)
954{
955    if (!IsValid())
956        return false;
957
958    bool success = false;
959
960    switch (regloc.type)
961    {
962        case UnwindLLDB::RegisterLocation::eRegisterInRegister:
963            {
964                const RegisterInfo *other_reg_info = GetRegisterInfoAtIndex(regloc.location.register_number);
965                if (IsFrameZero ())
966                {
967                    success = m_thread.GetRegisterContext()->WriteRegister (other_reg_info, value);
968                }
969                else
970                {
971                    success = GetNextFrame()->WriteRegister (other_reg_info, value);
972                }
973            }
974            break;
975        case UnwindLLDB::RegisterLocation::eRegisterValueInferred:
976        case UnwindLLDB::RegisterLocation::eRegisterNotSaved:
977            break;
978        case UnwindLLDB::RegisterLocation::eRegisterSavedAtHostMemoryLocation:
979            assert ("FIXME debugger inferior function call unwind");
980            break;
981        case UnwindLLDB::RegisterLocation::eRegisterSavedAtMemoryLocation:
982            {
983                Error error (WriteRegisterValueToMemory (reg_info,
984                                                         regloc.location.target_memory_location,
985                                                         reg_info->byte_size,
986                                                         value));
987                success = error.Success();
988            }
989            break;
990        default:
991            assert ("Unknown RegisterLocation type.");
992            break;
993    }
994    return success;
995}
996
997
998bool
999RegisterContextLLDB::IsValid () const
1000{
1001    return m_frame_type != eNotAValidFrame;
1002}
1003
1004bool
1005RegisterContextLLDB::IsTrapHandlerFrame () const
1006{
1007    return m_frame_type == eTrapHandlerFrame;
1008}
1009
1010// A skip frame is a bogus frame on the stack -- but one where we're likely to find a real frame farther
1011// up the stack if we keep looking.  It's always the second frame in an unwind (i.e. the first frame after
1012// frame zero) where unwinding can be the trickiest.  Ideally we'll mark up this frame in some way so the
1013// user knows we're displaying bad data and we may have skipped one frame of their real program in the
1014// process of getting back on track.
1015
1016bool
1017RegisterContextLLDB::IsSkipFrame () const
1018{
1019    return m_frame_type == eSkipFrame;
1020}
1021
1022bool
1023RegisterContextLLDB::IsTrapHandlerSymbol (lldb_private::Process *process, const lldb_private::SymbolContext &m_sym_ctx) const
1024{
1025    PlatformSP platform_sp (process->GetTarget().GetPlatform());
1026    if (platform_sp)
1027    {
1028        const std::vector<ConstString> trap_handler_names (platform_sp->GetTrapHandlerSymbolNames());
1029        for (ConstString name : trap_handler_names)
1030        {
1031            if ((m_sym_ctx.function && m_sym_ctx.function->GetName() == name) ||
1032                (m_sym_ctx.symbol   && m_sym_ctx.symbol->GetName()   == name))
1033            {
1034                return true;
1035            }
1036        }
1037    }
1038    const std::vector<ConstString> user_specified_trap_handler_names (m_parent_unwind.GetUserSpecifiedTrapHandlerFunctionNames());
1039    for (ConstString name : user_specified_trap_handler_names)
1040    {
1041        if ((m_sym_ctx.function && m_sym_ctx.function->GetName() == name) ||
1042            (m_sym_ctx.symbol   && m_sym_ctx.symbol->GetName()   == name))
1043        {
1044            return true;
1045        }
1046    }
1047
1048    return false;
1049}
1050
1051// Answer the question: Where did THIS frame save the CALLER frame ("previous" frame)'s register value?
1052
1053enum UnwindLLDB::RegisterSearchResult
1054RegisterContextLLDB::SavedLocationForRegister (uint32_t lldb_regnum, lldb_private::UnwindLLDB::RegisterLocation &regloc)
1055{
1056    // Have we already found this register location?
1057    if (!m_registers.empty())
1058    {
1059        std::map<uint32_t, lldb_private::UnwindLLDB::RegisterLocation>::const_iterator iterator;
1060        iterator = m_registers.find (lldb_regnum);
1061        if (iterator != m_registers.end())
1062        {
1063            regloc = iterator->second;
1064            UnwindLogMsg ("supplying caller's saved reg %d's location, cached", lldb_regnum);
1065            return UnwindLLDB::RegisterSearchResult::eRegisterFound;
1066        }
1067    }
1068
1069    uint32_t sp_regnum = LLDB_INVALID_REGNUM;
1070    uint32_t pc_regnum = LLDB_INVALID_REGNUM;
1071    m_thread.GetRegisterContext()->ConvertBetweenRegisterKinds (eRegisterKindGeneric, LLDB_REGNUM_GENERIC_SP, eRegisterKindLLDB, sp_regnum);
1072    m_thread.GetRegisterContext()->ConvertBetweenRegisterKinds (eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC, eRegisterKindLLDB, pc_regnum);
1073
1074    // Are we looking for the CALLER's stack pointer?  The stack pointer is defined to be the same as THIS frame's
1075    // CFA so just return the CFA value.  This is true on x86-32/x86-64 at least.
1076    if (sp_regnum != LLDB_INVALID_REGNUM && sp_regnum == lldb_regnum)
1077    {
1078        // make sure we won't lose precision copying an addr_t (m_cfa) into a uint64_t (.inferred_value)
1079        assert (sizeof (addr_t) <= sizeof (uint64_t));
1080        regloc.type = UnwindLLDB::RegisterLocation::eRegisterValueInferred;
1081        regloc.location.inferred_value = m_cfa;
1082        m_registers[lldb_regnum] = regloc;
1083        UnwindLogMsg ("supplying caller's stack pointer (%d) value, computed from CFA", lldb_regnum);
1084        return UnwindLLDB::RegisterSearchResult::eRegisterFound;
1085    }
1086
1087    // Look through the available UnwindPlans for the register location.
1088
1089    UnwindPlan::Row::RegisterLocation unwindplan_regloc;
1090    bool have_unwindplan_regloc = false;
1091    RegisterKind unwindplan_registerkind = (RegisterKind)-1;
1092
1093    if (m_fast_unwind_plan_sp)
1094    {
1095        UnwindPlan::RowSP active_row = m_fast_unwind_plan_sp->GetRowForFunctionOffset (m_current_offset);
1096        unwindplan_registerkind = m_fast_unwind_plan_sp->GetRegisterKind ();
1097        uint32_t row_regnum;
1098        if (!m_thread.GetRegisterContext()->ConvertBetweenRegisterKinds (eRegisterKindLLDB, lldb_regnum, unwindplan_registerkind, row_regnum))
1099        {
1100            UnwindLogMsg ("could not convert lldb regnum %d into %d RegisterKind reg numbering scheme",
1101                    lldb_regnum, (int) unwindplan_registerkind);
1102            return UnwindLLDB::RegisterSearchResult::eRegisterNotFound;
1103        }
1104        if (active_row->GetRegisterInfo (row_regnum, unwindplan_regloc))
1105        {
1106            UnwindLogMsg ("supplying caller's saved reg %d's location using FastUnwindPlan", lldb_regnum);
1107            have_unwindplan_regloc = true;
1108        }
1109    }
1110
1111    if (!have_unwindplan_regloc)
1112    {
1113        // m_full_unwind_plan_sp being NULL means that we haven't tried to find a full UnwindPlan yet
1114        if (!m_full_unwind_plan_sp)
1115            m_full_unwind_plan_sp = GetFullUnwindPlanForFrame ();
1116
1117        if (m_full_unwind_plan_sp)
1118        {
1119            UnwindPlan::RowSP active_row = m_full_unwind_plan_sp->GetRowForFunctionOffset (m_current_offset);
1120            unwindplan_registerkind = m_full_unwind_plan_sp->GetRegisterKind ();
1121            uint32_t row_regnum;
1122            bool row_register_rewritten_to_return_address_reg = false;
1123
1124            // If we're fetching the saved pc and this UnwindPlan defines a ReturnAddress register (e.g. lr on arm),
1125            // look for the return address register number in the UnwindPlan's row.
1126            if (lldb_regnum == pc_regnum && m_full_unwind_plan_sp->GetReturnAddressRegister() != LLDB_INVALID_REGNUM)
1127            {
1128               row_regnum = m_full_unwind_plan_sp->GetReturnAddressRegister();
1129               row_register_rewritten_to_return_address_reg = true;
1130               UnwindLogMsg ("requested caller's saved PC but this UnwindPlan uses a RA reg; getting reg %d instead",
1131                       row_regnum);
1132            }
1133            else
1134            {
1135                if (!m_thread.GetRegisterContext()->ConvertBetweenRegisterKinds (eRegisterKindLLDB, lldb_regnum, unwindplan_registerkind, row_regnum))
1136                {
1137                    if (unwindplan_registerkind == eRegisterKindGeneric)
1138                        UnwindLogMsg ("could not convert lldb regnum %d into eRegisterKindGeneric reg numbering scheme", lldb_regnum);
1139                    else
1140                        UnwindLogMsg ("could not convert lldb regnum %d into %d RegisterKind reg numbering scheme",
1141                                lldb_regnum, (int) unwindplan_registerkind);
1142                    return UnwindLLDB::RegisterSearchResult::eRegisterNotFound;
1143                }
1144            }
1145
1146            if (active_row->GetRegisterInfo (row_regnum, unwindplan_regloc))
1147            {
1148                have_unwindplan_regloc = true;
1149                UnwindLogMsg ("supplying caller's saved reg %d's location using %s UnwindPlan", lldb_regnum,
1150                              m_full_unwind_plan_sp->GetSourceName().GetCString());
1151            }
1152
1153            // This is frame 0 and we're retrieving the PC and it's saved in a Return Address register and
1154            // it hasn't been saved anywhere yet -- that is, it's still live in the actual register.
1155            // Handle this specially.
1156
1157            if (have_unwindplan_regloc == false
1158                && row_register_rewritten_to_return_address_reg == true
1159                && IsFrameZero()
1160                && row_regnum != LLDB_INVALID_REGNUM)
1161            {
1162                uint32_t ra_regnum_in_lldb_reg_numbering;
1163                if (m_thread.GetRegisterContext()->ConvertBetweenRegisterKinds (unwindplan_registerkind, row_regnum, eRegisterKindLLDB, ra_regnum_in_lldb_reg_numbering))
1164                {
1165                    lldb_private::UnwindLLDB::RegisterLocation new_regloc;
1166                    new_regloc.type = UnwindLLDB::RegisterLocation::eRegisterInRegister;
1167                    new_regloc.location.register_number = ra_regnum_in_lldb_reg_numbering;
1168                    m_registers[lldb_regnum] = new_regloc;
1169                    regloc = new_regloc;
1170                    UnwindLogMsg ("supplying caller's register %d from the live RegisterContext at frame 0, saved in %d", lldb_regnum, ra_regnum_in_lldb_reg_numbering);
1171                    return UnwindLLDB::RegisterSearchResult::eRegisterFound;
1172                }
1173            }
1174
1175            // If this architecture stores the return address in a register (it defines a Return Address register)
1176            // and we're on a non-zero stack frame and the Full UnwindPlan says that the pc is stored in the
1177            // RA registers (e.g. lr on arm), then we know that the full unwindplan is not trustworthy -- this
1178            // is an impossible situation and the instruction emulation code has likely been misled.
1179            // If this stack frame meets those criteria, we need to throw away the Full UnwindPlan that the
1180            // instruction emulation came up with and fall back to the architecture's Default UnwindPlan so
1181            // the stack walk can get past this point.
1182
1183            // Special note:  If the Full UnwindPlan was generated from the compiler, don't second-guess it
1184            // when we're at a call site location.
1185
1186            // arch_default_ra_regnum is the return address register # in the Full UnwindPlan register numbering
1187            uint32_t arch_default_ra_regnum = LLDB_INVALID_REGNUM;
1188            if (m_thread.GetRegisterContext()->ConvertBetweenRegisterKinds (eRegisterKindGeneric, LLDB_REGNUM_GENERIC_RA, unwindplan_registerkind, arch_default_ra_regnum)
1189                && arch_default_ra_regnum != LLDB_INVALID_REGNUM
1190                && pc_regnum != LLDB_INVALID_REGNUM
1191                && pc_regnum == lldb_regnum
1192                && unwindplan_regloc.IsInOtherRegister()
1193                && unwindplan_regloc.GetRegisterNumber() == arch_default_ra_regnum
1194                && m_full_unwind_plan_sp->GetSourcedFromCompiler() != eLazyBoolYes
1195                && !m_all_registers_available)
1196            {
1197                UnwindLogMsg ("%s UnwindPlan tried to restore the pc from the link register but this is a non-zero frame",
1198                              m_full_unwind_plan_sp->GetSourceName().GetCString());
1199
1200                // Throw away the full unwindplan; install the arch default unwindplan
1201                if (TryFallbackUnwindPlan())
1202                {
1203                    // Now re-fetch the pc value we're searching for
1204                    uint32_t arch_default_pc_reg = LLDB_INVALID_REGNUM;
1205                    UnwindPlan::RowSP active_row = m_full_unwind_plan_sp->GetRowForFunctionOffset (m_current_offset);
1206                    if (m_thread.GetRegisterContext()->ConvertBetweenRegisterKinds (eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC, m_full_unwind_plan_sp->GetRegisterKind(), arch_default_pc_reg)
1207                        && arch_default_pc_reg != LLDB_INVALID_REGNUM
1208                        && active_row
1209                        && active_row->GetRegisterInfo (arch_default_pc_reg, unwindplan_regloc))
1210                    {
1211                        have_unwindplan_regloc = true;
1212                    }
1213                    else
1214                    {
1215                        have_unwindplan_regloc = false;
1216                    }
1217                }
1218            }
1219        }
1220    }
1221
1222
1223    ExecutionContext exe_ctx(m_thread.shared_from_this());
1224    Process *process = exe_ctx.GetProcessPtr();
1225    if (have_unwindplan_regloc == false)
1226    {
1227        // If a volatile register is being requested, we don't want to forward the next frame's register contents
1228        // up the stack -- the register is not retrievable at this frame.
1229        ABI *abi = process ? process->GetABI().get() : NULL;
1230        if (abi)
1231        {
1232            const RegisterInfo *reg_info = GetRegisterInfoAtIndex(lldb_regnum);
1233            if (reg_info && abi->RegisterIsVolatile (reg_info))
1234            {
1235                UnwindLogMsg ("did not supply reg location for %d (%s) because it is volatile",
1236                    lldb_regnum, reg_info->name ? reg_info->name : "??");
1237                return UnwindLLDB::RegisterSearchResult::eRegisterIsVolatile;
1238            }
1239        }
1240
1241        if (IsFrameZero ())
1242        {
1243            // This is frame 0 - we should return the actual live register context value
1244            lldb_private::UnwindLLDB::RegisterLocation new_regloc;
1245            new_regloc.type = UnwindLLDB::RegisterLocation::eRegisterInRegister;
1246            new_regloc.location.register_number = lldb_regnum;
1247            m_registers[lldb_regnum] = new_regloc;
1248            regloc = new_regloc;
1249            UnwindLogMsg ("supplying caller's register %d from the live RegisterContext at frame 0", lldb_regnum);
1250            return UnwindLLDB::RegisterSearchResult::eRegisterFound;
1251        }
1252        else
1253        UnwindLogMsg ("could not supply caller's reg %d location", lldb_regnum);
1254        return UnwindLLDB::RegisterSearchResult::eRegisterNotFound;
1255    }
1256
1257    // unwindplan_regloc has valid contents about where to retrieve the register
1258    if (unwindplan_regloc.IsUnspecified())
1259    {
1260        lldb_private::UnwindLLDB::RegisterLocation new_regloc;
1261        new_regloc.type = UnwindLLDB::RegisterLocation::eRegisterNotSaved;
1262        m_registers[lldb_regnum] = new_regloc;
1263        UnwindLogMsg ("could not supply caller's reg %d location", lldb_regnum);
1264        return UnwindLLDB::RegisterSearchResult::eRegisterNotFound;
1265    }
1266
1267    if (unwindplan_regloc.IsSame())
1268    {
1269        if (IsFrameZero ())
1270        {
1271            UnwindLogMsg ("could not supply caller's reg %d location", lldb_regnum);
1272            return UnwindLLDB::RegisterSearchResult::eRegisterNotFound;
1273        }
1274        else
1275        {
1276            return UnwindLLDB::RegisterSearchResult::eRegisterNotFound;
1277        }
1278    }
1279
1280    if (unwindplan_regloc.IsCFAPlusOffset())
1281    {
1282        int offset = unwindplan_regloc.GetOffset();
1283        regloc.type = UnwindLLDB::RegisterLocation::eRegisterValueInferred;
1284        regloc.location.inferred_value = m_cfa + offset;
1285        m_registers[lldb_regnum] = regloc;
1286        UnwindLogMsg ("supplying caller's register %d, value is CFA plus offset %d", lldb_regnum, offset);
1287        return UnwindLLDB::RegisterSearchResult::eRegisterFound;
1288    }
1289
1290    if (unwindplan_regloc.IsAtCFAPlusOffset())
1291    {
1292        int offset = unwindplan_regloc.GetOffset();
1293        regloc.type = UnwindLLDB::RegisterLocation::eRegisterSavedAtMemoryLocation;
1294        regloc.location.target_memory_location = m_cfa + offset;
1295        m_registers[lldb_regnum] = regloc;
1296        UnwindLogMsg ("supplying caller's register %d from the stack, saved at CFA plus offset %d", lldb_regnum, offset);
1297        return UnwindLLDB::RegisterSearchResult::eRegisterFound;
1298    }
1299
1300    if (unwindplan_regloc.IsInOtherRegister())
1301    {
1302        uint32_t unwindplan_regnum = unwindplan_regloc.GetRegisterNumber();
1303        uint32_t row_regnum_in_lldb;
1304        if (!m_thread.GetRegisterContext()->ConvertBetweenRegisterKinds (unwindplan_registerkind, unwindplan_regnum, eRegisterKindLLDB, row_regnum_in_lldb))
1305        {
1306            UnwindLogMsg ("could not supply caller's reg %d location", lldb_regnum);
1307            return UnwindLLDB::RegisterSearchResult::eRegisterNotFound;
1308        }
1309        regloc.type = UnwindLLDB::RegisterLocation::eRegisterInRegister;
1310        regloc.location.register_number = row_regnum_in_lldb;
1311        m_registers[lldb_regnum] = regloc;
1312        UnwindLogMsg ("supplying caller's register %d, saved in register %d", lldb_regnum, row_regnum_in_lldb);
1313        return UnwindLLDB::RegisterSearchResult::eRegisterFound;
1314    }
1315
1316    if (unwindplan_regloc.IsDWARFExpression() || unwindplan_regloc.IsAtDWARFExpression())
1317    {
1318        DataExtractor dwarfdata (unwindplan_regloc.GetDWARFExpressionBytes(),
1319                                 unwindplan_regloc.GetDWARFExpressionLength(),
1320                                 process->GetByteOrder(), process->GetAddressByteSize());
1321        ModuleSP opcode_ctx;
1322        DWARFExpression dwarfexpr (opcode_ctx, dwarfdata, 0, unwindplan_regloc.GetDWARFExpressionLength());
1323        dwarfexpr.SetRegisterKind (unwindplan_registerkind);
1324        Value result;
1325        Error error;
1326        if (dwarfexpr.Evaluate (&exe_ctx, NULL, NULL, this, 0, NULL, result, &error))
1327        {
1328            addr_t val;
1329            val = result.GetScalar().ULongLong();
1330            if (unwindplan_regloc.IsDWARFExpression())
1331             {
1332                regloc.type = UnwindLLDB::RegisterLocation::eRegisterValueInferred;
1333                regloc.location.inferred_value = val;
1334                m_registers[lldb_regnum] = regloc;
1335                UnwindLogMsg ("supplying caller's register %d via DWARF expression (IsDWARFExpression)", lldb_regnum);
1336                return UnwindLLDB::RegisterSearchResult::eRegisterFound;
1337            }
1338            else
1339            {
1340                regloc.type = UnwindLLDB::RegisterLocation::eRegisterSavedAtMemoryLocation;
1341                regloc.location.target_memory_location = val;
1342                m_registers[lldb_regnum] = regloc;
1343                UnwindLogMsg ("supplying caller's register %d via DWARF expression (IsAtDWARFExpression)", lldb_regnum);
1344                return UnwindLLDB::RegisterSearchResult::eRegisterFound;
1345            }
1346        }
1347        UnwindLogMsg ("tried to use IsDWARFExpression or IsAtDWARFExpression for reg %d but failed", lldb_regnum);
1348        return UnwindLLDB::RegisterSearchResult::eRegisterNotFound;
1349    }
1350
1351    UnwindLogMsg ("could not supply caller's reg %d location", lldb_regnum);
1352
1353    // FIXME UnwindPlan::Row types atDWARFExpression and isDWARFExpression are unsupported.
1354
1355    return UnwindLLDB::RegisterSearchResult::eRegisterNotFound;
1356}
1357
1358// If the Full unwindplan has been determined to be incorrect, this method will
1359// replace it with the architecture's default unwindplan, if one is defined.
1360// It will also find the FuncUnwinders object for this function and replace the
1361// Full unwind method for the function there so we don't use the errant Full unwindplan
1362// again in the future of this debug session.
1363// We're most likely doing this because the Full unwindplan was generated by assembly
1364// instruction profiling and the profiler got something wrong.
1365
1366bool
1367RegisterContextLLDB::TryFallbackUnwindPlan ()
1368{
1369    UnwindPlan::Row::RegisterLocation unwindplan_regloc;
1370    if (m_fallback_unwind_plan_sp.get() == NULL)
1371        return false;
1372
1373    UnwindPlanSP original_full_unwind_plan_sp = m_full_unwind_plan_sp;
1374    UnwindPlan::RowSP active_row = m_fallback_unwind_plan_sp->GetRowForFunctionOffset (m_current_offset);
1375
1376    if (active_row && active_row->GetCFARegister() != LLDB_INVALID_REGNUM)
1377    {
1378        FuncUnwindersSP func_unwinders_sp;
1379        if (m_sym_ctx_valid && m_current_pc.IsValid() && m_current_pc.GetModule())
1380        {
1381            func_unwinders_sp = m_current_pc.GetModule()->GetObjectFile()->GetUnwindTable().GetFuncUnwindersContainingAddress (m_current_pc, m_sym_ctx);
1382            if (func_unwinders_sp)
1383            {
1384                func_unwinders_sp->InvalidateNonCallSiteUnwindPlan (m_thread);
1385            }
1386        }
1387        m_registers.clear();
1388        m_full_unwind_plan_sp = m_fallback_unwind_plan_sp;
1389        addr_t cfa_regval = LLDB_INVALID_ADDRESS;
1390        if (ReadGPRValue (m_fallback_unwind_plan_sp->GetRegisterKind(), active_row->GetCFARegister(), cfa_regval))
1391        {
1392            m_cfa = cfa_regval + active_row->GetCFAOffset ();
1393        }
1394
1395        UnwindLogMsg ("full unwind plan '%s' has been replaced by architecture default unwind plan '%s' for this function from now on.",
1396                      original_full_unwind_plan_sp->GetSourceName().GetCString(), m_fallback_unwind_plan_sp->GetSourceName().GetCString());
1397        m_fallback_unwind_plan_sp.reset();
1398    }
1399
1400    return true;
1401}
1402
1403// Retrieve a general purpose register value for THIS frame, as saved by the NEXT frame, i.e. the frame that
1404// this frame called.  e.g.
1405//
1406//  foo () { }
1407//  bar () { foo (); }
1408//  main () { bar (); }
1409//
1410//  stopped in foo() so
1411//     frame 0 - foo
1412//     frame 1 - bar
1413//     frame 2 - main
1414//  and this RegisterContext is for frame 1 (bar) - if we want to get the pc value for frame 1, we need to ask
1415//  where frame 0 (the "next" frame) saved that and retrieve the value.
1416
1417bool
1418RegisterContextLLDB::ReadGPRValue (int register_kind, uint32_t regnum, addr_t &value)
1419{
1420    if (!IsValid())
1421        return false;
1422
1423    uint32_t lldb_regnum;
1424    if (register_kind == eRegisterKindLLDB)
1425    {
1426        lldb_regnum = regnum;
1427    }
1428    else if (!m_thread.GetRegisterContext()->ConvertBetweenRegisterKinds (register_kind, regnum, eRegisterKindLLDB, lldb_regnum))
1429    {
1430        return false;
1431    }
1432
1433    const RegisterInfo *reg_info = GetRegisterInfoAtIndex(lldb_regnum);
1434    RegisterValue reg_value;
1435    // if this is frame 0 (currently executing frame), get the requested reg contents from the actual thread registers
1436    if (IsFrameZero ())
1437    {
1438        if (m_thread.GetRegisterContext()->ReadRegister (reg_info, reg_value))
1439        {
1440            value = reg_value.GetAsUInt64();
1441            return true;
1442        }
1443        return false;
1444    }
1445
1446    bool pc_register = false;
1447    uint32_t generic_regnum;
1448    if (register_kind == eRegisterKindGeneric && regnum == LLDB_REGNUM_GENERIC_PC)
1449    {
1450        pc_register = true;
1451    }
1452    else if (m_thread.GetRegisterContext()->ConvertBetweenRegisterKinds (register_kind, regnum, eRegisterKindGeneric, generic_regnum)
1453             && generic_regnum == LLDB_REGNUM_GENERIC_PC)
1454    {
1455        pc_register = true;
1456    }
1457
1458    lldb_private::UnwindLLDB::RegisterLocation regloc;
1459    if (!m_parent_unwind.SearchForSavedLocationForRegister (lldb_regnum, regloc, m_frame_number - 1, pc_register))
1460    {
1461        return false;
1462    }
1463    if (ReadRegisterValueFromRegisterLocation (regloc, reg_info, reg_value))
1464    {
1465        value = reg_value.GetAsUInt64();
1466        return true;
1467    }
1468    return false;
1469}
1470
1471// Find the value of a register in THIS frame
1472
1473bool
1474RegisterContextLLDB::ReadRegister (const RegisterInfo *reg_info, RegisterValue &value)
1475{
1476    if (!IsValid())
1477        return false;
1478
1479    const uint32_t lldb_regnum = reg_info->kinds[eRegisterKindLLDB];
1480    UnwindLogMsgVerbose ("looking for register saved location for reg %d", lldb_regnum);
1481
1482    // If this is the 0th frame, hand this over to the live register context
1483    if (IsFrameZero ())
1484    {
1485        UnwindLogMsgVerbose ("passing along to the live register context for reg %d", lldb_regnum);
1486        return m_thread.GetRegisterContext()->ReadRegister (reg_info, value);
1487    }
1488
1489    lldb_private::UnwindLLDB::RegisterLocation regloc;
1490    // Find out where the NEXT frame saved THIS frame's register contents
1491    if (!m_parent_unwind.SearchForSavedLocationForRegister (lldb_regnum, regloc, m_frame_number - 1, false))
1492        return false;
1493
1494    return ReadRegisterValueFromRegisterLocation (regloc, reg_info, value);
1495}
1496
1497bool
1498RegisterContextLLDB::WriteRegister (const RegisterInfo *reg_info, const RegisterValue &value)
1499{
1500    if (!IsValid())
1501        return false;
1502
1503    const uint32_t lldb_regnum = reg_info->kinds[eRegisterKindLLDB];
1504    UnwindLogMsgVerbose ("looking for register saved location for reg %d", lldb_regnum);
1505
1506    // If this is the 0th frame, hand this over to the live register context
1507    if (IsFrameZero ())
1508    {
1509        UnwindLogMsgVerbose ("passing along to the live register context for reg %d", lldb_regnum);
1510        return m_thread.GetRegisterContext()->WriteRegister (reg_info, value);
1511    }
1512
1513    lldb_private::UnwindLLDB::RegisterLocation regloc;
1514    // Find out where the NEXT frame saved THIS frame's register contents
1515    if (!m_parent_unwind.SearchForSavedLocationForRegister (lldb_regnum, regloc, m_frame_number - 1, false))
1516        return false;
1517
1518    return WriteRegisterValueToRegisterLocation (regloc, reg_info, value);
1519}
1520
1521// Don't need to implement this one
1522bool
1523RegisterContextLLDB::ReadAllRegisterValues (lldb::DataBufferSP &data_sp)
1524{
1525    return false;
1526}
1527
1528// Don't need to implement this one
1529bool
1530RegisterContextLLDB::WriteAllRegisterValues (const lldb::DataBufferSP& data_sp)
1531{
1532    return false;
1533}
1534
1535// Retrieve the pc value for THIS from
1536
1537bool
1538RegisterContextLLDB::GetCFA (addr_t& cfa)
1539{
1540    if (!IsValid())
1541    {
1542        return false;
1543    }
1544    if (m_cfa == LLDB_INVALID_ADDRESS)
1545    {
1546        return false;
1547    }
1548    cfa = m_cfa;
1549    return true;
1550}
1551
1552
1553RegisterContextLLDB::SharedPtr
1554RegisterContextLLDB::GetNextFrame () const
1555{
1556    RegisterContextLLDB::SharedPtr regctx;
1557    if (m_frame_number == 0)
1558      return regctx;
1559    return m_parent_unwind.GetRegisterContextForFrameNum (m_frame_number - 1);
1560}
1561
1562RegisterContextLLDB::SharedPtr
1563RegisterContextLLDB::GetPrevFrame () const
1564{
1565    RegisterContextLLDB::SharedPtr regctx;
1566    return m_parent_unwind.GetRegisterContextForFrameNum (m_frame_number + 1);
1567}
1568
1569// Retrieve the address of the start of the function of THIS frame
1570
1571bool
1572RegisterContextLLDB::GetStartPC (addr_t& start_pc)
1573{
1574    if (!IsValid())
1575        return false;
1576
1577    if (!m_start_pc.IsValid())
1578    {
1579        return ReadPC (start_pc);
1580    }
1581    start_pc = m_start_pc.GetLoadAddress (CalculateTarget().get());
1582    return true;
1583}
1584
1585// Retrieve the current pc value for THIS frame, as saved by the NEXT frame.
1586
1587bool
1588RegisterContextLLDB::ReadPC (addr_t& pc)
1589{
1590    if (!IsValid())
1591        return false;
1592
1593    if (ReadGPRValue (eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC, pc))
1594    {
1595        // A pc value of 0 or 1 is impossible in the middle of the stack -- it indicates the end of a stack walk.
1596        // On the currently executing frame (or such a frame interrupted asynchronously by sigtramp et al) this may
1597        // occur if code has jumped through a NULL pointer -- we want to be able to unwind past that frame to help
1598        // find the bug.
1599
1600        if (m_all_registers_available == false
1601            && (pc == 0 || pc == 1))
1602        {
1603            return false;
1604        }
1605        else
1606        {
1607            return true;
1608        }
1609    }
1610    else
1611    {
1612        return false;
1613    }
1614}
1615
1616
1617void
1618RegisterContextLLDB::UnwindLogMsg (const char *fmt, ...)
1619{
1620    Log *log(GetLogIfAllCategoriesSet (LIBLLDB_LOG_UNWIND));
1621    if (log)
1622    {
1623        va_list args;
1624        va_start (args, fmt);
1625
1626        char *logmsg;
1627        if (vasprintf (&logmsg, fmt, args) == -1 || logmsg == NULL)
1628        {
1629            if (logmsg)
1630                free (logmsg);
1631            va_end (args);
1632            return;
1633        }
1634        va_end (args);
1635
1636        log->Printf ("%*sth%d/fr%u %s",
1637                      m_frame_number < 100 ? m_frame_number : 100, "", m_thread.GetIndexID(), m_frame_number,
1638                      logmsg);
1639        free (logmsg);
1640    }
1641}
1642
1643void
1644RegisterContextLLDB::UnwindLogMsgVerbose (const char *fmt, ...)
1645{
1646    Log *log(GetLogIfAllCategoriesSet (LIBLLDB_LOG_UNWIND));
1647    if (log && log->GetVerbose())
1648    {
1649        va_list args;
1650        va_start (args, fmt);
1651
1652        char *logmsg;
1653        if (vasprintf (&logmsg, fmt, args) == -1 || logmsg == NULL)
1654        {
1655            if (logmsg)
1656                free (logmsg);
1657            va_end (args);
1658            return;
1659        }
1660        va_end (args);
1661
1662        log->Printf ("%*sth%d/fr%u %s",
1663                      m_frame_number < 100 ? m_frame_number : 100, "", m_thread.GetIndexID(), m_frame_number,
1664                      logmsg);
1665        free (logmsg);
1666    }
1667}
1668
1669
1670