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