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