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