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("Using fast unwind plan '%s'",
546                    m_fast_unwind_plan_sp->GetSourceName().AsCString());
547       UnwindLogMsg("active row: %s", active_row_strm.GetData());
548     }
549   } else {
550     m_full_unwind_plan_sp = GetFullUnwindPlanForFrame();
551     int valid_offset = -1;
552     if (IsUnwindPlanValidForCurrentPC(m_full_unwind_plan_sp, valid_offset)) {
553       active_row = m_full_unwind_plan_sp->GetRowForFunctionOffset(valid_offset);
554       row_register_kind = m_full_unwind_plan_sp->GetRegisterKind();
555       PropagateTrapHandlerFlagFromUnwindPlan(m_full_unwind_plan_sp);
556       if (active_row.get() && log) {
557         StreamString active_row_strm;
558         active_row->Dump(active_row_strm, m_full_unwind_plan_sp.get(),
559                          &m_thread,
560                          m_start_pc.GetLoadAddress(exe_ctx.GetTargetPtr()));
561         UnwindLogMsg("Using full unwind plan '%s'",
562                      m_full_unwind_plan_sp->GetSourceName().AsCString());
563         UnwindLogMsg("active row: %s", active_row_strm.GetData());
564       }
565     }
566   }
567 
568   if (!active_row.get()) {
569     m_frame_type = eNotAValidFrame;
570     UnwindLogMsg("could not find unwind row for this pc");
571     return;
572   }
573 
574   if (!ReadFrameAddress(row_register_kind, active_row->GetCFAValue(), m_cfa)) {
575     UnwindLogMsg("failed to get cfa");
576     m_frame_type = eNotAValidFrame;
577     return;
578   }
579 
580   ReadFrameAddress(row_register_kind, active_row->GetAFAValue(), m_afa);
581 
582   UnwindLogMsg("m_cfa = 0x%" PRIx64 " m_afa = 0x%" PRIx64, m_cfa, m_afa);
583 
584   if (CheckIfLoopingStack()) {
585     TryFallbackUnwindPlan();
586     if (CheckIfLoopingStack()) {
587       UnwindLogMsg("same CFA address as next frame, assuming the unwind is "
588                    "looping - stopping");
589       m_frame_type = eNotAValidFrame;
590       return;
591     }
592   }
593 
594   UnwindLogMsg("initialized frame current pc is 0x%" PRIx64
595                " cfa is 0x%" PRIx64 " afa is 0x%" PRIx64,
596                (uint64_t)m_current_pc.GetLoadAddress(exe_ctx.GetTargetPtr()),
597                (uint64_t)m_cfa,
598                (uint64_t)m_afa);
599 }
600 
601 bool RegisterContextUnwind::CheckIfLoopingStack() {
602   // If we have a bad stack setup, we can get the same CFA value multiple times
603   // -- or even more devious, we can actually oscillate between two CFA values.
604   // Detect that here and break out to avoid a possible infinite loop in lldb
605   // trying to unwind the stack. To detect when we have the same CFA value
606   // multiple times, we compare the
607   // CFA of the current
608   // frame with the 2nd next frame because in some specail case (e.g. signal
609   // hanlders, hand written assembly without ABI compliance) we can have 2
610   // frames with the same
611   // CFA (in theory we
612   // can have arbitrary number of frames with the same CFA, but more then 2 is
613   // very very unlikely)
614 
615   RegisterContextUnwind::SharedPtr next_frame = GetNextFrame();
616   if (next_frame) {
617     RegisterContextUnwind::SharedPtr next_next_frame =
618         next_frame->GetNextFrame();
619     addr_t next_next_frame_cfa = LLDB_INVALID_ADDRESS;
620     if (next_next_frame && next_next_frame->GetCFA(next_next_frame_cfa)) {
621       if (next_next_frame_cfa == m_cfa) {
622         // We have a loop in the stack unwind
623         return true;
624       }
625     }
626   }
627   return false;
628 }
629 
630 bool RegisterContextUnwind::IsFrameZero() const { return m_frame_number == 0; }
631 
632 // Find a fast unwind plan for this frame, if possible.
633 //
634 // On entry to this method,
635 //
636 //   1. m_frame_type should already be set to eTrapHandlerFrame/eDebuggerFrame
637 //   if either of those are correct,
638 //   2. m_sym_ctx should already be filled in, and
639 //   3. m_current_pc should have the current pc value for this frame
640 //   4. m_current_offset_backed_up_one should have the current byte offset into
641 //   the function, maybe backed up by 1, -1 if unknown
642 
643 UnwindPlanSP RegisterContextUnwind::GetFastUnwindPlanForFrame() {
644   UnwindPlanSP unwind_plan_sp;
645   ModuleSP pc_module_sp(m_current_pc.GetModule());
646 
647   if (!m_current_pc.IsValid() || !pc_module_sp ||
648       pc_module_sp->GetObjectFile() == nullptr)
649     return unwind_plan_sp;
650 
651   if (IsFrameZero())
652     return unwind_plan_sp;
653 
654   FuncUnwindersSP func_unwinders_sp(
655       pc_module_sp->GetUnwindTable().GetFuncUnwindersContainingAddress(
656           m_current_pc, m_sym_ctx));
657   if (!func_unwinders_sp)
658     return unwind_plan_sp;
659 
660   // If we're in _sigtramp(), unwinding past this frame requires special
661   // knowledge.
662   if (m_frame_type == eTrapHandlerFrame || m_frame_type == eDebuggerFrame)
663     return unwind_plan_sp;
664 
665   unwind_plan_sp = func_unwinders_sp->GetUnwindPlanFastUnwind(
666       *m_thread.CalculateTarget(), m_thread);
667   if (unwind_plan_sp) {
668     if (unwind_plan_sp->PlanValidAtAddress(m_current_pc)) {
669       m_frame_type = eNormalFrame;
670       return unwind_plan_sp;
671     } else {
672       unwind_plan_sp.reset();
673     }
674   }
675   return unwind_plan_sp;
676 }
677 
678 // On entry to this method,
679 //
680 //   1. m_frame_type should already be set to eTrapHandlerFrame/eDebuggerFrame
681 //   if either of those are correct,
682 //   2. m_sym_ctx should already be filled in, and
683 //   3. m_current_pc should have the current pc value for this frame
684 //   4. m_current_offset_backed_up_one should have the current byte offset into
685 //   the function, maybe backed up by 1, -1 if unknown
686 
687 UnwindPlanSP RegisterContextUnwind::GetFullUnwindPlanForFrame() {
688   UnwindPlanSP unwind_plan_sp;
689   UnwindPlanSP arch_default_unwind_plan_sp;
690   ExecutionContext exe_ctx(m_thread.shared_from_this());
691   Process *process = exe_ctx.GetProcessPtr();
692   ABI *abi = process ? process->GetABI().get() : nullptr;
693   if (abi) {
694     arch_default_unwind_plan_sp =
695         std::make_shared<UnwindPlan>(lldb::eRegisterKindGeneric);
696     abi->CreateDefaultUnwindPlan(*arch_default_unwind_plan_sp);
697   } else {
698     UnwindLogMsg(
699         "unable to get architectural default UnwindPlan from ABI plugin");
700   }
701 
702   bool behaves_like_zeroth_frame = false;
703   if (IsFrameZero() || GetNextFrame()->m_frame_type == eTrapHandlerFrame ||
704       GetNextFrame()->m_frame_type == eDebuggerFrame) {
705     behaves_like_zeroth_frame = true;
706     // If this frame behaves like a 0th frame (currently executing or
707     // interrupted asynchronously), all registers can be retrieved.
708     m_all_registers_available = true;
709   }
710 
711   // If we've done a jmp 0x0 / bl 0x0 (called through a null function pointer)
712   // so the pc is 0x0 in the zeroth frame, we need to use the "unwind at first
713   // instruction" arch default UnwindPlan Also, if this Process can report on
714   // memory region attributes, any non-executable region means we jumped
715   // through a bad function pointer - handle the same way as 0x0. Note, if we
716   // have a symbol context & a symbol, we don't want to follow this code path.
717   // This is for jumping to memory regions without any information available.
718 
719   if ((!m_sym_ctx_valid ||
720        (m_sym_ctx.function == nullptr && m_sym_ctx.symbol == nullptr)) &&
721       behaves_like_zeroth_frame && m_current_pc.IsValid()) {
722     uint32_t permissions;
723     addr_t current_pc_addr =
724         m_current_pc.GetLoadAddress(exe_ctx.GetTargetPtr());
725     if (current_pc_addr == 0 ||
726         (process &&
727          process->GetLoadAddressPermissions(current_pc_addr, permissions) &&
728          (permissions & ePermissionsExecutable) == 0)) {
729       if (abi) {
730         unwind_plan_sp =
731             std::make_shared<UnwindPlan>(lldb::eRegisterKindGeneric);
732         abi->CreateFunctionEntryUnwindPlan(*unwind_plan_sp);
733         m_frame_type = eNormalFrame;
734         return unwind_plan_sp;
735       }
736     }
737   }
738 
739   // No Module for the current pc, try using the architecture default unwind.
740   ModuleSP pc_module_sp(m_current_pc.GetModule());
741   if (!m_current_pc.IsValid() || !pc_module_sp ||
742       pc_module_sp->GetObjectFile() == nullptr) {
743     m_frame_type = eNormalFrame;
744     return arch_default_unwind_plan_sp;
745   }
746 
747   FuncUnwindersSP func_unwinders_sp;
748   if (m_sym_ctx_valid) {
749     func_unwinders_sp =
750         pc_module_sp->GetUnwindTable().GetFuncUnwindersContainingAddress(
751             m_current_pc, m_sym_ctx);
752   }
753 
754   // No FuncUnwinders available for this pc (stripped function symbols, lldb
755   // could not augment its function table with another source, like
756   // LC_FUNCTION_STARTS or eh_frame in ObjectFileMachO). See if eh_frame or the
757   // .ARM.exidx tables have unwind information for this address, else fall back
758   // to the architectural default unwind.
759   if (!func_unwinders_sp) {
760     m_frame_type = eNormalFrame;
761 
762     if (!pc_module_sp || !pc_module_sp->GetObjectFile() ||
763         !m_current_pc.IsValid())
764       return arch_default_unwind_plan_sp;
765 
766     // Even with -fomit-frame-pointer, we can try eh_frame to get back on
767     // track.
768     DWARFCallFrameInfo *eh_frame =
769         pc_module_sp->GetUnwindTable().GetEHFrameInfo();
770     if (eh_frame) {
771       unwind_plan_sp = std::make_shared<UnwindPlan>(lldb::eRegisterKindGeneric);
772       if (eh_frame->GetUnwindPlan(m_current_pc, *unwind_plan_sp))
773         return unwind_plan_sp;
774       else
775         unwind_plan_sp.reset();
776     }
777 
778     ArmUnwindInfo *arm_exidx =
779         pc_module_sp->GetUnwindTable().GetArmUnwindInfo();
780     if (arm_exidx) {
781       unwind_plan_sp = std::make_shared<UnwindPlan>(lldb::eRegisterKindGeneric);
782       if (arm_exidx->GetUnwindPlan(exe_ctx.GetTargetRef(), m_current_pc,
783                                    *unwind_plan_sp))
784         return unwind_plan_sp;
785       else
786         unwind_plan_sp.reset();
787     }
788 
789     CallFrameInfo *object_file_unwind =
790         pc_module_sp->GetUnwindTable().GetObjectFileUnwindInfo();
791     if (object_file_unwind) {
792       unwind_plan_sp = std::make_shared<UnwindPlan>(lldb::eRegisterKindGeneric);
793       if (object_file_unwind->GetUnwindPlan(m_current_pc, *unwind_plan_sp))
794         return unwind_plan_sp;
795       else
796         unwind_plan_sp.reset();
797     }
798 
799     return arch_default_unwind_plan_sp;
800   }
801 
802   // If we're in _sigtramp(), unwinding past this frame requires special
803   // knowledge.  On Mac OS X this knowledge is properly encoded in the eh_frame
804   // section, so prefer that if available. On other platforms we may need to
805   // provide a platform-specific UnwindPlan which encodes the details of how to
806   // unwind out of sigtramp.
807   if (m_frame_type == eTrapHandlerFrame && process) {
808     m_fast_unwind_plan_sp.reset();
809     unwind_plan_sp =
810         func_unwinders_sp->GetEHFrameUnwindPlan(process->GetTarget());
811     if (!unwind_plan_sp)
812       unwind_plan_sp =
813           func_unwinders_sp->GetObjectFileUnwindPlan(process->GetTarget());
814     if (unwind_plan_sp && unwind_plan_sp->PlanValidAtAddress(m_current_pc) &&
815         unwind_plan_sp->GetSourcedFromCompiler() == eLazyBoolYes) {
816       return unwind_plan_sp;
817     }
818   }
819 
820   // Ask the DynamicLoader if the eh_frame CFI should be trusted in this frame
821   // even when it's frame zero This comes up if we have hand-written functions
822   // in a Module and hand-written eh_frame.  The assembly instruction
823   // inspection may fail and the eh_frame CFI were probably written with some
824   // care to do the right thing.  It'd be nice if there was a way to ask the
825   // eh_frame directly if it is asynchronous (can be trusted at every
826   // instruction point) or synchronous (the normal case - only at call sites).
827   // But there is not.
828   if (process && process->GetDynamicLoader() &&
829       process->GetDynamicLoader()->AlwaysRelyOnEHUnwindInfo(m_sym_ctx)) {
830     // We must specifically call the GetEHFrameUnwindPlan() method here --
831     // normally we would call GetUnwindPlanAtCallSite() -- because CallSite may
832     // return an unwind plan sourced from either eh_frame (that's what we
833     // intend) or compact unwind (this won't work)
834     unwind_plan_sp =
835         func_unwinders_sp->GetEHFrameUnwindPlan(process->GetTarget());
836     if (!unwind_plan_sp)
837       unwind_plan_sp =
838           func_unwinders_sp->GetObjectFileUnwindPlan(process->GetTarget());
839     if (unwind_plan_sp && unwind_plan_sp->PlanValidAtAddress(m_current_pc)) {
840       UnwindLogMsgVerbose("frame uses %s for full UnwindPlan because the "
841                           "DynamicLoader suggested we prefer it",
842                           unwind_plan_sp->GetSourceName().GetCString());
843       return unwind_plan_sp;
844     }
845   }
846 
847   // Typically the NonCallSite UnwindPlan is the unwind created by inspecting
848   // the assembly language instructions
849   if (behaves_like_zeroth_frame && process) {
850     unwind_plan_sp = func_unwinders_sp->GetUnwindPlanAtNonCallSite(
851         process->GetTarget(), m_thread);
852     if (unwind_plan_sp && unwind_plan_sp->PlanValidAtAddress(m_current_pc)) {
853       if (unwind_plan_sp->GetSourcedFromCompiler() == eLazyBoolNo) {
854         // We probably have an UnwindPlan created by inspecting assembly
855         // instructions. The assembly profilers work really well with compiler-
856         // generated functions but hand- written assembly can be problematic.
857         // We set the eh_frame based unwind plan as our fallback unwind plan if
858         // instruction emulation doesn't work out even for non call sites if it
859         // is available and use the architecture default unwind plan if it is
860         // not available. The eh_frame unwind plan is more reliable even on non
861         // call sites then the architecture default plan and for hand written
862         // assembly code it is often written in a way that it valid at all
863         // location what helps in the most common cases when the instruction
864         // emulation fails.
865         UnwindPlanSP call_site_unwind_plan =
866             func_unwinders_sp->GetUnwindPlanAtCallSite(process->GetTarget(),
867                                                        m_thread);
868         if (call_site_unwind_plan &&
869             call_site_unwind_plan.get() != unwind_plan_sp.get() &&
870             call_site_unwind_plan->GetSourceName() !=
871                 unwind_plan_sp->GetSourceName()) {
872           m_fallback_unwind_plan_sp = call_site_unwind_plan;
873         } else {
874           m_fallback_unwind_plan_sp = arch_default_unwind_plan_sp;
875         }
876       }
877       UnwindLogMsgVerbose("frame uses %s for full UnwindPlan because this "
878                           "is the non-call site unwind plan and this is a "
879                           "zeroth frame",
880                           unwind_plan_sp->GetSourceName().GetCString());
881       return unwind_plan_sp;
882     }
883 
884     // If we're on the first instruction of a function, and we have an
885     // architectural default UnwindPlan for the initial instruction of a
886     // function, use that.
887     if (m_current_offset == 0) {
888       unwind_plan_sp =
889           func_unwinders_sp->GetUnwindPlanArchitectureDefaultAtFunctionEntry(
890               m_thread);
891       if (unwind_plan_sp) {
892         UnwindLogMsgVerbose("frame uses %s for full UnwindPlan because we are at "
893                             "the first instruction of a function",
894                             unwind_plan_sp->GetSourceName().GetCString());
895         return unwind_plan_sp;
896       }
897     }
898   }
899 
900   // Typically this is unwind info from an eh_frame section intended for
901   // exception handling; only valid at call sites
902   if (process) {
903     unwind_plan_sp = func_unwinders_sp->GetUnwindPlanAtCallSite(
904         process->GetTarget(), m_thread);
905   }
906   int valid_offset = -1;
907   if (IsUnwindPlanValidForCurrentPC(unwind_plan_sp, valid_offset)) {
908     UnwindLogMsgVerbose("frame uses %s for full UnwindPlan because this "
909                         "is the call-site unwind plan",
910                         unwind_plan_sp->GetSourceName().GetCString());
911     return unwind_plan_sp;
912   }
913 
914   // We'd prefer to use an UnwindPlan intended for call sites when we're at a
915   // call site but if we've struck out on that, fall back to using the non-
916   // call-site assembly inspection UnwindPlan if possible.
917   if (process) {
918     unwind_plan_sp = func_unwinders_sp->GetUnwindPlanAtNonCallSite(
919         process->GetTarget(), m_thread);
920   }
921   if (unwind_plan_sp &&
922       unwind_plan_sp->GetSourcedFromCompiler() == eLazyBoolNo) {
923     // We probably have an UnwindPlan created by inspecting assembly
924     // instructions. The assembly profilers work really well with compiler-
925     // generated functions but hand- written assembly can be problematic. We
926     // set the eh_frame based unwind plan as our fallback unwind plan if
927     // instruction emulation doesn't work out even for non call sites if it is
928     // available and use the architecture default unwind plan if it is not
929     // available. The eh_frame unwind plan is more reliable even on non call
930     // sites then the architecture default plan and for hand written assembly
931     // code it is often written in a way that it valid at all location what
932     // helps in the most common cases when the instruction emulation fails.
933     UnwindPlanSP call_site_unwind_plan =
934         func_unwinders_sp->GetUnwindPlanAtCallSite(process->GetTarget(),
935                                                    m_thread);
936     if (call_site_unwind_plan &&
937         call_site_unwind_plan.get() != unwind_plan_sp.get() &&
938         call_site_unwind_plan->GetSourceName() !=
939             unwind_plan_sp->GetSourceName()) {
940       m_fallback_unwind_plan_sp = call_site_unwind_plan;
941     } else {
942       m_fallback_unwind_plan_sp = arch_default_unwind_plan_sp;
943     }
944   }
945 
946   if (IsUnwindPlanValidForCurrentPC(unwind_plan_sp, valid_offset)) {
947     UnwindLogMsgVerbose("frame uses %s for full UnwindPlan because we "
948                         "failed to find a call-site unwind plan that would work",
949                         unwind_plan_sp->GetSourceName().GetCString());
950     return unwind_plan_sp;
951   }
952 
953   // If nothing else, use the architectural default UnwindPlan and hope that
954   // does the job.
955   if (arch_default_unwind_plan_sp)
956     UnwindLogMsgVerbose(
957         "frame uses %s for full UnwindPlan because we are falling back "
958         "to the arch default plan",
959         arch_default_unwind_plan_sp->GetSourceName().GetCString());
960   else
961     UnwindLogMsg(
962         "Unable to find any UnwindPlan for full unwind of this frame.");
963 
964   return arch_default_unwind_plan_sp;
965 }
966 
967 void RegisterContextUnwind::InvalidateAllRegisters() {
968   m_frame_type = eNotAValidFrame;
969 }
970 
971 size_t RegisterContextUnwind::GetRegisterCount() {
972   return m_thread.GetRegisterContext()->GetRegisterCount();
973 }
974 
975 const RegisterInfo *RegisterContextUnwind::GetRegisterInfoAtIndex(size_t reg) {
976   return m_thread.GetRegisterContext()->GetRegisterInfoAtIndex(reg);
977 }
978 
979 size_t RegisterContextUnwind::GetRegisterSetCount() {
980   return m_thread.GetRegisterContext()->GetRegisterSetCount();
981 }
982 
983 const RegisterSet *RegisterContextUnwind::GetRegisterSet(size_t reg_set) {
984   return m_thread.GetRegisterContext()->GetRegisterSet(reg_set);
985 }
986 
987 uint32_t RegisterContextUnwind::ConvertRegisterKindToRegisterNumber(
988     lldb::RegisterKind kind, uint32_t num) {
989   return m_thread.GetRegisterContext()->ConvertRegisterKindToRegisterNumber(
990       kind, num);
991 }
992 
993 bool RegisterContextUnwind::ReadRegisterValueFromRegisterLocation(
994     lldb_private::UnwindLLDB::RegisterLocation regloc,
995     const RegisterInfo *reg_info, RegisterValue &value) {
996   if (!IsValid())
997     return false;
998   bool success = false;
999 
1000   switch (regloc.type) {
1001   case UnwindLLDB::RegisterLocation::eRegisterInLiveRegisterContext: {
1002     const RegisterInfo *other_reg_info =
1003         GetRegisterInfoAtIndex(regloc.location.register_number);
1004 
1005     if (!other_reg_info)
1006       return false;
1007 
1008     success =
1009         m_thread.GetRegisterContext()->ReadRegister(other_reg_info, value);
1010   } break;
1011   case UnwindLLDB::RegisterLocation::eRegisterInRegister: {
1012     const RegisterInfo *other_reg_info =
1013         GetRegisterInfoAtIndex(regloc.location.register_number);
1014 
1015     if (!other_reg_info)
1016       return false;
1017 
1018     if (IsFrameZero()) {
1019       success =
1020           m_thread.GetRegisterContext()->ReadRegister(other_reg_info, value);
1021     } else {
1022       success = GetNextFrame()->ReadRegister(other_reg_info, value);
1023     }
1024   } break;
1025   case UnwindLLDB::RegisterLocation::eRegisterValueInferred:
1026     success =
1027         value.SetUInt(regloc.location.inferred_value, reg_info->byte_size);
1028     break;
1029 
1030   case UnwindLLDB::RegisterLocation::eRegisterNotSaved:
1031     break;
1032   case UnwindLLDB::RegisterLocation::eRegisterSavedAtHostMemoryLocation:
1033     llvm_unreachable("FIXME debugger inferior function call unwind");
1034   case UnwindLLDB::RegisterLocation::eRegisterSavedAtMemoryLocation: {
1035     Status error(ReadRegisterValueFromMemory(
1036         reg_info, regloc.location.target_memory_location, reg_info->byte_size,
1037         value));
1038     success = error.Success();
1039   } break;
1040   default:
1041     llvm_unreachable("Unknown RegisterLocation type.");
1042   }
1043   return success;
1044 }
1045 
1046 bool RegisterContextUnwind::WriteRegisterValueToRegisterLocation(
1047     lldb_private::UnwindLLDB::RegisterLocation regloc,
1048     const RegisterInfo *reg_info, const RegisterValue &value) {
1049   if (!IsValid())
1050     return false;
1051 
1052   bool success = false;
1053 
1054   switch (regloc.type) {
1055   case UnwindLLDB::RegisterLocation::eRegisterInLiveRegisterContext: {
1056     const RegisterInfo *other_reg_info =
1057         GetRegisterInfoAtIndex(regloc.location.register_number);
1058     success =
1059         m_thread.GetRegisterContext()->WriteRegister(other_reg_info, value);
1060   } break;
1061   case UnwindLLDB::RegisterLocation::eRegisterInRegister: {
1062     const RegisterInfo *other_reg_info =
1063         GetRegisterInfoAtIndex(regloc.location.register_number);
1064     if (IsFrameZero()) {
1065       success =
1066           m_thread.GetRegisterContext()->WriteRegister(other_reg_info, value);
1067     } else {
1068       success = GetNextFrame()->WriteRegister(other_reg_info, value);
1069     }
1070   } break;
1071   case UnwindLLDB::RegisterLocation::eRegisterValueInferred:
1072   case UnwindLLDB::RegisterLocation::eRegisterNotSaved:
1073     break;
1074   case UnwindLLDB::RegisterLocation::eRegisterSavedAtHostMemoryLocation:
1075     llvm_unreachable("FIXME debugger inferior function call unwind");
1076   case UnwindLLDB::RegisterLocation::eRegisterSavedAtMemoryLocation: {
1077     Status error(WriteRegisterValueToMemory(
1078         reg_info, regloc.location.target_memory_location, reg_info->byte_size,
1079         value));
1080     success = error.Success();
1081   } break;
1082   default:
1083     llvm_unreachable("Unknown RegisterLocation type.");
1084   }
1085   return success;
1086 }
1087 
1088 bool RegisterContextUnwind::IsValid() const {
1089   return m_frame_type != eNotAValidFrame;
1090 }
1091 
1092 // After the final stack frame in a stack walk we'll get one invalid
1093 // (eNotAValidFrame) stack frame -- one past the end of the stack walk.  But
1094 // higher-level code will need to tell the difference between "the unwind plan
1095 // below this frame failed" versus "we successfully completed the stack walk"
1096 // so this method helps to disambiguate that.
1097 
1098 bool RegisterContextUnwind::IsTrapHandlerFrame() const {
1099   return m_frame_type == eTrapHandlerFrame;
1100 }
1101 
1102 // A skip frame is a bogus frame on the stack -- but one where we're likely to
1103 // find a real frame farther
1104 // up the stack if we keep looking.  It's always the second frame in an unwind
1105 // (i.e. the first frame after frame zero) where unwinding can be the
1106 // trickiest.  Ideally we'll mark up this frame in some way so the user knows
1107 // we're displaying bad data and we may have skipped one frame of their real
1108 // program in the process of getting back on track.
1109 
1110 bool RegisterContextUnwind::IsSkipFrame() const {
1111   return m_frame_type == eSkipFrame;
1112 }
1113 
1114 bool RegisterContextUnwind::IsTrapHandlerSymbol(
1115     lldb_private::Process *process,
1116     const lldb_private::SymbolContext &m_sym_ctx) const {
1117   PlatformSP platform_sp(process->GetTarget().GetPlatform());
1118   if (platform_sp) {
1119     const std::vector<ConstString> trap_handler_names(
1120         platform_sp->GetTrapHandlerSymbolNames());
1121     for (ConstString name : trap_handler_names) {
1122       if ((m_sym_ctx.function && m_sym_ctx.function->GetName() == name) ||
1123           (m_sym_ctx.symbol && m_sym_ctx.symbol->GetName() == name)) {
1124         return true;
1125       }
1126     }
1127   }
1128   const std::vector<ConstString> user_specified_trap_handler_names(
1129       m_parent_unwind.GetUserSpecifiedTrapHandlerFunctionNames());
1130   for (ConstString name : user_specified_trap_handler_names) {
1131     if ((m_sym_ctx.function && m_sym_ctx.function->GetName() == name) ||
1132         (m_sym_ctx.symbol && m_sym_ctx.symbol->GetName() == name)) {
1133       return true;
1134     }
1135   }
1136 
1137   return false;
1138 }
1139 
1140 // Answer the question: Where did THIS frame save the CALLER frame ("previous"
1141 // frame)'s register value?
1142 
1143 enum UnwindLLDB::RegisterSearchResult
1144 RegisterContextUnwind::SavedLocationForRegister(
1145     uint32_t lldb_regnum, lldb_private::UnwindLLDB::RegisterLocation &regloc) {
1146   RegisterNumber regnum(m_thread, eRegisterKindLLDB, lldb_regnum);
1147   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_UNWIND));
1148 
1149   // Have we already found this register location?
1150   if (!m_registers.empty()) {
1151     std::map<uint32_t,
1152              lldb_private::UnwindLLDB::RegisterLocation>::const_iterator
1153         iterator;
1154     iterator = m_registers.find(regnum.GetAsKind(eRegisterKindLLDB));
1155     if (iterator != m_registers.end()) {
1156       regloc = iterator->second;
1157       UnwindLogMsg("supplying caller's saved %s (%d)'s location, cached",
1158                    regnum.GetName(), regnum.GetAsKind(eRegisterKindLLDB));
1159       return UnwindLLDB::RegisterSearchResult::eRegisterFound;
1160     }
1161   }
1162 
1163   // Look through the available UnwindPlans for the register location.
1164 
1165   UnwindPlan::Row::RegisterLocation unwindplan_regloc;
1166   bool have_unwindplan_regloc = false;
1167   RegisterKind unwindplan_registerkind = kNumRegisterKinds;
1168 
1169   if (m_fast_unwind_plan_sp) {
1170     UnwindPlan::RowSP active_row =
1171         m_fast_unwind_plan_sp->GetRowForFunctionOffset(m_current_offset);
1172     unwindplan_registerkind = m_fast_unwind_plan_sp->GetRegisterKind();
1173     if (regnum.GetAsKind(unwindplan_registerkind) == LLDB_INVALID_REGNUM) {
1174       UnwindLogMsg("could not convert lldb regnum %s (%d) into %d RegisterKind "
1175                    "reg numbering scheme",
1176                    regnum.GetName(), regnum.GetAsKind(eRegisterKindLLDB),
1177                    (int)unwindplan_registerkind);
1178       return UnwindLLDB::RegisterSearchResult::eRegisterNotFound;
1179     }
1180     // The architecture default unwind plan marks unknown registers as
1181     // Undefined so that we don't forward them up the stack when a
1182     // jitted stack frame may have overwritten them.  But when the
1183     // arch default unwind plan is used as the Fast Unwind Plan, we
1184     // need to recognize this & switch over to the Full Unwind Plan
1185     // to see what unwind rule that (more knoweldgeable, probably)
1186     // UnwindPlan has.  If the full UnwindPlan says the register
1187     // location is Undefined, then it really is.
1188     if (active_row->GetRegisterInfo(regnum.GetAsKind(unwindplan_registerkind),
1189                                     unwindplan_regloc) &&
1190         !unwindplan_regloc.IsUndefined()) {
1191       UnwindLogMsg(
1192           "supplying caller's saved %s (%d)'s location using FastUnwindPlan",
1193           regnum.GetName(), regnum.GetAsKind(eRegisterKindLLDB));
1194       have_unwindplan_regloc = true;
1195     }
1196   }
1197 
1198   if (!have_unwindplan_regloc) {
1199     // m_full_unwind_plan_sp being NULL means that we haven't tried to find a
1200     // full UnwindPlan yet
1201     bool got_new_full_unwindplan = false;
1202     if (!m_full_unwind_plan_sp) {
1203       m_full_unwind_plan_sp = GetFullUnwindPlanForFrame();
1204       got_new_full_unwindplan = true;
1205     }
1206 
1207     if (m_full_unwind_plan_sp) {
1208       RegisterNumber pc_regnum(m_thread, eRegisterKindGeneric,
1209                                LLDB_REGNUM_GENERIC_PC);
1210 
1211       UnwindPlan::RowSP active_row =
1212           m_full_unwind_plan_sp->GetRowForFunctionOffset(m_current_offset);
1213       unwindplan_registerkind = m_full_unwind_plan_sp->GetRegisterKind();
1214 
1215       if (got_new_full_unwindplan && active_row.get() && log) {
1216         StreamString active_row_strm;
1217         ExecutionContext exe_ctx(m_thread.shared_from_this());
1218         active_row->Dump(active_row_strm, m_full_unwind_plan_sp.get(),
1219                          &m_thread,
1220                          m_start_pc.GetLoadAddress(exe_ctx.GetTargetPtr()));
1221         UnwindLogMsg("Using full unwind plan '%s'",
1222                      m_full_unwind_plan_sp->GetSourceName().AsCString());
1223         UnwindLogMsg("active row: %s", active_row_strm.GetData());
1224       }
1225       RegisterNumber return_address_reg;
1226 
1227       // If we're fetching the saved pc and this UnwindPlan defines a
1228       // ReturnAddress register (e.g. lr on arm), look for the return address
1229       // register number in the UnwindPlan's row.
1230       if (pc_regnum.IsValid() && pc_regnum == regnum &&
1231           m_full_unwind_plan_sp->GetReturnAddressRegister() !=
1232               LLDB_INVALID_REGNUM) {
1233         // If this is a trap handler frame, we should have access to
1234         // the complete register context when the interrupt/async
1235         // signal was received, we should fetch the actual saved $pc
1236         // value instead of the Return Address register.
1237         // If $pc is not available, fall back to the RA reg.
1238         UnwindPlan::Row::RegisterLocation scratch;
1239         if (m_frame_type == eTrapHandlerFrame &&
1240             active_row->GetRegisterInfo
1241               (pc_regnum.GetAsKind (unwindplan_registerkind), scratch)) {
1242           UnwindLogMsg("Providing pc register instead of rewriting to "
1243                        "RA reg because this is a trap handler and there is "
1244                        "a location for the saved pc register value.");
1245         } else {
1246           return_address_reg.init(
1247               m_thread, m_full_unwind_plan_sp->GetRegisterKind(),
1248               m_full_unwind_plan_sp->GetReturnAddressRegister());
1249           regnum = return_address_reg;
1250           UnwindLogMsg("requested caller's saved PC but this UnwindPlan uses a "
1251                        "RA reg; getting %s (%d) instead",
1252                        return_address_reg.GetName(),
1253                        return_address_reg.GetAsKind(eRegisterKindLLDB));
1254         }
1255       } else {
1256         if (regnum.GetAsKind(unwindplan_registerkind) == LLDB_INVALID_REGNUM) {
1257           if (unwindplan_registerkind == eRegisterKindGeneric) {
1258             UnwindLogMsg("could not convert lldb regnum %s (%d) into "
1259                          "eRegisterKindGeneric reg numbering scheme",
1260                          regnum.GetName(), regnum.GetAsKind(eRegisterKindLLDB));
1261           } else {
1262             UnwindLogMsg("could not convert lldb regnum %s (%d) into %d "
1263                          "RegisterKind reg numbering scheme",
1264                          regnum.GetName(), regnum.GetAsKind(eRegisterKindLLDB),
1265                          (int)unwindplan_registerkind);
1266           }
1267           return UnwindLLDB::RegisterSearchResult::eRegisterNotFound;
1268         }
1269       }
1270 
1271       if (regnum.IsValid() &&
1272           active_row->GetRegisterInfo(regnum.GetAsKind(unwindplan_registerkind),
1273                                       unwindplan_regloc)) {
1274         have_unwindplan_regloc = true;
1275         UnwindLogMsg(
1276             "supplying caller's saved %s (%d)'s location using %s UnwindPlan",
1277             regnum.GetName(), regnum.GetAsKind(eRegisterKindLLDB),
1278             m_full_unwind_plan_sp->GetSourceName().GetCString());
1279       }
1280 
1281       // This is frame 0 and we're retrieving the PC and it's saved in a Return
1282       // Address register and it hasn't been saved anywhere yet -- that is,
1283       // it's still live in the actual register. Handle this specially.
1284 
1285       if (!have_unwindplan_regloc && return_address_reg.IsValid() &&
1286           IsFrameZero()) {
1287         if (return_address_reg.GetAsKind(eRegisterKindLLDB) !=
1288             LLDB_INVALID_REGNUM) {
1289           lldb_private::UnwindLLDB::RegisterLocation new_regloc;
1290           new_regloc.type =
1291               UnwindLLDB::RegisterLocation::eRegisterInLiveRegisterContext;
1292           new_regloc.location.register_number =
1293               return_address_reg.GetAsKind(eRegisterKindLLDB);
1294           m_registers[regnum.GetAsKind(eRegisterKindLLDB)] = new_regloc;
1295           regloc = new_regloc;
1296           UnwindLogMsg("supplying caller's register %s (%d) from the live "
1297                        "RegisterContext at frame 0, saved in %d",
1298                        return_address_reg.GetName(),
1299                        return_address_reg.GetAsKind(eRegisterKindLLDB),
1300                        return_address_reg.GetAsKind(eRegisterKindLLDB));
1301           return UnwindLLDB::RegisterSearchResult::eRegisterFound;
1302         }
1303       }
1304 
1305       // If this architecture stores the return address in a register (it
1306       // defines a Return Address register) and we're on a non-zero stack frame
1307       // and the Full UnwindPlan says that the pc is stored in the
1308       // RA registers (e.g. lr on arm), then we know that the full unwindplan is
1309       // not trustworthy -- this
1310       // is an impossible situation and the instruction emulation code has
1311       // likely been misled. If this stack frame meets those criteria, we need
1312       // to throw away the Full UnwindPlan that the instruction emulation came
1313       // up with and fall back to the architecture's Default UnwindPlan so the
1314       // stack walk can get past this point.
1315 
1316       // Special note:  If the Full UnwindPlan was generated from the compiler,
1317       // don't second-guess it when we're at a call site location.
1318 
1319       // arch_default_ra_regnum is the return address register # in the Full
1320       // UnwindPlan register numbering
1321       RegisterNumber arch_default_ra_regnum(m_thread, eRegisterKindGeneric,
1322                                             LLDB_REGNUM_GENERIC_RA);
1323 
1324       if (arch_default_ra_regnum.GetAsKind(unwindplan_registerkind) !=
1325               LLDB_INVALID_REGNUM &&
1326           pc_regnum == regnum && unwindplan_regloc.IsInOtherRegister() &&
1327           unwindplan_regloc.GetRegisterNumber() ==
1328               arch_default_ra_regnum.GetAsKind(unwindplan_registerkind) &&
1329           m_full_unwind_plan_sp->GetSourcedFromCompiler() != eLazyBoolYes &&
1330           !m_all_registers_available) {
1331         UnwindLogMsg("%s UnwindPlan tried to restore the pc from the link "
1332                      "register but this is a non-zero frame",
1333                      m_full_unwind_plan_sp->GetSourceName().GetCString());
1334 
1335         // Throw away the full unwindplan; install the arch default unwindplan
1336         if (ForceSwitchToFallbackUnwindPlan()) {
1337           // Update for the possibly new unwind plan
1338           unwindplan_registerkind = m_full_unwind_plan_sp->GetRegisterKind();
1339           UnwindPlan::RowSP active_row =
1340               m_full_unwind_plan_sp->GetRowForFunctionOffset(m_current_offset);
1341 
1342           // Sanity check: Verify that we can fetch a pc value and CFA value
1343           // with this unwind plan
1344 
1345           RegisterNumber arch_default_pc_reg(m_thread, eRegisterKindGeneric,
1346                                              LLDB_REGNUM_GENERIC_PC);
1347           bool can_fetch_pc_value = false;
1348           bool can_fetch_cfa = false;
1349           addr_t cfa_value;
1350           if (active_row) {
1351             if (arch_default_pc_reg.GetAsKind(unwindplan_registerkind) !=
1352                     LLDB_INVALID_REGNUM &&
1353                 active_row->GetRegisterInfo(
1354                     arch_default_pc_reg.GetAsKind(unwindplan_registerkind),
1355                     unwindplan_regloc)) {
1356               can_fetch_pc_value = true;
1357             }
1358             if (ReadFrameAddress(unwindplan_registerkind,
1359                                  active_row->GetCFAValue(), cfa_value)) {
1360               can_fetch_cfa = true;
1361             }
1362           }
1363 
1364           have_unwindplan_regloc = can_fetch_pc_value && can_fetch_cfa;
1365         } else {
1366           // We were unable to fall back to another unwind plan
1367           have_unwindplan_regloc = false;
1368         }
1369       }
1370     }
1371   }
1372 
1373   ExecutionContext exe_ctx(m_thread.shared_from_this());
1374   Process *process = exe_ctx.GetProcessPtr();
1375   if (!have_unwindplan_regloc) {
1376     // If the UnwindPlan failed to give us an unwind location for this
1377     // register, we may be able to fall back to some ABI-defined default.  For
1378     // example, some ABIs allow to determine the caller's SP via the CFA. Also,
1379     // the ABI may set volatile registers to the undefined state.
1380     ABI *abi = process ? process->GetABI().get() : nullptr;
1381     if (abi) {
1382       const RegisterInfo *reg_info =
1383           GetRegisterInfoAtIndex(regnum.GetAsKind(eRegisterKindLLDB));
1384       if (reg_info &&
1385           abi->GetFallbackRegisterLocation(reg_info, unwindplan_regloc)) {
1386         UnwindLogMsg(
1387             "supplying caller's saved %s (%d)'s location using ABI default",
1388             regnum.GetName(), regnum.GetAsKind(eRegisterKindLLDB));
1389         have_unwindplan_regloc = true;
1390       }
1391     }
1392   }
1393 
1394   if (!have_unwindplan_regloc) {
1395     if (IsFrameZero()) {
1396       // This is frame 0 - we should return the actual live register context
1397       // value
1398       lldb_private::UnwindLLDB::RegisterLocation new_regloc;
1399       new_regloc.type =
1400           UnwindLLDB::RegisterLocation::eRegisterInLiveRegisterContext;
1401       new_regloc.location.register_number = regnum.GetAsKind(eRegisterKindLLDB);
1402       m_registers[regnum.GetAsKind(eRegisterKindLLDB)] = new_regloc;
1403       regloc = new_regloc;
1404       UnwindLogMsg("supplying caller's register %s (%d) from the live "
1405                    "RegisterContext at frame 0",
1406                    regnum.GetName(), regnum.GetAsKind(eRegisterKindLLDB));
1407       return UnwindLLDB::RegisterSearchResult::eRegisterFound;
1408     } else {
1409       std::string unwindplan_name("");
1410       if (m_full_unwind_plan_sp) {
1411         unwindplan_name += "via '";
1412         unwindplan_name += m_full_unwind_plan_sp->GetSourceName().AsCString();
1413         unwindplan_name += "'";
1414       }
1415       UnwindLogMsg("no save location for %s (%d) %s", regnum.GetName(),
1416                    regnum.GetAsKind(eRegisterKindLLDB),
1417                    unwindplan_name.c_str());
1418     }
1419     return UnwindLLDB::RegisterSearchResult::eRegisterNotFound;
1420   }
1421 
1422   // unwindplan_regloc has valid contents about where to retrieve the register
1423   if (unwindplan_regloc.IsUnspecified()) {
1424     lldb_private::UnwindLLDB::RegisterLocation new_regloc;
1425     new_regloc.type = UnwindLLDB::RegisterLocation::eRegisterNotSaved;
1426     m_registers[regnum.GetAsKind(eRegisterKindLLDB)] = new_regloc;
1427     UnwindLogMsg("save location for %s (%d) is unspecified, continue searching",
1428                  regnum.GetName(), regnum.GetAsKind(eRegisterKindLLDB));
1429     return UnwindLLDB::RegisterSearchResult::eRegisterNotFound;
1430   }
1431 
1432   if (unwindplan_regloc.IsUndefined()) {
1433     UnwindLogMsg(
1434         "did not supply reg location for %s (%d) because it is volatile",
1435         regnum.GetName(), regnum.GetAsKind(eRegisterKindLLDB));
1436     return UnwindLLDB::RegisterSearchResult::eRegisterIsVolatile;
1437   }
1438 
1439   if (unwindplan_regloc.IsSame()) {
1440     if (!IsFrameZero() &&
1441         (regnum.GetAsKind(eRegisterKindGeneric) == LLDB_REGNUM_GENERIC_PC ||
1442          regnum.GetAsKind(eRegisterKindGeneric) == LLDB_REGNUM_GENERIC_RA)) {
1443       UnwindLogMsg("register %s (%d) is marked as 'IsSame' - it is a pc or "
1444                    "return address reg on a non-zero frame -- treat as if we "
1445                    "have no information",
1446                    regnum.GetName(), regnum.GetAsKind(eRegisterKindLLDB));
1447       return UnwindLLDB::RegisterSearchResult::eRegisterNotFound;
1448     } else {
1449       regloc.type = UnwindLLDB::RegisterLocation::eRegisterInRegister;
1450       regloc.location.register_number = regnum.GetAsKind(eRegisterKindLLDB);
1451       m_registers[regnum.GetAsKind(eRegisterKindLLDB)] = regloc;
1452       UnwindLogMsg(
1453           "supplying caller's register %s (%d), saved in register %s (%d)",
1454           regnum.GetName(), regnum.GetAsKind(eRegisterKindLLDB),
1455           regnum.GetName(), regnum.GetAsKind(eRegisterKindLLDB));
1456       return UnwindLLDB::RegisterSearchResult::eRegisterFound;
1457     }
1458   }
1459 
1460   if (unwindplan_regloc.IsCFAPlusOffset()) {
1461     int offset = unwindplan_regloc.GetOffset();
1462     regloc.type = UnwindLLDB::RegisterLocation::eRegisterValueInferred;
1463     regloc.location.inferred_value = m_cfa + offset;
1464     m_registers[regnum.GetAsKind(eRegisterKindLLDB)] = regloc;
1465     UnwindLogMsg("supplying caller's register %s (%d), value is CFA plus "
1466                  "offset %d [value is 0x%" PRIx64 "]",
1467                  regnum.GetName(), regnum.GetAsKind(eRegisterKindLLDB), offset,
1468                  regloc.location.inferred_value);
1469     return UnwindLLDB::RegisterSearchResult::eRegisterFound;
1470   }
1471 
1472   if (unwindplan_regloc.IsAtCFAPlusOffset()) {
1473     int offset = unwindplan_regloc.GetOffset();
1474     regloc.type = UnwindLLDB::RegisterLocation::eRegisterSavedAtMemoryLocation;
1475     regloc.location.target_memory_location = m_cfa + offset;
1476     m_registers[regnum.GetAsKind(eRegisterKindLLDB)] = regloc;
1477     UnwindLogMsg("supplying caller's register %s (%d) from the stack, saved at "
1478                  "CFA plus offset %d [saved at 0x%" PRIx64 "]",
1479                  regnum.GetName(), regnum.GetAsKind(eRegisterKindLLDB), offset,
1480                  regloc.location.target_memory_location);
1481     return UnwindLLDB::RegisterSearchResult::eRegisterFound;
1482   }
1483 
1484   if (unwindplan_regloc.IsAFAPlusOffset()) {
1485     if (m_afa == LLDB_INVALID_ADDRESS)
1486         return UnwindLLDB::RegisterSearchResult::eRegisterNotFound;
1487 
1488     int offset = unwindplan_regloc.GetOffset();
1489     regloc.type = UnwindLLDB::RegisterLocation::eRegisterValueInferred;
1490     regloc.location.inferred_value = m_afa + offset;
1491     m_registers[regnum.GetAsKind(eRegisterKindLLDB)] = regloc;
1492     UnwindLogMsg("supplying caller's register %s (%d), value is AFA plus "
1493                  "offset %d [value is 0x%" PRIx64 "]",
1494                  regnum.GetName(), regnum.GetAsKind(eRegisterKindLLDB), offset,
1495                  regloc.location.inferred_value);
1496     return UnwindLLDB::RegisterSearchResult::eRegisterFound;
1497   }
1498 
1499   if (unwindplan_regloc.IsAtAFAPlusOffset()) {
1500     if (m_afa == LLDB_INVALID_ADDRESS)
1501         return UnwindLLDB::RegisterSearchResult::eRegisterNotFound;
1502 
1503     int offset = unwindplan_regloc.GetOffset();
1504     regloc.type = UnwindLLDB::RegisterLocation::eRegisterSavedAtMemoryLocation;
1505     regloc.location.target_memory_location = m_afa + offset;
1506     m_registers[regnum.GetAsKind(eRegisterKindLLDB)] = regloc;
1507     UnwindLogMsg("supplying caller's register %s (%d) from the stack, saved at "
1508                  "AFA plus offset %d [saved at 0x%" PRIx64 "]",
1509                  regnum.GetName(), regnum.GetAsKind(eRegisterKindLLDB), offset,
1510                  regloc.location.target_memory_location);
1511     return UnwindLLDB::RegisterSearchResult::eRegisterFound;
1512   }
1513 
1514   if (unwindplan_regloc.IsInOtherRegister()) {
1515     uint32_t unwindplan_regnum = unwindplan_regloc.GetRegisterNumber();
1516     RegisterNumber row_regnum(m_thread, unwindplan_registerkind,
1517                               unwindplan_regnum);
1518     if (row_regnum.GetAsKind(eRegisterKindLLDB) == LLDB_INVALID_REGNUM) {
1519       UnwindLogMsg("could not supply caller's %s (%d) location - was saved in "
1520                    "another reg but couldn't convert that regnum",
1521                    regnum.GetName(), regnum.GetAsKind(eRegisterKindLLDB));
1522       return UnwindLLDB::RegisterSearchResult::eRegisterNotFound;
1523     }
1524     regloc.type = UnwindLLDB::RegisterLocation::eRegisterInRegister;
1525     regloc.location.register_number = row_regnum.GetAsKind(eRegisterKindLLDB);
1526     m_registers[regnum.GetAsKind(eRegisterKindLLDB)] = regloc;
1527     UnwindLogMsg(
1528         "supplying caller's register %s (%d), saved in register %s (%d)",
1529         regnum.GetName(), regnum.GetAsKind(eRegisterKindLLDB),
1530         row_regnum.GetName(), row_regnum.GetAsKind(eRegisterKindLLDB));
1531     return UnwindLLDB::RegisterSearchResult::eRegisterFound;
1532   }
1533 
1534   if (unwindplan_regloc.IsDWARFExpression() ||
1535       unwindplan_regloc.IsAtDWARFExpression()) {
1536     DataExtractor dwarfdata(unwindplan_regloc.GetDWARFExpressionBytes(),
1537                             unwindplan_regloc.GetDWARFExpressionLength(),
1538                             process->GetByteOrder(),
1539                             process->GetAddressByteSize());
1540     ModuleSP opcode_ctx;
1541     DWARFExpression dwarfexpr(opcode_ctx, dwarfdata, nullptr);
1542     dwarfexpr.SetRegisterKind(unwindplan_registerkind);
1543     Value cfa_val = Scalar(m_cfa);
1544     cfa_val.SetValueType(Value::ValueType::LoadAddress);
1545     Value result;
1546     Status error;
1547     if (dwarfexpr.Evaluate(&exe_ctx, this, 0, &cfa_val, nullptr, result,
1548                            &error)) {
1549       addr_t val;
1550       val = result.GetScalar().ULongLong();
1551       if (unwindplan_regloc.IsDWARFExpression()) {
1552         regloc.type = UnwindLLDB::RegisterLocation::eRegisterValueInferred;
1553         regloc.location.inferred_value = val;
1554         m_registers[regnum.GetAsKind(eRegisterKindLLDB)] = regloc;
1555         UnwindLogMsg("supplying caller's register %s (%d) via DWARF expression "
1556                      "(IsDWARFExpression)",
1557                      regnum.GetName(), regnum.GetAsKind(eRegisterKindLLDB));
1558         return UnwindLLDB::RegisterSearchResult::eRegisterFound;
1559       } else {
1560         regloc.type =
1561             UnwindLLDB::RegisterLocation::eRegisterSavedAtMemoryLocation;
1562         regloc.location.target_memory_location = val;
1563         m_registers[regnum.GetAsKind(eRegisterKindLLDB)] = regloc;
1564         UnwindLogMsg("supplying caller's register %s (%d) via DWARF expression "
1565                      "(IsAtDWARFExpression)",
1566                      regnum.GetName(), regnum.GetAsKind(eRegisterKindLLDB));
1567         return UnwindLLDB::RegisterSearchResult::eRegisterFound;
1568       }
1569     }
1570     UnwindLogMsg("tried to use IsDWARFExpression or IsAtDWARFExpression for %s "
1571                  "(%d) but failed",
1572                  regnum.GetName(), regnum.GetAsKind(eRegisterKindLLDB));
1573     return UnwindLLDB::RegisterSearchResult::eRegisterNotFound;
1574   }
1575 
1576   UnwindLogMsg("no save location for %s (%d) in this stack frame",
1577                regnum.GetName(), regnum.GetAsKind(eRegisterKindLLDB));
1578 
1579   // FIXME UnwindPlan::Row types atDWARFExpression and isDWARFExpression are
1580   // unsupported.
1581 
1582   return UnwindLLDB::RegisterSearchResult::eRegisterNotFound;
1583 }
1584 
1585 // TryFallbackUnwindPlan() -- this method is a little tricky.
1586 //
1587 // When this is called, the frame above -- the caller frame, the "previous"
1588 // frame -- is invalid or bad.
1589 //
1590 // Instead of stopping the stack walk here, we'll try a different UnwindPlan
1591 // and see if we can get a valid frame above us.
1592 //
1593 // This most often happens when an unwind plan based on assembly instruction
1594 // inspection is not correct -- mostly with hand-written assembly functions or
1595 // functions where the stack frame is set up "out of band", e.g. the kernel
1596 // saved the register context and then called an asynchronous trap handler like
1597 // _sigtramp.
1598 //
1599 // Often in these cases, if we just do a dumb stack walk we'll get past this
1600 // tricky frame and our usual techniques can continue to be used.
1601 
1602 bool RegisterContextUnwind::TryFallbackUnwindPlan() {
1603   if (m_fallback_unwind_plan_sp.get() == nullptr)
1604     return false;
1605 
1606   if (m_full_unwind_plan_sp.get() == nullptr)
1607     return false;
1608 
1609   if (m_full_unwind_plan_sp.get() == m_fallback_unwind_plan_sp.get() ||
1610       m_full_unwind_plan_sp->GetSourceName() ==
1611           m_fallback_unwind_plan_sp->GetSourceName()) {
1612     return false;
1613   }
1614 
1615   // If a compiler generated unwind plan failed, trying the arch default
1616   // unwindplan isn't going to do any better.
1617   if (m_full_unwind_plan_sp->GetSourcedFromCompiler() == eLazyBoolYes)
1618     return false;
1619 
1620   // Get the caller's pc value and our own CFA value. Swap in the fallback
1621   // unwind plan, re-fetch the caller's pc value and CFA value. If they're the
1622   // same, then the fallback unwind plan provides no benefit.
1623 
1624   RegisterNumber pc_regnum(m_thread, eRegisterKindGeneric,
1625                            LLDB_REGNUM_GENERIC_PC);
1626 
1627   addr_t old_caller_pc_value = LLDB_INVALID_ADDRESS;
1628   addr_t new_caller_pc_value = LLDB_INVALID_ADDRESS;
1629   UnwindLLDB::RegisterLocation regloc;
1630   if (SavedLocationForRegister(pc_regnum.GetAsKind(eRegisterKindLLDB),
1631                                regloc) ==
1632       UnwindLLDB::RegisterSearchResult::eRegisterFound) {
1633     const RegisterInfo *reg_info =
1634         GetRegisterInfoAtIndex(pc_regnum.GetAsKind(eRegisterKindLLDB));
1635     if (reg_info) {
1636       RegisterValue reg_value;
1637       if (ReadRegisterValueFromRegisterLocation(regloc, reg_info, reg_value)) {
1638         old_caller_pc_value = reg_value.GetAsUInt64();
1639       }
1640     }
1641   }
1642 
1643   // This is a tricky wrinkle!  If SavedLocationForRegister() detects a really
1644   // impossible register location for the full unwind plan, it may call
1645   // ForceSwitchToFallbackUnwindPlan() which in turn replaces the full
1646   // unwindplan with the fallback... in short, we're done, we're using the
1647   // fallback UnwindPlan. We checked if m_fallback_unwind_plan_sp was nullptr
1648   // at the top -- the only way it became nullptr since then is via
1649   // SavedLocationForRegister().
1650   if (m_fallback_unwind_plan_sp.get() == nullptr)
1651     return true;
1652 
1653   // Switch the full UnwindPlan to be the fallback UnwindPlan.  If we decide
1654   // this isn't working, we need to restore. We'll also need to save & restore
1655   // the value of the m_cfa ivar.  Save is down below a bit in 'old_cfa'.
1656   UnwindPlanSP original_full_unwind_plan_sp = m_full_unwind_plan_sp;
1657   addr_t old_cfa = m_cfa;
1658   addr_t old_afa = m_afa;
1659 
1660   m_registers.clear();
1661 
1662   m_full_unwind_plan_sp = m_fallback_unwind_plan_sp;
1663 
1664   UnwindPlan::RowSP active_row =
1665       m_fallback_unwind_plan_sp->GetRowForFunctionOffset(m_current_offset);
1666 
1667   if (active_row &&
1668       active_row->GetCFAValue().GetValueType() !=
1669           UnwindPlan::Row::FAValue::unspecified) {
1670     addr_t new_cfa;
1671     if (!ReadFrameAddress(m_fallback_unwind_plan_sp->GetRegisterKind(),
1672                             active_row->GetCFAValue(), new_cfa) ||
1673         new_cfa == 0 || new_cfa == 1 || new_cfa == LLDB_INVALID_ADDRESS) {
1674       UnwindLogMsg("failed to get cfa with fallback unwindplan");
1675       m_fallback_unwind_plan_sp.reset();
1676       m_full_unwind_plan_sp = original_full_unwind_plan_sp;
1677       return false;
1678     }
1679     m_cfa = new_cfa;
1680 
1681     ReadFrameAddress(m_fallback_unwind_plan_sp->GetRegisterKind(),
1682                      active_row->GetAFAValue(), m_afa);
1683 
1684     if (SavedLocationForRegister(pc_regnum.GetAsKind(eRegisterKindLLDB),
1685                                  regloc) ==
1686         UnwindLLDB::RegisterSearchResult::eRegisterFound) {
1687       const RegisterInfo *reg_info =
1688           GetRegisterInfoAtIndex(pc_regnum.GetAsKind(eRegisterKindLLDB));
1689       if (reg_info) {
1690         RegisterValue reg_value;
1691         if (ReadRegisterValueFromRegisterLocation(regloc, reg_info,
1692                                                   reg_value)) {
1693           new_caller_pc_value = reg_value.GetAsUInt64();
1694         }
1695       }
1696     }
1697 
1698     if (new_caller_pc_value == LLDB_INVALID_ADDRESS) {
1699       UnwindLogMsg("failed to get a pc value for the caller frame with the "
1700                    "fallback unwind plan");
1701       m_fallback_unwind_plan_sp.reset();
1702       m_full_unwind_plan_sp = original_full_unwind_plan_sp;
1703       m_cfa = old_cfa;
1704       m_afa = old_afa;
1705       return false;
1706     }
1707 
1708     if (old_caller_pc_value == new_caller_pc_value &&
1709         m_cfa == old_cfa &&
1710         m_afa == old_afa) {
1711       UnwindLogMsg("fallback unwind plan got the same values for this frame "
1712                    "CFA and caller frame pc, not using");
1713       m_fallback_unwind_plan_sp.reset();
1714       m_full_unwind_plan_sp = original_full_unwind_plan_sp;
1715       return false;
1716     }
1717 
1718     UnwindLogMsg("trying to unwind from this function with the UnwindPlan '%s' "
1719                  "because UnwindPlan '%s' failed.",
1720                  m_fallback_unwind_plan_sp->GetSourceName().GetCString(),
1721                  original_full_unwind_plan_sp->GetSourceName().GetCString());
1722 
1723     // We've copied the fallback unwind plan into the full - now clear the
1724     // fallback.
1725     m_fallback_unwind_plan_sp.reset();
1726     PropagateTrapHandlerFlagFromUnwindPlan(m_full_unwind_plan_sp);
1727   }
1728 
1729   return true;
1730 }
1731 
1732 bool RegisterContextUnwind::ForceSwitchToFallbackUnwindPlan() {
1733   if (m_fallback_unwind_plan_sp.get() == nullptr)
1734     return false;
1735 
1736   if (m_full_unwind_plan_sp.get() == nullptr)
1737     return false;
1738 
1739   if (m_full_unwind_plan_sp.get() == m_fallback_unwind_plan_sp.get() ||
1740       m_full_unwind_plan_sp->GetSourceName() ==
1741           m_fallback_unwind_plan_sp->GetSourceName()) {
1742     return false;
1743   }
1744 
1745   UnwindPlan::RowSP active_row =
1746       m_fallback_unwind_plan_sp->GetRowForFunctionOffset(m_current_offset);
1747 
1748   if (active_row &&
1749       active_row->GetCFAValue().GetValueType() !=
1750           UnwindPlan::Row::FAValue::unspecified) {
1751     addr_t new_cfa;
1752     if (!ReadFrameAddress(m_fallback_unwind_plan_sp->GetRegisterKind(),
1753                             active_row->GetCFAValue(), new_cfa) ||
1754         new_cfa == 0 || new_cfa == 1 || new_cfa == LLDB_INVALID_ADDRESS) {
1755       UnwindLogMsg("failed to get cfa with fallback unwindplan");
1756       m_fallback_unwind_plan_sp.reset();
1757       return false;
1758     }
1759 
1760     ReadFrameAddress(m_fallback_unwind_plan_sp->GetRegisterKind(),
1761                      active_row->GetAFAValue(), m_afa);
1762 
1763     m_full_unwind_plan_sp = m_fallback_unwind_plan_sp;
1764     m_fallback_unwind_plan_sp.reset();
1765 
1766     m_registers.clear();
1767 
1768     m_cfa = new_cfa;
1769 
1770     PropagateTrapHandlerFlagFromUnwindPlan(m_full_unwind_plan_sp);
1771 
1772     UnwindLogMsg("switched unconditionally to the fallback unwindplan %s",
1773                  m_full_unwind_plan_sp->GetSourceName().GetCString());
1774     return true;
1775   }
1776   return false;
1777 }
1778 
1779 void RegisterContextUnwind::PropagateTrapHandlerFlagFromUnwindPlan(
1780     lldb::UnwindPlanSP unwind_plan) {
1781   if (unwind_plan->GetUnwindPlanForSignalTrap() != eLazyBoolYes) {
1782     // Unwind plan does not indicate trap handler.  Do nothing.  We may
1783     // already be flagged as trap handler flag due to the symbol being
1784     // in the trap handler symbol list, and that should take precedence.
1785     return;
1786   } else if (m_frame_type != eNormalFrame) {
1787     // If this is already a trap handler frame, nothing to do.
1788     // If this is a skip or debug or invalid frame, don't override that.
1789     return;
1790   }
1791 
1792   m_frame_type = eTrapHandlerFrame;
1793 
1794   if (m_current_offset_backed_up_one != m_current_offset) {
1795     // We backed up the pc by 1 to compute the symbol context, but
1796     // now need to undo that because the pc of the trap handler
1797     // frame may in fact be the first instruction of a signal return
1798     // trampoline, rather than the instruction after a call.  This
1799     // happens on systems where the signal handler dispatch code, rather
1800     // than calling the handler and being returned to, jumps to the
1801     // handler after pushing the address of a return trampoline on the
1802     // stack -- on these systems, when the handler returns, control will
1803     // be transferred to the return trampoline, so that's the best
1804     // symbol we can present in the callstack.
1805     UnwindLogMsg("Resetting current offset and re-doing symbol lookup; "
1806                  "old symbol was %s",
1807                  GetSymbolOrFunctionName(m_sym_ctx).AsCString(""));
1808     m_current_offset_backed_up_one = m_current_offset;
1809 
1810     AddressRange addr_range;
1811     m_sym_ctx_valid = m_current_pc.ResolveFunctionScope(m_sym_ctx, &addr_range);
1812 
1813     UnwindLogMsg("Symbol is now %s",
1814                  GetSymbolOrFunctionName(m_sym_ctx).AsCString(""));
1815 
1816     ExecutionContext exe_ctx(m_thread.shared_from_this());
1817     Process *process = exe_ctx.GetProcessPtr();
1818     Target *target = &process->GetTarget();
1819 
1820     m_start_pc = addr_range.GetBaseAddress();
1821     m_current_offset =
1822         m_current_pc.GetLoadAddress(target) - m_start_pc.GetLoadAddress(target);
1823   }
1824 }
1825 
1826 bool RegisterContextUnwind::ReadFrameAddress(
1827     lldb::RegisterKind row_register_kind, UnwindPlan::Row::FAValue &fa,
1828     addr_t &address) {
1829   RegisterValue reg_value;
1830 
1831   address = LLDB_INVALID_ADDRESS;
1832   addr_t cfa_reg_contents;
1833 
1834   switch (fa.GetValueType()) {
1835   case UnwindPlan::Row::FAValue::isRegisterDereferenced: {
1836     RegisterNumber cfa_reg(m_thread, row_register_kind,
1837                            fa.GetRegisterNumber());
1838     if (ReadGPRValue(cfa_reg, cfa_reg_contents)) {
1839       const RegisterInfo *reg_info =
1840           GetRegisterInfoAtIndex(cfa_reg.GetAsKind(eRegisterKindLLDB));
1841       RegisterValue reg_value;
1842       if (reg_info) {
1843         Status error = ReadRegisterValueFromMemory(
1844             reg_info, cfa_reg_contents, reg_info->byte_size, reg_value);
1845         if (error.Success()) {
1846           address = reg_value.GetAsUInt64();
1847           UnwindLogMsg(
1848               "CFA value via dereferencing reg %s (%d): reg has val 0x%" PRIx64
1849               ", CFA value is 0x%" PRIx64,
1850               cfa_reg.GetName(), cfa_reg.GetAsKind(eRegisterKindLLDB),
1851               cfa_reg_contents, address);
1852           return true;
1853         } else {
1854           UnwindLogMsg("Tried to deref reg %s (%d) [0x%" PRIx64
1855                        "] but memory read failed.",
1856                        cfa_reg.GetName(), cfa_reg.GetAsKind(eRegisterKindLLDB),
1857                        cfa_reg_contents);
1858         }
1859       }
1860     }
1861     break;
1862   }
1863   case UnwindPlan::Row::FAValue::isRegisterPlusOffset: {
1864     RegisterNumber cfa_reg(m_thread, row_register_kind,
1865                            fa.GetRegisterNumber());
1866     if (ReadGPRValue(cfa_reg, cfa_reg_contents)) {
1867       if (cfa_reg_contents == LLDB_INVALID_ADDRESS || cfa_reg_contents == 0 ||
1868           cfa_reg_contents == 1) {
1869         UnwindLogMsg(
1870             "Got an invalid CFA register value - reg %s (%d), value 0x%" PRIx64,
1871             cfa_reg.GetName(), cfa_reg.GetAsKind(eRegisterKindLLDB),
1872             cfa_reg_contents);
1873         cfa_reg_contents = LLDB_INVALID_ADDRESS;
1874         return false;
1875       }
1876       address = cfa_reg_contents + fa.GetOffset();
1877       UnwindLogMsg(
1878           "CFA is 0x%" PRIx64 ": Register %s (%d) contents are 0x%" PRIx64
1879           ", offset is %d",
1880           address, cfa_reg.GetName(), cfa_reg.GetAsKind(eRegisterKindLLDB),
1881           cfa_reg_contents, fa.GetOffset());
1882       return true;
1883     }
1884     break;
1885   }
1886   case UnwindPlan::Row::FAValue::isDWARFExpression: {
1887     ExecutionContext exe_ctx(m_thread.shared_from_this());
1888     Process *process = exe_ctx.GetProcessPtr();
1889     DataExtractor dwarfdata(fa.GetDWARFExpressionBytes(),
1890                             fa.GetDWARFExpressionLength(),
1891                             process->GetByteOrder(),
1892                             process->GetAddressByteSize());
1893     ModuleSP opcode_ctx;
1894     DWARFExpression dwarfexpr(opcode_ctx, dwarfdata, nullptr);
1895     dwarfexpr.SetRegisterKind(row_register_kind);
1896     Value result;
1897     Status error;
1898     if (dwarfexpr.Evaluate(&exe_ctx, this, 0, nullptr, nullptr, result,
1899                            &error)) {
1900       address = result.GetScalar().ULongLong();
1901 
1902       UnwindLogMsg("CFA value set by DWARF expression is 0x%" PRIx64,
1903                    address);
1904       return true;
1905     }
1906     UnwindLogMsg("Failed to set CFA value via DWARF expression: %s",
1907                  error.AsCString());
1908     break;
1909   }
1910   case UnwindPlan::Row::FAValue::isRaSearch: {
1911     Process &process = *m_thread.GetProcess();
1912     lldb::addr_t return_address_hint = GetReturnAddressHint(fa.GetOffset());
1913     if (return_address_hint == LLDB_INVALID_ADDRESS)
1914       return false;
1915     const unsigned max_iterations = 256;
1916     for (unsigned i = 0; i < max_iterations; ++i) {
1917       Status st;
1918       lldb::addr_t candidate_addr =
1919           return_address_hint + i * process.GetAddressByteSize();
1920       lldb::addr_t candidate =
1921           process.ReadPointerFromMemory(candidate_addr, st);
1922       if (st.Fail()) {
1923         UnwindLogMsg("Cannot read memory at 0x%" PRIx64 ": %s", candidate_addr,
1924                      st.AsCString());
1925         return false;
1926       }
1927       Address addr;
1928       uint32_t permissions;
1929       if (process.GetLoadAddressPermissions(candidate, permissions) &&
1930           permissions & lldb::ePermissionsExecutable) {
1931         address = candidate_addr;
1932         UnwindLogMsg("Heuristically found CFA: 0x%" PRIx64, address);
1933         return true;
1934       }
1935     }
1936     UnwindLogMsg("No suitable CFA found");
1937     break;
1938   }
1939   default:
1940     return false;
1941   }
1942   return false;
1943 }
1944 
1945 lldb::addr_t RegisterContextUnwind::GetReturnAddressHint(int32_t plan_offset) {
1946   addr_t hint;
1947   if (!ReadGPRValue(eRegisterKindGeneric, LLDB_REGNUM_GENERIC_SP, hint))
1948     return LLDB_INVALID_ADDRESS;
1949   if (!m_sym_ctx.module_sp || !m_sym_ctx.symbol)
1950     return LLDB_INVALID_ADDRESS;
1951 
1952   hint += plan_offset;
1953 
1954   if (auto next = GetNextFrame()) {
1955     if (!next->m_sym_ctx.module_sp || !next->m_sym_ctx.symbol)
1956       return LLDB_INVALID_ADDRESS;
1957     if (auto expected_size =
1958             next->m_sym_ctx.module_sp->GetSymbolFile()->GetParameterStackSize(
1959                 *next->m_sym_ctx.symbol))
1960       hint += *expected_size;
1961     else {
1962       UnwindLogMsgVerbose("Could not retrieve parameter size: %s",
1963                           llvm::toString(expected_size.takeError()).c_str());
1964       return LLDB_INVALID_ADDRESS;
1965     }
1966   }
1967   return hint;
1968 }
1969 
1970 // Retrieve a general purpose register value for THIS frame, as saved by the
1971 // NEXT frame, i.e. the frame that
1972 // this frame called.  e.g.
1973 //
1974 //  foo () { }
1975 //  bar () { foo (); }
1976 //  main () { bar (); }
1977 //
1978 //  stopped in foo() so
1979 //     frame 0 - foo
1980 //     frame 1 - bar
1981 //     frame 2 - main
1982 //  and this RegisterContext is for frame 1 (bar) - if we want to get the pc
1983 //  value for frame 1, we need to ask
1984 //  where frame 0 (the "next" frame) saved that and retrieve the value.
1985 
1986 bool RegisterContextUnwind::ReadGPRValue(lldb::RegisterKind register_kind,
1987                                          uint32_t regnum, addr_t &value) {
1988   if (!IsValid())
1989     return false;
1990 
1991   uint32_t lldb_regnum;
1992   if (register_kind == eRegisterKindLLDB) {
1993     lldb_regnum = regnum;
1994   } else if (!m_thread.GetRegisterContext()->ConvertBetweenRegisterKinds(
1995                  register_kind, regnum, eRegisterKindLLDB, lldb_regnum)) {
1996     return false;
1997   }
1998 
1999   const RegisterInfo *reg_info = GetRegisterInfoAtIndex(lldb_regnum);
2000   RegisterValue reg_value;
2001   // if this is frame 0 (currently executing frame), get the requested reg
2002   // contents from the actual thread registers
2003   if (IsFrameZero()) {
2004     if (m_thread.GetRegisterContext()->ReadRegister(reg_info, reg_value)) {
2005       value = reg_value.GetAsUInt64();
2006       return true;
2007     }
2008     return false;
2009   }
2010 
2011   bool pc_register = false;
2012   uint32_t generic_regnum;
2013   if (register_kind == eRegisterKindGeneric &&
2014       (regnum == LLDB_REGNUM_GENERIC_PC || regnum == LLDB_REGNUM_GENERIC_RA)) {
2015     pc_register = true;
2016   } else if (m_thread.GetRegisterContext()->ConvertBetweenRegisterKinds(
2017                  register_kind, regnum, eRegisterKindGeneric, generic_regnum) &&
2018              (generic_regnum == LLDB_REGNUM_GENERIC_PC ||
2019               generic_regnum == LLDB_REGNUM_GENERIC_RA)) {
2020     pc_register = true;
2021   }
2022 
2023   lldb_private::UnwindLLDB::RegisterLocation regloc;
2024   if (!m_parent_unwind.SearchForSavedLocationForRegister(
2025           lldb_regnum, regloc, m_frame_number - 1, pc_register)) {
2026     return false;
2027   }
2028   if (ReadRegisterValueFromRegisterLocation(regloc, reg_info, reg_value)) {
2029     value = reg_value.GetAsUInt64();
2030     return true;
2031   }
2032   return false;
2033 }
2034 
2035 bool RegisterContextUnwind::ReadGPRValue(const RegisterNumber &regnum,
2036                                          addr_t &value) {
2037   return ReadGPRValue(regnum.GetRegisterKind(), regnum.GetRegisterNumber(),
2038                       value);
2039 }
2040 
2041 // Find the value of a register in THIS frame
2042 
2043 bool RegisterContextUnwind::ReadRegister(const RegisterInfo *reg_info,
2044                                          RegisterValue &value) {
2045   if (!IsValid())
2046     return false;
2047 
2048   const uint32_t lldb_regnum = reg_info->kinds[eRegisterKindLLDB];
2049   UnwindLogMsgVerbose("looking for register saved location for reg %d",
2050                       lldb_regnum);
2051 
2052   // If this is the 0th frame, hand this over to the live register context
2053   if (IsFrameZero()) {
2054     UnwindLogMsgVerbose("passing along to the live register context for reg %d",
2055                         lldb_regnum);
2056     return m_thread.GetRegisterContext()->ReadRegister(reg_info, value);
2057   }
2058 
2059   bool is_pc_regnum = false;
2060   if (reg_info->kinds[eRegisterKindGeneric] == LLDB_REGNUM_GENERIC_PC ||
2061       reg_info->kinds[eRegisterKindGeneric] == LLDB_REGNUM_GENERIC_RA) {
2062     is_pc_regnum = true;
2063   }
2064 
2065   lldb_private::UnwindLLDB::RegisterLocation regloc;
2066   // Find out where the NEXT frame saved THIS frame's register contents
2067   if (!m_parent_unwind.SearchForSavedLocationForRegister(
2068           lldb_regnum, regloc, m_frame_number - 1, is_pc_regnum))
2069     return false;
2070 
2071   return ReadRegisterValueFromRegisterLocation(regloc, reg_info, value);
2072 }
2073 
2074 bool RegisterContextUnwind::WriteRegister(const RegisterInfo *reg_info,
2075                                           const RegisterValue &value) {
2076   if (!IsValid())
2077     return false;
2078 
2079   const uint32_t lldb_regnum = reg_info->kinds[eRegisterKindLLDB];
2080   UnwindLogMsgVerbose("looking for register saved location for reg %d",
2081                       lldb_regnum);
2082 
2083   // If this is the 0th frame, hand this over to the live register context
2084   if (IsFrameZero()) {
2085     UnwindLogMsgVerbose("passing along to the live register context for reg %d",
2086                         lldb_regnum);
2087     return m_thread.GetRegisterContext()->WriteRegister(reg_info, value);
2088   }
2089 
2090   lldb_private::UnwindLLDB::RegisterLocation regloc;
2091   // Find out where the NEXT frame saved THIS frame's register contents
2092   if (!m_parent_unwind.SearchForSavedLocationForRegister(
2093           lldb_regnum, regloc, m_frame_number - 1, false))
2094     return false;
2095 
2096   return WriteRegisterValueToRegisterLocation(regloc, reg_info, value);
2097 }
2098 
2099 // Don't need to implement this one
2100 bool RegisterContextUnwind::ReadAllRegisterValues(lldb::DataBufferSP &data_sp) {
2101   return false;
2102 }
2103 
2104 // Don't need to implement this one
2105 bool RegisterContextUnwind::WriteAllRegisterValues(
2106     const lldb::DataBufferSP &data_sp) {
2107   return false;
2108 }
2109 
2110 // Retrieve the pc value for THIS from
2111 
2112 bool RegisterContextUnwind::GetCFA(addr_t &cfa) {
2113   if (!IsValid()) {
2114     return false;
2115   }
2116   if (m_cfa == LLDB_INVALID_ADDRESS) {
2117     return false;
2118   }
2119   cfa = m_cfa;
2120   return true;
2121 }
2122 
2123 RegisterContextUnwind::SharedPtr RegisterContextUnwind::GetNextFrame() const {
2124   RegisterContextUnwind::SharedPtr regctx;
2125   if (m_frame_number == 0)
2126     return regctx;
2127   return m_parent_unwind.GetRegisterContextForFrameNum(m_frame_number - 1);
2128 }
2129 
2130 RegisterContextUnwind::SharedPtr RegisterContextUnwind::GetPrevFrame() const {
2131   RegisterContextUnwind::SharedPtr regctx;
2132   return m_parent_unwind.GetRegisterContextForFrameNum(m_frame_number + 1);
2133 }
2134 
2135 // Retrieve the address of the start of the function of THIS frame
2136 
2137 bool RegisterContextUnwind::GetStartPC(addr_t &start_pc) {
2138   if (!IsValid())
2139     return false;
2140 
2141   if (!m_start_pc.IsValid()) {
2142         bool read_successfully = ReadPC (start_pc);
2143         if (read_successfully)
2144         {
2145             ProcessSP process_sp (m_thread.GetProcess());
2146             if (process_sp)
2147             {
2148                 ABI *abi = process_sp->GetABI().get();
2149                 if (abi)
2150                     start_pc = abi->FixCodeAddress(start_pc);
2151             }
2152         }
2153         return read_successfully;
2154   }
2155   start_pc = m_start_pc.GetLoadAddress(CalculateTarget().get());
2156   return true;
2157 }
2158 
2159 // Retrieve the current pc value for THIS frame, as saved by the NEXT frame.
2160 
2161 bool RegisterContextUnwind::ReadPC(addr_t &pc) {
2162   if (!IsValid())
2163     return false;
2164 
2165   bool above_trap_handler = false;
2166   if (GetNextFrame().get() && GetNextFrame()->IsValid() &&
2167       GetNextFrame()->IsTrapHandlerFrame())
2168     above_trap_handler = true;
2169 
2170   if (ReadGPRValue(eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC, pc)) {
2171     // A pc value of 0 or 1 is impossible in the middle of the stack -- it
2172     // indicates the end of a stack walk.
2173     // On the currently executing frame (or such a frame interrupted
2174     // asynchronously by sigtramp et al) this may occur if code has jumped
2175     // through a NULL pointer -- we want to be able to unwind past that frame
2176     // to help find the bug.
2177 
2178     ProcessSP process_sp (m_thread.GetProcess());
2179     if (process_sp)
2180     {
2181         ABI *abi = process_sp->GetABI().get();
2182         if (abi)
2183             pc = abi->FixCodeAddress(pc);
2184     }
2185 
2186     return !(m_all_registers_available == false &&
2187              above_trap_handler == false && (pc == 0 || pc == 1));
2188   } else {
2189     return false;
2190   }
2191 }
2192 
2193 void RegisterContextUnwind::UnwindLogMsg(const char *fmt, ...) {
2194   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_UNWIND));
2195   if (log) {
2196     va_list args;
2197     va_start(args, fmt);
2198 
2199     char *logmsg;
2200     if (vasprintf(&logmsg, fmt, args) == -1 || logmsg == nullptr) {
2201       if (logmsg)
2202         free(logmsg);
2203       va_end(args);
2204       return;
2205     }
2206     va_end(args);
2207 
2208     LLDB_LOGF(log, "%*sth%d/fr%u %s",
2209               m_frame_number < 100 ? m_frame_number : 100, "",
2210               m_thread.GetIndexID(), m_frame_number, logmsg);
2211     free(logmsg);
2212   }
2213 }
2214 
2215 void RegisterContextUnwind::UnwindLogMsgVerbose(const char *fmt, ...) {
2216   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_UNWIND));
2217   if (log && log->GetVerbose()) {
2218     va_list args;
2219     va_start(args, fmt);
2220 
2221     char *logmsg;
2222     if (vasprintf(&logmsg, fmt, args) == -1 || logmsg == nullptr) {
2223       if (logmsg)
2224         free(logmsg);
2225       va_end(args);
2226       return;
2227     }
2228     va_end(args);
2229 
2230     LLDB_LOGF(log, "%*sth%d/fr%u %s",
2231               m_frame_number < 100 ? m_frame_number : 100, "",
2232               m_thread.GetIndexID(), m_frame_number, logmsg);
2233     free(logmsg);
2234   }
2235 }
2236