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