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