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