1 //===-- RegisterContextUnwind.cpp -----------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "lldb/Target/RegisterContextUnwind.h"
10 #include "lldb/Core/Address.h"
11 #include "lldb/Core/AddressRange.h"
12 #include "lldb/Core/Module.h"
13 #include "lldb/Core/Value.h"
14 #include "lldb/Expression/DWARFExpression.h"
15 #include "lldb/Symbol/ArmUnwindInfo.h"
16 #include "lldb/Symbol/CallFrameInfo.h"
17 #include "lldb/Symbol/DWARFCallFrameInfo.h"
18 #include "lldb/Symbol/FuncUnwinders.h"
19 #include "lldb/Symbol/Function.h"
20 #include "lldb/Symbol/ObjectFile.h"
21 #include "lldb/Symbol/Symbol.h"
22 #include "lldb/Symbol/SymbolContext.h"
23 #include "lldb/Symbol/SymbolFile.h"
24 #include "lldb/Target/ABI.h"
25 #include "lldb/Target/DynamicLoader.h"
26 #include "lldb/Target/ExecutionContext.h"
27 #include "lldb/Target/LanguageRuntime.h"
28 #include "lldb/Target/Platform.h"
29 #include "lldb/Target/Process.h"
30 #include "lldb/Target/SectionLoadList.h"
31 #include "lldb/Target/StackFrame.h"
32 #include "lldb/Target/Target.h"
33 #include "lldb/Target/Thread.h"
34 #include "lldb/Utility/DataBufferHeap.h"
35 #include "lldb/Utility/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, int &valid_pc_offset) {
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     valid_pc_offset = m_current_offset;
93     return true;
94   }
95 
96   // if m_current_offset <= 0, we've got nothing else to try
97   if (m_current_offset <= 0)
98     return false;
99 
100   // check pc - 1 to see if it's valid
101   Address pc_minus_one(m_current_pc);
102   pc_minus_one.SetOffset(m_current_pc.GetOffset() - 1);
103   if (unwind_plan_sp->PlanValidAtAddress(pc_minus_one)) {
104     // *valid_pc_offset = m_current_offset - 1;
105     valid_pc_offset = m_current_pc.GetOffset() - 1;
106     return true;
107   }
108 
109   return false;
110 }
111 
112 // Initialize a RegisterContextUnwind which is the first frame of a stack -- the
113 // zeroth frame or currently executing frame.
114 
115 void RegisterContextUnwind::InitializeZerothFrame() {
116   Log *log = GetLog(LLDBLog::Unwind);
117   ExecutionContext exe_ctx(m_thread.shared_from_this());
118   RegisterContextSP reg_ctx_sp = m_thread.GetRegisterContext();
119 
120   if (reg_ctx_sp.get() == nullptr) {
121     m_frame_type = eNotAValidFrame;
122     UnwindLogMsg("frame does not have a register context");
123     return;
124   }
125 
126   addr_t current_pc = reg_ctx_sp->GetPC();
127 
128   if (current_pc == LLDB_INVALID_ADDRESS) {
129     m_frame_type = eNotAValidFrame;
130     UnwindLogMsg("frame does not have a pc");
131     return;
132   }
133 
134   Process *process = exe_ctx.GetProcessPtr();
135 
136   // Let ABIs fixup code addresses to make sure they are valid. In ARM ABIs
137   // this will strip bit zero in case we read a PC from memory or from the LR.
138   // (which would be a no-op in frame 0 where we get it from the register set,
139   // but still a good idea to make the call here for other ABIs that may
140   // exist.)
141   ABI *abi = process->GetABI().get();
142   if (abi)
143     current_pc = abi->FixCodeAddress(current_pc);
144 
145   UnwindPlanSP lang_runtime_plan_sp = LanguageRuntime::GetRuntimeUnwindPlan(
146       m_thread, this, m_behaves_like_zeroth_frame);
147   if (lang_runtime_plan_sp.get()) {
148     UnwindLogMsg("This is an async frame");
149   }
150 
151   // Initialize m_current_pc, an Address object, based on current_pc, an
152   // addr_t.
153   m_current_pc.SetLoadAddress(current_pc, &process->GetTarget());
154 
155   // If we don't have a Module for some reason, we're not going to find
156   // symbol/function information - just stick in some reasonable defaults and
157   // hope we can unwind past this frame.
158   ModuleSP pc_module_sp(m_current_pc.GetModule());
159   if (!m_current_pc.IsValid() || !pc_module_sp) {
160     UnwindLogMsg("using architectural default unwind method");
161   }
162 
163   AddressRange addr_range;
164   m_sym_ctx_valid = m_current_pc.ResolveFunctionScope(m_sym_ctx, &addr_range);
165 
166   if (m_sym_ctx.symbol) {
167     UnwindLogMsg("with pc value of 0x%" PRIx64 ", symbol name is '%s'",
168                  current_pc, GetSymbolOrFunctionName(m_sym_ctx).AsCString(""));
169   } else if (m_sym_ctx.function) {
170     UnwindLogMsg("with pc value of 0x%" PRIx64 ", function name is '%s'",
171                  current_pc, GetSymbolOrFunctionName(m_sym_ctx).AsCString(""));
172   } else {
173     UnwindLogMsg("with pc value of 0x%" PRIx64
174                  ", no symbol/function name is known.",
175                  current_pc);
176   }
177 
178   if (IsTrapHandlerSymbol(process, m_sym_ctx)) {
179     m_frame_type = eTrapHandlerFrame;
180   } else {
181     // FIXME:  Detect eDebuggerFrame here.
182     m_frame_type = eNormalFrame;
183   }
184 
185   // If we were able to find a symbol/function, set addr_range to the bounds of
186   // that symbol/function. else treat the current pc value as the start_pc and
187   // record no offset.
188   if (addr_range.GetBaseAddress().IsValid()) {
189     m_start_pc = addr_range.GetBaseAddress();
190     if (m_current_pc.GetSection() == m_start_pc.GetSection()) {
191       m_current_offset = m_current_pc.GetOffset() - m_start_pc.GetOffset();
192     } else if (m_current_pc.GetModule() == m_start_pc.GetModule()) {
193       // This means that whatever symbol we kicked up isn't really correct ---
194       // we should not cross section boundaries ... We really should NULL out
195       // the function/symbol in this case unless there is a bad assumption here
196       // due to inlined functions?
197       m_current_offset =
198           m_current_pc.GetFileAddress() - m_start_pc.GetFileAddress();
199     }
200     m_current_offset_backed_up_one = m_current_offset;
201   } else {
202     m_start_pc = m_current_pc;
203     m_current_offset = -1;
204     m_current_offset_backed_up_one = -1;
205   }
206 
207   // We've set m_frame_type and m_sym_ctx before these calls.
208 
209   m_fast_unwind_plan_sp = GetFastUnwindPlanForFrame();
210   m_full_unwind_plan_sp = GetFullUnwindPlanForFrame();
211 
212   UnwindPlan::RowSP active_row;
213   lldb::RegisterKind row_register_kind = eRegisterKindGeneric;
214 
215   // If we have LanguageRuntime UnwindPlan for this unwind, use those
216   // rules to find the caller frame instead of the function's normal
217   // UnwindPlans.  The full unwind plan for this frame will be
218   // the LanguageRuntime-provided unwind plan, and there will not be a
219   // fast unwind plan.
220   if (lang_runtime_plan_sp.get()) {
221     active_row =
222         lang_runtime_plan_sp->GetRowForFunctionOffset(m_current_offset);
223     row_register_kind = lang_runtime_plan_sp->GetRegisterKind();
224     if (!ReadFrameAddress(row_register_kind, active_row->GetCFAValue(),
225                           m_cfa)) {
226       UnwindLogMsg("Cannot set cfa");
227     } else {
228       m_full_unwind_plan_sp = lang_runtime_plan_sp;
229       if (log) {
230         StreamString active_row_strm;
231         active_row->Dump(active_row_strm, lang_runtime_plan_sp.get(), &m_thread,
232                          m_start_pc.GetLoadAddress(exe_ctx.GetTargetPtr()));
233         UnwindLogMsg("async active row: %s", active_row_strm.GetData());
234       }
235       UnwindLogMsg("m_cfa = 0x%" PRIx64 " m_afa = 0x%" PRIx64, m_cfa, m_afa);
236       UnwindLogMsg(
237           "initialized async frame current pc is 0x%" PRIx64
238           " cfa is 0x%" PRIx64 " afa is 0x%" PRIx64,
239           (uint64_t)m_current_pc.GetLoadAddress(exe_ctx.GetTargetPtr()),
240           (uint64_t)m_cfa, (uint64_t)m_afa);
241 
242       return;
243     }
244   }
245 
246   if (m_full_unwind_plan_sp &&
247       m_full_unwind_plan_sp->PlanValidAtAddress(m_current_pc)) {
248     active_row =
249         m_full_unwind_plan_sp->GetRowForFunctionOffset(m_current_offset);
250     row_register_kind = m_full_unwind_plan_sp->GetRegisterKind();
251     if (active_row.get() && log) {
252       StreamString active_row_strm;
253       active_row->Dump(active_row_strm, m_full_unwind_plan_sp.get(), &m_thread,
254                        m_start_pc.GetLoadAddress(exe_ctx.GetTargetPtr()));
255       UnwindLogMsg("%s", active_row_strm.GetData());
256     }
257   }
258 
259   if (!active_row.get()) {
260     UnwindLogMsg("could not find an unwindplan row for this frame's pc");
261     m_frame_type = eNotAValidFrame;
262     return;
263   }
264 
265   if (!ReadFrameAddress(row_register_kind, active_row->GetCFAValue(), m_cfa)) {
266     // Try the fall back unwind plan since the
267     // full unwind plan failed.
268     FuncUnwindersSP func_unwinders_sp;
269     UnwindPlanSP call_site_unwind_plan;
270     bool cfa_status = false;
271 
272     if (m_sym_ctx_valid) {
273       func_unwinders_sp =
274           pc_module_sp->GetUnwindTable().GetFuncUnwindersContainingAddress(
275               m_current_pc, m_sym_ctx);
276     }
277 
278     if (func_unwinders_sp.get() != nullptr)
279       call_site_unwind_plan = func_unwinders_sp->GetUnwindPlanAtCallSite(
280           process->GetTarget(), m_thread);
281 
282     if (call_site_unwind_plan.get() != nullptr) {
283       m_fallback_unwind_plan_sp = call_site_unwind_plan;
284       if (TryFallbackUnwindPlan())
285         cfa_status = true;
286     }
287     if (!cfa_status) {
288       UnwindLogMsg("could not read CFA value for first frame.");
289       m_frame_type = eNotAValidFrame;
290       return;
291     }
292   } else
293     ReadFrameAddress(row_register_kind, active_row->GetAFAValue(), m_afa);
294 
295   UnwindLogMsg("initialized frame current pc is 0x%" PRIx64 " cfa is 0x%" PRIx64
296                " afa is 0x%" PRIx64 " using %s UnwindPlan",
297                (uint64_t)m_current_pc.GetLoadAddress(exe_ctx.GetTargetPtr()),
298                (uint64_t)m_cfa,
299                (uint64_t)m_afa,
300                m_full_unwind_plan_sp->GetSourceName().GetCString());
301 }
302 
303 // Initialize a RegisterContextUnwind for the non-zeroth frame -- rely on the
304 // RegisterContextUnwind "below" it to provide things like its current pc value.
305 
306 void RegisterContextUnwind::InitializeNonZerothFrame() {
307   Log *log = GetLog(LLDBLog::Unwind);
308   if (IsFrameZero()) {
309     m_frame_type = eNotAValidFrame;
310     UnwindLogMsg("non-zeroth frame tests positive for IsFrameZero -- that "
311                  "shouldn't happen.");
312     return;
313   }
314 
315   if (!GetNextFrame().get() || !GetNextFrame()->IsValid()) {
316     m_frame_type = eNotAValidFrame;
317     UnwindLogMsg("Could not get next frame, marking this frame as invalid.");
318     return;
319   }
320   if (!m_thread.GetRegisterContext()) {
321     m_frame_type = eNotAValidFrame;
322     UnwindLogMsg("Could not get register context for this thread, marking this "
323                  "frame as invalid.");
324     return;
325   }
326 
327   ExecutionContext exe_ctx(m_thread.shared_from_this());
328   Process *process = exe_ctx.GetProcessPtr();
329 
330   // Some languages may have a logical parent stack frame which is
331   // not a real stack frame, but the programmer would consider it to
332   // be the caller of the frame, e.g. Swift asynchronous frames.
333   //
334   // A LanguageRuntime may provide an UnwindPlan that is used in this
335   // stack trace base on the RegisterContext contents, intsead
336   // of the normal UnwindPlans we would use for the return-pc.
337   UnwindPlanSP lang_runtime_plan_sp = LanguageRuntime::GetRuntimeUnwindPlan(
338       m_thread, this, m_behaves_like_zeroth_frame);
339   if (lang_runtime_plan_sp.get()) {
340     UnwindLogMsg("This is an async frame");
341   }
342 
343   addr_t pc;
344   if (!ReadGPRValue(eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC, pc)) {
345     UnwindLogMsg("could not get pc value");
346     m_frame_type = eNotAValidFrame;
347     return;
348   }
349 
350   // Let ABIs fixup code addresses to make sure they are valid. In ARM ABIs
351   // this will strip bit zero in case we read a PC from memory or from the LR.
352   ABI *abi = process->GetABI().get();
353   if (abi)
354     pc = abi->FixCodeAddress(pc);
355 
356   if (log) {
357     UnwindLogMsg("pc = 0x%" PRIx64, pc);
358     addr_t reg_val;
359     if (ReadGPRValue(eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FP, reg_val))
360       UnwindLogMsg("fp = 0x%" PRIx64, reg_val);
361     if (ReadGPRValue(eRegisterKindGeneric, LLDB_REGNUM_GENERIC_SP, reg_val))
362       UnwindLogMsg("sp = 0x%" PRIx64, reg_val);
363   }
364 
365   // A pc of 0x0 means it's the end of the stack crawl unless we're above a trap
366   // handler function
367   bool above_trap_handler = false;
368   if (GetNextFrame().get() && GetNextFrame()->IsValid() &&
369       GetNextFrame()->IsTrapHandlerFrame())
370     above_trap_handler = true;
371 
372   if (pc == 0 || pc == 0x1) {
373     if (!above_trap_handler) {
374       m_frame_type = eNotAValidFrame;
375       UnwindLogMsg("this frame has a pc of 0x0");
376       return;
377     }
378   }
379 
380   const bool allow_section_end = true;
381   m_current_pc.SetLoadAddress(pc, &process->GetTarget(), allow_section_end);
382 
383   // If we don't have a Module for some reason, we're not going to find
384   // symbol/function information - just stick in some reasonable defaults and
385   // hope we can unwind past this frame.  If we're above a trap handler,
386   // we may be at a bogus address because we jumped through a bogus function
387   // pointer and trapped, so don't force the arch default unwind plan in that
388   // case.
389   ModuleSP pc_module_sp(m_current_pc.GetModule());
390   if ((!m_current_pc.IsValid() || !pc_module_sp) &&
391       above_trap_handler == false) {
392     UnwindLogMsg("using architectural default unwind method");
393 
394     // Test the pc value to see if we know it's in an unmapped/non-executable
395     // region of memory.
396     uint32_t permissions;
397     if (process->GetLoadAddressPermissions(pc, permissions) &&
398         (permissions & ePermissionsExecutable) == 0) {
399       // If this is the second frame off the stack, we may have unwound the
400       // first frame incorrectly.  But using the architecture default unwind
401       // plan may get us back on track -- albeit possibly skipping a real
402       // frame.  Give this frame a clearly-invalid pc and see if we can get any
403       // further.
404       if (GetNextFrame().get() && GetNextFrame()->IsValid() &&
405           GetNextFrame()->IsFrameZero()) {
406         UnwindLogMsg("had a pc of 0x%" PRIx64 " which is not in executable "
407                                               "memory but on frame 1 -- "
408                                               "allowing it once.",
409                      (uint64_t)pc);
410         m_frame_type = eSkipFrame;
411       } else {
412         // anywhere other than the second frame, a non-executable pc means
413         // we're off in the weeds -- stop now.
414         m_frame_type = eNotAValidFrame;
415         UnwindLogMsg("pc is in a non-executable section of memory and this "
416                      "isn't the 2nd frame in the stack walk.");
417         return;
418       }
419     }
420 
421     if (abi) {
422       m_fast_unwind_plan_sp.reset();
423       m_full_unwind_plan_sp =
424           std::make_shared<UnwindPlan>(lldb::eRegisterKindGeneric);
425       abi->CreateDefaultUnwindPlan(*m_full_unwind_plan_sp);
426       if (m_frame_type != eSkipFrame) // don't override eSkipFrame
427       {
428         m_frame_type = eNormalFrame;
429       }
430       m_all_registers_available = false;
431       m_current_offset = -1;
432       m_current_offset_backed_up_one = -1;
433       RegisterKind row_register_kind = m_full_unwind_plan_sp->GetRegisterKind();
434       UnwindPlan::RowSP row = m_full_unwind_plan_sp->GetRowForFunctionOffset(0);
435       if (row.get()) {
436         if (!ReadFrameAddress(row_register_kind, row->GetCFAValue(), m_cfa)) {
437           UnwindLogMsg("failed to get cfa value");
438           if (m_frame_type != eSkipFrame) // don't override eSkipFrame
439           {
440             m_frame_type = eNotAValidFrame;
441           }
442           return;
443         }
444 
445         ReadFrameAddress(row_register_kind, row->GetAFAValue(), m_afa);
446 
447         // A couple of sanity checks..
448         if (m_cfa == LLDB_INVALID_ADDRESS || m_cfa == 0 || m_cfa == 1) {
449           UnwindLogMsg("could not find a valid cfa address");
450           m_frame_type = eNotAValidFrame;
451           return;
452         }
453 
454         // m_cfa should point into the stack memory; if we can query memory
455         // region permissions, see if the memory is allocated & readable.
456         if (process->GetLoadAddressPermissions(m_cfa, permissions) &&
457             (permissions & ePermissionsReadable) == 0) {
458           m_frame_type = eNotAValidFrame;
459           UnwindLogMsg(
460               "the CFA points to a region of memory that is not readable");
461           return;
462         }
463       } else {
464         UnwindLogMsg("could not find a row for function offset zero");
465         m_frame_type = eNotAValidFrame;
466         return;
467       }
468 
469       if (CheckIfLoopingStack()) {
470         TryFallbackUnwindPlan();
471         if (CheckIfLoopingStack()) {
472           UnwindLogMsg("same CFA address as next frame, assuming the unwind is "
473                        "looping - stopping");
474           m_frame_type = eNotAValidFrame;
475           return;
476         }
477       }
478 
479       UnwindLogMsg("initialized frame cfa is 0x%" PRIx64 " afa is 0x%" PRIx64,
480                    (uint64_t)m_cfa, (uint64_t)m_afa);
481       return;
482     }
483     m_frame_type = eNotAValidFrame;
484     UnwindLogMsg("could not find any symbol for this pc, or a default unwind "
485                  "plan, to continue unwind.");
486     return;
487   }
488 
489   AddressRange addr_range;
490   m_sym_ctx_valid = m_current_pc.ResolveFunctionScope(m_sym_ctx, &addr_range);
491 
492   if (m_sym_ctx.symbol) {
493     UnwindLogMsg("with pc value of 0x%" PRIx64 ", symbol name is '%s'", pc,
494                  GetSymbolOrFunctionName(m_sym_ctx).AsCString(""));
495   } else if (m_sym_ctx.function) {
496     UnwindLogMsg("with pc value of 0x%" PRIx64 ", function name is '%s'", pc,
497                  GetSymbolOrFunctionName(m_sym_ctx).AsCString(""));
498   } else {
499     UnwindLogMsg("with pc value of 0x%" PRIx64
500                  ", no symbol/function name is known.",
501                  pc);
502   }
503 
504   bool decr_pc_and_recompute_addr_range;
505 
506   if (!m_sym_ctx_valid) {
507     // Always decrement and recompute if the symbol lookup failed
508     decr_pc_and_recompute_addr_range = true;
509   } else if (GetNextFrame()->m_frame_type == eTrapHandlerFrame ||
510              GetNextFrame()->m_frame_type == eDebuggerFrame) {
511     // Don't decrement if we're "above" an asynchronous event like
512     // sigtramp.
513     decr_pc_and_recompute_addr_range = false;
514   } else if (!addr_range.GetBaseAddress().IsValid() ||
515              addr_range.GetBaseAddress().GetSection() != m_current_pc.GetSection() ||
516              addr_range.GetBaseAddress().GetOffset() != m_current_pc.GetOffset()) {
517     // If our "current" pc isn't the start of a function, no need
518     // to decrement and recompute.
519     decr_pc_and_recompute_addr_range = false;
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     int valid_offset = -1;
640     if (IsUnwindPlanValidForCurrentPC(m_full_unwind_plan_sp, valid_offset)) {
641       active_row = m_full_unwind_plan_sp->GetRowForFunctionOffset(valid_offset);
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   int valid_offset = -1;
1011   if (IsUnwindPlanValidForCurrentPC(unwind_plan_sp, valid_offset)) {
1012     UnwindLogMsgVerbose("frame uses %s for full UnwindPlan because this "
1013                         "is the call-site unwind plan",
1014                         unwind_plan_sp->GetSourceName().GetCString());
1015     return unwind_plan_sp;
1016   }
1017 
1018   // We'd prefer to use an UnwindPlan intended for call sites when we're at a
1019   // call site but if we've struck out on that, fall back to using the non-
1020   // call-site assembly inspection UnwindPlan if possible.
1021   if (process) {
1022     unwind_plan_sp = func_unwinders_sp->GetUnwindPlanAtNonCallSite(
1023         process->GetTarget(), m_thread);
1024   }
1025   if (unwind_plan_sp &&
1026       unwind_plan_sp->GetSourcedFromCompiler() == eLazyBoolNo) {
1027     // We probably have an UnwindPlan created by inspecting assembly
1028     // instructions. The assembly profilers work really well with compiler-
1029     // generated functions but hand- written assembly can be problematic. We
1030     // set the eh_frame based unwind plan as our fallback unwind plan if
1031     // instruction emulation doesn't work out even for non call sites if it is
1032     // available and use the architecture default unwind plan if it is not
1033     // available. The eh_frame unwind plan is more reliable even on non call
1034     // sites then the architecture default plan and for hand written assembly
1035     // code it is often written in a way that it valid at all location what
1036     // helps in the most common cases when the instruction emulation fails.
1037     UnwindPlanSP call_site_unwind_plan =
1038         func_unwinders_sp->GetUnwindPlanAtCallSite(process->GetTarget(),
1039                                                    m_thread);
1040     if (call_site_unwind_plan &&
1041         call_site_unwind_plan.get() != unwind_plan_sp.get() &&
1042         call_site_unwind_plan->GetSourceName() !=
1043             unwind_plan_sp->GetSourceName()) {
1044       m_fallback_unwind_plan_sp = call_site_unwind_plan;
1045     } else {
1046       m_fallback_unwind_plan_sp = arch_default_unwind_plan_sp;
1047     }
1048   }
1049 
1050   if (IsUnwindPlanValidForCurrentPC(unwind_plan_sp, valid_offset)) {
1051     UnwindLogMsgVerbose("frame uses %s for full UnwindPlan because we "
1052                         "failed to find a call-site unwind plan that would work",
1053                         unwind_plan_sp->GetSourceName().GetCString());
1054     return unwind_plan_sp;
1055   }
1056 
1057   // If nothing else, use the architectural default UnwindPlan and hope that
1058   // does the job.
1059   if (arch_default_unwind_plan_sp)
1060     UnwindLogMsgVerbose(
1061         "frame uses %s for full UnwindPlan because we are falling back "
1062         "to the arch default plan",
1063         arch_default_unwind_plan_sp->GetSourceName().GetCString());
1064   else
1065     UnwindLogMsg(
1066         "Unable to find any UnwindPlan for full unwind of this frame.");
1067 
1068   return arch_default_unwind_plan_sp;
1069 }
1070 
1071 void RegisterContextUnwind::InvalidateAllRegisters() {
1072   m_frame_type = eNotAValidFrame;
1073 }
1074 
1075 size_t RegisterContextUnwind::GetRegisterCount() {
1076   return m_thread.GetRegisterContext()->GetRegisterCount();
1077 }
1078 
1079 const RegisterInfo *RegisterContextUnwind::GetRegisterInfoAtIndex(size_t reg) {
1080   return m_thread.GetRegisterContext()->GetRegisterInfoAtIndex(reg);
1081 }
1082 
1083 size_t RegisterContextUnwind::GetRegisterSetCount() {
1084   return m_thread.GetRegisterContext()->GetRegisterSetCount();
1085 }
1086 
1087 const RegisterSet *RegisterContextUnwind::GetRegisterSet(size_t reg_set) {
1088   return m_thread.GetRegisterContext()->GetRegisterSet(reg_set);
1089 }
1090 
1091 uint32_t RegisterContextUnwind::ConvertRegisterKindToRegisterNumber(
1092     lldb::RegisterKind kind, uint32_t num) {
1093   return m_thread.GetRegisterContext()->ConvertRegisterKindToRegisterNumber(
1094       kind, num);
1095 }
1096 
1097 bool RegisterContextUnwind::ReadRegisterValueFromRegisterLocation(
1098     lldb_private::UnwindLLDB::RegisterLocation regloc,
1099     const RegisterInfo *reg_info, RegisterValue &value) {
1100   if (!IsValid())
1101     return false;
1102   bool success = false;
1103 
1104   switch (regloc.type) {
1105   case UnwindLLDB::RegisterLocation::eRegisterInLiveRegisterContext: {
1106     const RegisterInfo *other_reg_info =
1107         GetRegisterInfoAtIndex(regloc.location.register_number);
1108 
1109     if (!other_reg_info)
1110       return false;
1111 
1112     success =
1113         m_thread.GetRegisterContext()->ReadRegister(other_reg_info, value);
1114   } break;
1115   case UnwindLLDB::RegisterLocation::eRegisterInRegister: {
1116     const RegisterInfo *other_reg_info =
1117         GetRegisterInfoAtIndex(regloc.location.register_number);
1118 
1119     if (!other_reg_info)
1120       return false;
1121 
1122     if (IsFrameZero()) {
1123       success =
1124           m_thread.GetRegisterContext()->ReadRegister(other_reg_info, value);
1125     } else {
1126       success = GetNextFrame()->ReadRegister(other_reg_info, value);
1127     }
1128   } break;
1129   case UnwindLLDB::RegisterLocation::eRegisterValueInferred:
1130     success =
1131         value.SetUInt(regloc.location.inferred_value, reg_info->byte_size);
1132     break;
1133 
1134   case UnwindLLDB::RegisterLocation::eRegisterNotSaved:
1135     break;
1136   case UnwindLLDB::RegisterLocation::eRegisterSavedAtHostMemoryLocation:
1137     llvm_unreachable("FIXME debugger inferior function call unwind");
1138   case UnwindLLDB::RegisterLocation::eRegisterSavedAtMemoryLocation: {
1139     Status error(ReadRegisterValueFromMemory(
1140         reg_info, regloc.location.target_memory_location, reg_info->byte_size,
1141         value));
1142     success = error.Success();
1143   } break;
1144   default:
1145     llvm_unreachable("Unknown RegisterLocation type.");
1146   }
1147   return success;
1148 }
1149 
1150 bool RegisterContextUnwind::WriteRegisterValueToRegisterLocation(
1151     lldb_private::UnwindLLDB::RegisterLocation regloc,
1152     const RegisterInfo *reg_info, const RegisterValue &value) {
1153   if (!IsValid())
1154     return false;
1155 
1156   bool success = false;
1157 
1158   switch (regloc.type) {
1159   case UnwindLLDB::RegisterLocation::eRegisterInLiveRegisterContext: {
1160     const RegisterInfo *other_reg_info =
1161         GetRegisterInfoAtIndex(regloc.location.register_number);
1162     success =
1163         m_thread.GetRegisterContext()->WriteRegister(other_reg_info, value);
1164   } break;
1165   case UnwindLLDB::RegisterLocation::eRegisterInRegister: {
1166     const RegisterInfo *other_reg_info =
1167         GetRegisterInfoAtIndex(regloc.location.register_number);
1168     if (IsFrameZero()) {
1169       success =
1170           m_thread.GetRegisterContext()->WriteRegister(other_reg_info, value);
1171     } else {
1172       success = GetNextFrame()->WriteRegister(other_reg_info, value);
1173     }
1174   } break;
1175   case UnwindLLDB::RegisterLocation::eRegisterValueInferred:
1176   case UnwindLLDB::RegisterLocation::eRegisterNotSaved:
1177     break;
1178   case UnwindLLDB::RegisterLocation::eRegisterSavedAtHostMemoryLocation:
1179     llvm_unreachable("FIXME debugger inferior function call unwind");
1180   case UnwindLLDB::RegisterLocation::eRegisterSavedAtMemoryLocation: {
1181     Status error(WriteRegisterValueToMemory(
1182         reg_info, regloc.location.target_memory_location, reg_info->byte_size,
1183         value));
1184     success = error.Success();
1185   } break;
1186   default:
1187     llvm_unreachable("Unknown RegisterLocation type.");
1188   }
1189   return success;
1190 }
1191 
1192 bool RegisterContextUnwind::IsValid() const {
1193   return m_frame_type != eNotAValidFrame;
1194 }
1195 
1196 // After the final stack frame in a stack walk we'll get one invalid
1197 // (eNotAValidFrame) stack frame -- one past the end of the stack walk.  But
1198 // higher-level code will need to tell the difference between "the unwind plan
1199 // below this frame failed" versus "we successfully completed the stack walk"
1200 // so this method helps to disambiguate that.
1201 
1202 bool RegisterContextUnwind::IsTrapHandlerFrame() const {
1203   return m_frame_type == eTrapHandlerFrame;
1204 }
1205 
1206 // A skip frame is a bogus frame on the stack -- but one where we're likely to
1207 // find a real frame farther
1208 // up the stack if we keep looking.  It's always the second frame in an unwind
1209 // (i.e. the first frame after frame zero) where unwinding can be the
1210 // trickiest.  Ideally we'll mark up this frame in some way so the user knows
1211 // we're displaying bad data and we may have skipped one frame of their real
1212 // program in the process of getting back on track.
1213 
1214 bool RegisterContextUnwind::IsSkipFrame() const {
1215   return m_frame_type == eSkipFrame;
1216 }
1217 
1218 bool RegisterContextUnwind::IsTrapHandlerSymbol(
1219     lldb_private::Process *process,
1220     const lldb_private::SymbolContext &m_sym_ctx) const {
1221   PlatformSP platform_sp(process->GetTarget().GetPlatform());
1222   if (platform_sp) {
1223     const std::vector<ConstString> trap_handler_names(
1224         platform_sp->GetTrapHandlerSymbolNames());
1225     for (ConstString name : trap_handler_names) {
1226       if ((m_sym_ctx.function && m_sym_ctx.function->GetName() == name) ||
1227           (m_sym_ctx.symbol && m_sym_ctx.symbol->GetName() == name)) {
1228         return true;
1229       }
1230     }
1231   }
1232   const std::vector<ConstString> user_specified_trap_handler_names(
1233       m_parent_unwind.GetUserSpecifiedTrapHandlerFunctionNames());
1234   for (ConstString name : user_specified_trap_handler_names) {
1235     if ((m_sym_ctx.function && m_sym_ctx.function->GetName() == name) ||
1236         (m_sym_ctx.symbol && m_sym_ctx.symbol->GetName() == name)) {
1237       return true;
1238     }
1239   }
1240 
1241   return false;
1242 }
1243 
1244 // Answer the question: Where did THIS frame save the CALLER frame ("previous"
1245 // frame)'s register value?
1246 
1247 enum UnwindLLDB::RegisterSearchResult
1248 RegisterContextUnwind::SavedLocationForRegister(
1249     uint32_t lldb_regnum, lldb_private::UnwindLLDB::RegisterLocation &regloc) {
1250   RegisterNumber regnum(m_thread, eRegisterKindLLDB, lldb_regnum);
1251   Log *log = GetLog(LLDBLog::Unwind);
1252 
1253   // Have we already found this register location?
1254   if (!m_registers.empty()) {
1255     std::map<uint32_t,
1256              lldb_private::UnwindLLDB::RegisterLocation>::const_iterator
1257         iterator;
1258     iterator = m_registers.find(regnum.GetAsKind(eRegisterKindLLDB));
1259     if (iterator != m_registers.end()) {
1260       regloc = iterator->second;
1261       UnwindLogMsg("supplying caller's saved %s (%d)'s location, cached",
1262                    regnum.GetName(), regnum.GetAsKind(eRegisterKindLLDB));
1263       return UnwindLLDB::RegisterSearchResult::eRegisterFound;
1264     }
1265   }
1266 
1267   // Look through the available UnwindPlans for the register location.
1268 
1269   UnwindPlan::Row::RegisterLocation unwindplan_regloc;
1270   bool have_unwindplan_regloc = false;
1271   RegisterKind unwindplan_registerkind = kNumRegisterKinds;
1272 
1273   if (m_fast_unwind_plan_sp) {
1274     UnwindPlan::RowSP active_row =
1275         m_fast_unwind_plan_sp->GetRowForFunctionOffset(m_current_offset);
1276     unwindplan_registerkind = m_fast_unwind_plan_sp->GetRegisterKind();
1277     if (regnum.GetAsKind(unwindplan_registerkind) == LLDB_INVALID_REGNUM) {
1278       UnwindLogMsg("could not convert lldb regnum %s (%d) into %d RegisterKind "
1279                    "reg numbering scheme",
1280                    regnum.GetName(), regnum.GetAsKind(eRegisterKindLLDB),
1281                    (int)unwindplan_registerkind);
1282       return UnwindLLDB::RegisterSearchResult::eRegisterNotFound;
1283     }
1284     // The architecture default unwind plan marks unknown registers as
1285     // Undefined so that we don't forward them up the stack when a
1286     // jitted stack frame may have overwritten them.  But when the
1287     // arch default unwind plan is used as the Fast Unwind Plan, we
1288     // need to recognize this & switch over to the Full Unwind Plan
1289     // to see what unwind rule that (more knoweldgeable, probably)
1290     // UnwindPlan has.  If the full UnwindPlan says the register
1291     // location is Undefined, then it really is.
1292     if (active_row->GetRegisterInfo(regnum.GetAsKind(unwindplan_registerkind),
1293                                     unwindplan_regloc) &&
1294         !unwindplan_regloc.IsUndefined()) {
1295       UnwindLogMsg(
1296           "supplying caller's saved %s (%d)'s location using FastUnwindPlan",
1297           regnum.GetName(), regnum.GetAsKind(eRegisterKindLLDB));
1298       have_unwindplan_regloc = true;
1299     }
1300   }
1301 
1302   if (!have_unwindplan_regloc) {
1303     // m_full_unwind_plan_sp being NULL means that we haven't tried to find a
1304     // full UnwindPlan yet
1305     bool got_new_full_unwindplan = false;
1306     if (!m_full_unwind_plan_sp) {
1307       m_full_unwind_plan_sp = GetFullUnwindPlanForFrame();
1308       got_new_full_unwindplan = true;
1309     }
1310 
1311     if (m_full_unwind_plan_sp) {
1312       RegisterNumber pc_regnum(m_thread, eRegisterKindGeneric,
1313                                LLDB_REGNUM_GENERIC_PC);
1314 
1315       UnwindPlan::RowSP active_row =
1316           m_full_unwind_plan_sp->GetRowForFunctionOffset(m_current_offset);
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     DWARFExpression dwarfexpr(opcode_ctx, dwarfdata, nullptr);
1646     dwarfexpr.SetRegisterKind(unwindplan_registerkind);
1647     Value cfa_val = Scalar(m_cfa);
1648     cfa_val.SetValueType(Value::ValueType::LoadAddress);
1649     Value result;
1650     Status error;
1651     if (dwarfexpr.Evaluate(&exe_ctx, this, 0, &cfa_val, nullptr, result,
1652                            &error)) {
1653       addr_t val;
1654       val = result.GetScalar().ULongLong();
1655       if (unwindplan_regloc.IsDWARFExpression()) {
1656         regloc.type = UnwindLLDB::RegisterLocation::eRegisterValueInferred;
1657         regloc.location.inferred_value = val;
1658         m_registers[regnum.GetAsKind(eRegisterKindLLDB)] = regloc;
1659         UnwindLogMsg("supplying caller's register %s (%d) via DWARF expression "
1660                      "(IsDWARFExpression)",
1661                      regnum.GetName(), regnum.GetAsKind(eRegisterKindLLDB));
1662         return UnwindLLDB::RegisterSearchResult::eRegisterFound;
1663       } else {
1664         regloc.type =
1665             UnwindLLDB::RegisterLocation::eRegisterSavedAtMemoryLocation;
1666         regloc.location.target_memory_location = val;
1667         m_registers[regnum.GetAsKind(eRegisterKindLLDB)] = regloc;
1668         UnwindLogMsg("supplying caller's register %s (%d) via DWARF expression "
1669                      "(IsAtDWARFExpression)",
1670                      regnum.GetName(), regnum.GetAsKind(eRegisterKindLLDB));
1671         return UnwindLLDB::RegisterSearchResult::eRegisterFound;
1672       }
1673     }
1674     UnwindLogMsg("tried to use IsDWARFExpression or IsAtDWARFExpression for %s "
1675                  "(%d) but failed",
1676                  regnum.GetName(), regnum.GetAsKind(eRegisterKindLLDB));
1677     return UnwindLLDB::RegisterSearchResult::eRegisterNotFound;
1678   }
1679 
1680   UnwindLogMsg("no save location for %s (%d) in this stack frame",
1681                regnum.GetName(), regnum.GetAsKind(eRegisterKindLLDB));
1682 
1683   // FIXME UnwindPlan::Row types atDWARFExpression and isDWARFExpression are
1684   // unsupported.
1685 
1686   return UnwindLLDB::RegisterSearchResult::eRegisterNotFound;
1687 }
1688 
1689 // TryFallbackUnwindPlan() -- this method is a little tricky.
1690 //
1691 // When this is called, the frame above -- the caller frame, the "previous"
1692 // frame -- is invalid or bad.
1693 //
1694 // Instead of stopping the stack walk here, we'll try a different UnwindPlan
1695 // and see if we can get a valid frame above us.
1696 //
1697 // This most often happens when an unwind plan based on assembly instruction
1698 // inspection is not correct -- mostly with hand-written assembly functions or
1699 // functions where the stack frame is set up "out of band", e.g. the kernel
1700 // saved the register context and then called an asynchronous trap handler like
1701 // _sigtramp.
1702 //
1703 // Often in these cases, if we just do a dumb stack walk we'll get past this
1704 // tricky frame and our usual techniques can continue to be used.
1705 
1706 bool RegisterContextUnwind::TryFallbackUnwindPlan() {
1707   if (m_fallback_unwind_plan_sp.get() == nullptr)
1708     return false;
1709 
1710   if (m_full_unwind_plan_sp.get() == nullptr)
1711     return false;
1712 
1713   if (m_full_unwind_plan_sp.get() == m_fallback_unwind_plan_sp.get() ||
1714       m_full_unwind_plan_sp->GetSourceName() ==
1715           m_fallback_unwind_plan_sp->GetSourceName()) {
1716     return false;
1717   }
1718 
1719   // If a compiler generated unwind plan failed, trying the arch default
1720   // unwindplan isn't going to do any better.
1721   if (m_full_unwind_plan_sp->GetSourcedFromCompiler() == eLazyBoolYes)
1722     return false;
1723 
1724   // Get the caller's pc value and our own CFA value. Swap in the fallback
1725   // unwind plan, re-fetch the caller's pc value and CFA value. If they're the
1726   // same, then the fallback unwind plan provides no benefit.
1727 
1728   RegisterNumber pc_regnum(m_thread, eRegisterKindGeneric,
1729                            LLDB_REGNUM_GENERIC_PC);
1730 
1731   addr_t old_caller_pc_value = LLDB_INVALID_ADDRESS;
1732   addr_t new_caller_pc_value = LLDB_INVALID_ADDRESS;
1733   UnwindLLDB::RegisterLocation regloc;
1734   if (SavedLocationForRegister(pc_regnum.GetAsKind(eRegisterKindLLDB),
1735                                regloc) ==
1736       UnwindLLDB::RegisterSearchResult::eRegisterFound) {
1737     const RegisterInfo *reg_info =
1738         GetRegisterInfoAtIndex(pc_regnum.GetAsKind(eRegisterKindLLDB));
1739     if (reg_info) {
1740       RegisterValue reg_value;
1741       if (ReadRegisterValueFromRegisterLocation(regloc, reg_info, reg_value)) {
1742         old_caller_pc_value = reg_value.GetAsUInt64();
1743         if (ProcessSP process_sp = m_thread.GetProcess()) {
1744           if (ABISP abi = process_sp->GetABI())
1745             old_caller_pc_value = abi->FixCodeAddress(old_caller_pc_value);
1746         }
1747       }
1748     }
1749   }
1750 
1751   // This is a tricky wrinkle!  If SavedLocationForRegister() detects a really
1752   // impossible register location for the full unwind plan, it may call
1753   // ForceSwitchToFallbackUnwindPlan() which in turn replaces the full
1754   // unwindplan with the fallback... in short, we're done, we're using the
1755   // fallback UnwindPlan. We checked if m_fallback_unwind_plan_sp was nullptr
1756   // at the top -- the only way it became nullptr since then is via
1757   // SavedLocationForRegister().
1758   if (m_fallback_unwind_plan_sp.get() == nullptr)
1759     return true;
1760 
1761   // Switch the full UnwindPlan to be the fallback UnwindPlan.  If we decide
1762   // this isn't working, we need to restore. We'll also need to save & restore
1763   // the value of the m_cfa ivar.  Save is down below a bit in 'old_cfa'.
1764   UnwindPlanSP original_full_unwind_plan_sp = m_full_unwind_plan_sp;
1765   addr_t old_cfa = m_cfa;
1766   addr_t old_afa = m_afa;
1767 
1768   m_registers.clear();
1769 
1770   m_full_unwind_plan_sp = m_fallback_unwind_plan_sp;
1771 
1772   UnwindPlan::RowSP active_row =
1773       m_fallback_unwind_plan_sp->GetRowForFunctionOffset(m_current_offset);
1774 
1775   if (active_row &&
1776       active_row->GetCFAValue().GetValueType() !=
1777           UnwindPlan::Row::FAValue::unspecified) {
1778     addr_t new_cfa;
1779     if (!ReadFrameAddress(m_fallback_unwind_plan_sp->GetRegisterKind(),
1780                             active_row->GetCFAValue(), new_cfa) ||
1781         new_cfa == 0 || new_cfa == 1 || new_cfa == LLDB_INVALID_ADDRESS) {
1782       UnwindLogMsg("failed to get cfa with fallback unwindplan");
1783       m_fallback_unwind_plan_sp.reset();
1784       m_full_unwind_plan_sp = original_full_unwind_plan_sp;
1785       return false;
1786     }
1787     m_cfa = new_cfa;
1788 
1789     ReadFrameAddress(m_fallback_unwind_plan_sp->GetRegisterKind(),
1790                      active_row->GetAFAValue(), m_afa);
1791 
1792     if (SavedLocationForRegister(pc_regnum.GetAsKind(eRegisterKindLLDB),
1793                                  regloc) ==
1794         UnwindLLDB::RegisterSearchResult::eRegisterFound) {
1795       const RegisterInfo *reg_info =
1796           GetRegisterInfoAtIndex(pc_regnum.GetAsKind(eRegisterKindLLDB));
1797       if (reg_info) {
1798         RegisterValue reg_value;
1799         if (ReadRegisterValueFromRegisterLocation(regloc, reg_info,
1800                                                   reg_value)) {
1801           new_caller_pc_value = reg_value.GetAsUInt64();
1802           if (ProcessSP process_sp = m_thread.GetProcess()) {
1803             if (ABISP abi = process_sp->GetABI())
1804               new_caller_pc_value = abi->FixCodeAddress(new_caller_pc_value);
1805           }
1806         }
1807       }
1808     }
1809 
1810     if (new_caller_pc_value == LLDB_INVALID_ADDRESS) {
1811       UnwindLogMsg("failed to get a pc value for the caller frame with the "
1812                    "fallback unwind plan");
1813       m_fallback_unwind_plan_sp.reset();
1814       m_full_unwind_plan_sp = original_full_unwind_plan_sp;
1815       m_cfa = old_cfa;
1816       m_afa = old_afa;
1817       return false;
1818     }
1819 
1820     if (old_caller_pc_value == new_caller_pc_value &&
1821         m_cfa == old_cfa &&
1822         m_afa == old_afa) {
1823       UnwindLogMsg("fallback unwind plan got the same values for this frame "
1824                    "CFA and caller frame pc, not using");
1825       m_fallback_unwind_plan_sp.reset();
1826       m_full_unwind_plan_sp = original_full_unwind_plan_sp;
1827       return false;
1828     }
1829 
1830     UnwindLogMsg("trying to unwind from this function with the UnwindPlan '%s' "
1831                  "because UnwindPlan '%s' failed.",
1832                  m_fallback_unwind_plan_sp->GetSourceName().GetCString(),
1833                  original_full_unwind_plan_sp->GetSourceName().GetCString());
1834 
1835     // We've copied the fallback unwind plan into the full - now clear the
1836     // fallback.
1837     m_fallback_unwind_plan_sp.reset();
1838     PropagateTrapHandlerFlagFromUnwindPlan(m_full_unwind_plan_sp);
1839   }
1840 
1841   return true;
1842 }
1843 
1844 bool RegisterContextUnwind::ForceSwitchToFallbackUnwindPlan() {
1845   if (m_fallback_unwind_plan_sp.get() == nullptr)
1846     return false;
1847 
1848   if (m_full_unwind_plan_sp.get() == nullptr)
1849     return false;
1850 
1851   if (m_full_unwind_plan_sp.get() == m_fallback_unwind_plan_sp.get() ||
1852       m_full_unwind_plan_sp->GetSourceName() ==
1853           m_fallback_unwind_plan_sp->GetSourceName()) {
1854     return false;
1855   }
1856 
1857   UnwindPlan::RowSP active_row =
1858       m_fallback_unwind_plan_sp->GetRowForFunctionOffset(m_current_offset);
1859 
1860   if (active_row &&
1861       active_row->GetCFAValue().GetValueType() !=
1862           UnwindPlan::Row::FAValue::unspecified) {
1863     addr_t new_cfa;
1864     if (!ReadFrameAddress(m_fallback_unwind_plan_sp->GetRegisterKind(),
1865                             active_row->GetCFAValue(), new_cfa) ||
1866         new_cfa == 0 || new_cfa == 1 || new_cfa == LLDB_INVALID_ADDRESS) {
1867       UnwindLogMsg("failed to get cfa with fallback unwindplan");
1868       m_fallback_unwind_plan_sp.reset();
1869       return false;
1870     }
1871 
1872     ReadFrameAddress(m_fallback_unwind_plan_sp->GetRegisterKind(),
1873                      active_row->GetAFAValue(), m_afa);
1874 
1875     m_full_unwind_plan_sp = m_fallback_unwind_plan_sp;
1876     m_fallback_unwind_plan_sp.reset();
1877 
1878     m_registers.clear();
1879 
1880     m_cfa = new_cfa;
1881 
1882     PropagateTrapHandlerFlagFromUnwindPlan(m_full_unwind_plan_sp);
1883 
1884     UnwindLogMsg("switched unconditionally to the fallback unwindplan %s",
1885                  m_full_unwind_plan_sp->GetSourceName().GetCString());
1886     return true;
1887   }
1888   return false;
1889 }
1890 
1891 void RegisterContextUnwind::PropagateTrapHandlerFlagFromUnwindPlan(
1892     lldb::UnwindPlanSP unwind_plan) {
1893   if (unwind_plan->GetUnwindPlanForSignalTrap() != eLazyBoolYes) {
1894     // Unwind plan does not indicate trap handler.  Do nothing.  We may
1895     // already be flagged as trap handler flag due to the symbol being
1896     // in the trap handler symbol list, and that should take precedence.
1897     return;
1898   } else if (m_frame_type != eNormalFrame) {
1899     // If this is already a trap handler frame, nothing to do.
1900     // If this is a skip or debug or invalid frame, don't override that.
1901     return;
1902   }
1903 
1904   m_frame_type = eTrapHandlerFrame;
1905 
1906   if (m_current_offset_backed_up_one != m_current_offset) {
1907     // We backed up the pc by 1 to compute the symbol context, but
1908     // now need to undo that because the pc of the trap handler
1909     // frame may in fact be the first instruction of a signal return
1910     // trampoline, rather than the instruction after a call.  This
1911     // happens on systems where the signal handler dispatch code, rather
1912     // than calling the handler and being returned to, jumps to the
1913     // handler after pushing the address of a return trampoline on the
1914     // stack -- on these systems, when the handler returns, control will
1915     // be transferred to the return trampoline, so that's the best
1916     // symbol we can present in the callstack.
1917     UnwindLogMsg("Resetting current offset and re-doing symbol lookup; "
1918                  "old symbol was %s",
1919                  GetSymbolOrFunctionName(m_sym_ctx).AsCString(""));
1920     m_current_offset_backed_up_one = m_current_offset;
1921 
1922     AddressRange addr_range;
1923     m_sym_ctx_valid = m_current_pc.ResolveFunctionScope(m_sym_ctx, &addr_range);
1924 
1925     UnwindLogMsg("Symbol is now %s",
1926                  GetSymbolOrFunctionName(m_sym_ctx).AsCString(""));
1927 
1928     ExecutionContext exe_ctx(m_thread.shared_from_this());
1929     Process *process = exe_ctx.GetProcessPtr();
1930     Target *target = &process->GetTarget();
1931 
1932     m_start_pc = addr_range.GetBaseAddress();
1933     m_current_offset =
1934         m_current_pc.GetLoadAddress(target) - m_start_pc.GetLoadAddress(target);
1935   }
1936 }
1937 
1938 bool RegisterContextUnwind::ReadFrameAddress(
1939     lldb::RegisterKind row_register_kind, UnwindPlan::Row::FAValue &fa,
1940     addr_t &address) {
1941   RegisterValue reg_value;
1942 
1943   address = LLDB_INVALID_ADDRESS;
1944   addr_t cfa_reg_contents;
1945 
1946   switch (fa.GetValueType()) {
1947   case UnwindPlan::Row::FAValue::isRegisterDereferenced: {
1948     RegisterNumber cfa_reg(m_thread, row_register_kind,
1949                            fa.GetRegisterNumber());
1950     if (ReadGPRValue(cfa_reg, cfa_reg_contents)) {
1951       const RegisterInfo *reg_info =
1952           GetRegisterInfoAtIndex(cfa_reg.GetAsKind(eRegisterKindLLDB));
1953       RegisterValue reg_value;
1954       if (reg_info) {
1955         Status error = ReadRegisterValueFromMemory(
1956             reg_info, cfa_reg_contents, reg_info->byte_size, reg_value);
1957         if (error.Success()) {
1958           address = reg_value.GetAsUInt64();
1959           if (ABISP abi_sp = m_thread.GetProcess()->GetABI())
1960             address = abi_sp->FixCodeAddress(address);
1961           UnwindLogMsg(
1962               "CFA value via dereferencing reg %s (%d): reg has val 0x%" PRIx64
1963               ", CFA value is 0x%" PRIx64,
1964               cfa_reg.GetName(), cfa_reg.GetAsKind(eRegisterKindLLDB),
1965               cfa_reg_contents, address);
1966           return true;
1967         } else {
1968           UnwindLogMsg("Tried to deref reg %s (%d) [0x%" PRIx64
1969                        "] but memory read failed.",
1970                        cfa_reg.GetName(), cfa_reg.GetAsKind(eRegisterKindLLDB),
1971                        cfa_reg_contents);
1972         }
1973       }
1974     }
1975     break;
1976   }
1977   case UnwindPlan::Row::FAValue::isRegisterPlusOffset: {
1978     RegisterNumber cfa_reg(m_thread, row_register_kind,
1979                            fa.GetRegisterNumber());
1980     if (ReadGPRValue(cfa_reg, cfa_reg_contents)) {
1981       if (cfa_reg_contents == LLDB_INVALID_ADDRESS || cfa_reg_contents == 0 ||
1982           cfa_reg_contents == 1) {
1983         UnwindLogMsg(
1984             "Got an invalid CFA register value - reg %s (%d), value 0x%" PRIx64,
1985             cfa_reg.GetName(), cfa_reg.GetAsKind(eRegisterKindLLDB),
1986             cfa_reg_contents);
1987         cfa_reg_contents = LLDB_INVALID_ADDRESS;
1988         return false;
1989       }
1990       address = cfa_reg_contents + fa.GetOffset();
1991       UnwindLogMsg(
1992           "CFA is 0x%" PRIx64 ": Register %s (%d) contents are 0x%" PRIx64
1993           ", offset is %d",
1994           address, cfa_reg.GetName(), cfa_reg.GetAsKind(eRegisterKindLLDB),
1995           cfa_reg_contents, fa.GetOffset());
1996       return true;
1997     }
1998     break;
1999   }
2000   case UnwindPlan::Row::FAValue::isDWARFExpression: {
2001     ExecutionContext exe_ctx(m_thread.shared_from_this());
2002     Process *process = exe_ctx.GetProcessPtr();
2003     DataExtractor dwarfdata(fa.GetDWARFExpressionBytes(),
2004                             fa.GetDWARFExpressionLength(),
2005                             process->GetByteOrder(),
2006                             process->GetAddressByteSize());
2007     ModuleSP opcode_ctx;
2008     DWARFExpression dwarfexpr(opcode_ctx, dwarfdata, nullptr);
2009     dwarfexpr.SetRegisterKind(row_register_kind);
2010     Value result;
2011     Status error;
2012     if (dwarfexpr.Evaluate(&exe_ctx, this, 0, nullptr, nullptr, result,
2013                            &error)) {
2014       address = result.GetScalar().ULongLong();
2015       if (ABISP abi_sp = m_thread.GetProcess()->GetABI())
2016         address = abi_sp->FixCodeAddress(address);
2017 
2018       UnwindLogMsg("CFA value set by DWARF expression is 0x%" PRIx64,
2019                    address);
2020       return true;
2021     }
2022     UnwindLogMsg("Failed to set CFA value via DWARF expression: %s",
2023                  error.AsCString());
2024     break;
2025   }
2026   case UnwindPlan::Row::FAValue::isRaSearch: {
2027     Process &process = *m_thread.GetProcess();
2028     lldb::addr_t return_address_hint = GetReturnAddressHint(fa.GetOffset());
2029     if (return_address_hint == LLDB_INVALID_ADDRESS)
2030       return false;
2031     const unsigned max_iterations = 256;
2032     for (unsigned i = 0; i < max_iterations; ++i) {
2033       Status st;
2034       lldb::addr_t candidate_addr =
2035           return_address_hint + i * process.GetAddressByteSize();
2036       lldb::addr_t candidate =
2037           process.ReadPointerFromMemory(candidate_addr, st);
2038       if (st.Fail()) {
2039         UnwindLogMsg("Cannot read memory at 0x%" PRIx64 ": %s", candidate_addr,
2040                      st.AsCString());
2041         return false;
2042       }
2043       Address addr;
2044       uint32_t permissions;
2045       if (process.GetLoadAddressPermissions(candidate, permissions) &&
2046           permissions & lldb::ePermissionsExecutable) {
2047         address = candidate_addr;
2048         UnwindLogMsg("Heuristically found CFA: 0x%" PRIx64, address);
2049         return true;
2050       }
2051     }
2052     UnwindLogMsg("No suitable CFA found");
2053     break;
2054   }
2055   default:
2056     return false;
2057   }
2058   return false;
2059 }
2060 
2061 lldb::addr_t RegisterContextUnwind::GetReturnAddressHint(int32_t plan_offset) {
2062   addr_t hint;
2063   if (!ReadGPRValue(eRegisterKindGeneric, LLDB_REGNUM_GENERIC_SP, hint))
2064     return LLDB_INVALID_ADDRESS;
2065   if (!m_sym_ctx.module_sp || !m_sym_ctx.symbol)
2066     return LLDB_INVALID_ADDRESS;
2067 
2068   hint += plan_offset;
2069 
2070   if (auto next = GetNextFrame()) {
2071     if (!next->m_sym_ctx.module_sp || !next->m_sym_ctx.symbol)
2072       return LLDB_INVALID_ADDRESS;
2073     if (auto expected_size =
2074             next->m_sym_ctx.module_sp->GetSymbolFile()->GetParameterStackSize(
2075                 *next->m_sym_ctx.symbol))
2076       hint += *expected_size;
2077     else {
2078       UnwindLogMsgVerbose("Could not retrieve parameter size: %s",
2079                           llvm::toString(expected_size.takeError()).c_str());
2080       return LLDB_INVALID_ADDRESS;
2081     }
2082   }
2083   return hint;
2084 }
2085 
2086 // Retrieve a general purpose register value for THIS frame, as saved by the
2087 // NEXT frame, i.e. the frame that
2088 // this frame called.  e.g.
2089 //
2090 //  foo () { }
2091 //  bar () { foo (); }
2092 //  main () { bar (); }
2093 //
2094 //  stopped in foo() so
2095 //     frame 0 - foo
2096 //     frame 1 - bar
2097 //     frame 2 - main
2098 //  and this RegisterContext is for frame 1 (bar) - if we want to get the pc
2099 //  value for frame 1, we need to ask
2100 //  where frame 0 (the "next" frame) saved that and retrieve the value.
2101 
2102 bool RegisterContextUnwind::ReadGPRValue(lldb::RegisterKind register_kind,
2103                                          uint32_t regnum, addr_t &value) {
2104   if (!IsValid())
2105     return false;
2106 
2107   uint32_t lldb_regnum;
2108   if (register_kind == eRegisterKindLLDB) {
2109     lldb_regnum = regnum;
2110   } else if (!m_thread.GetRegisterContext()->ConvertBetweenRegisterKinds(
2111                  register_kind, regnum, eRegisterKindLLDB, lldb_regnum)) {
2112     return false;
2113   }
2114 
2115   const RegisterInfo *reg_info = GetRegisterInfoAtIndex(lldb_regnum);
2116   RegisterValue reg_value;
2117   // if this is frame 0 (currently executing frame), get the requested reg
2118   // contents from the actual thread registers
2119   if (IsFrameZero()) {
2120     if (m_thread.GetRegisterContext()->ReadRegister(reg_info, reg_value)) {
2121       value = reg_value.GetAsUInt64();
2122       return true;
2123     }
2124     return false;
2125   }
2126 
2127   bool pc_register = false;
2128   uint32_t generic_regnum;
2129   if (register_kind == eRegisterKindGeneric &&
2130       (regnum == LLDB_REGNUM_GENERIC_PC || regnum == LLDB_REGNUM_GENERIC_RA)) {
2131     pc_register = true;
2132   } else if (m_thread.GetRegisterContext()->ConvertBetweenRegisterKinds(
2133                  register_kind, regnum, eRegisterKindGeneric, generic_regnum) &&
2134              (generic_regnum == LLDB_REGNUM_GENERIC_PC ||
2135               generic_regnum == LLDB_REGNUM_GENERIC_RA)) {
2136     pc_register = true;
2137   }
2138 
2139   lldb_private::UnwindLLDB::RegisterLocation regloc;
2140   if (!m_parent_unwind.SearchForSavedLocationForRegister(
2141           lldb_regnum, regloc, m_frame_number - 1, pc_register)) {
2142     return false;
2143   }
2144   if (ReadRegisterValueFromRegisterLocation(regloc, reg_info, reg_value)) {
2145     value = reg_value.GetAsUInt64();
2146     if (pc_register) {
2147       if (ProcessSP process_sp = m_thread.GetProcess()) {
2148         if (ABISP abi = process_sp->GetABI())
2149           value = abi->FixCodeAddress(value);
2150       }
2151     }
2152     return true;
2153   }
2154   return false;
2155 }
2156 
2157 bool RegisterContextUnwind::ReadGPRValue(const RegisterNumber &regnum,
2158                                          addr_t &value) {
2159   return ReadGPRValue(regnum.GetRegisterKind(), regnum.GetRegisterNumber(),
2160                       value);
2161 }
2162 
2163 // Find the value of a register in THIS frame
2164 
2165 bool RegisterContextUnwind::ReadRegister(const RegisterInfo *reg_info,
2166                                          RegisterValue &value) {
2167   if (!IsValid())
2168     return false;
2169 
2170   const uint32_t lldb_regnum = reg_info->kinds[eRegisterKindLLDB];
2171   UnwindLogMsgVerbose("looking for register saved location for reg %d",
2172                       lldb_regnum);
2173 
2174   // If this is the 0th frame, hand this over to the live register context
2175   if (IsFrameZero()) {
2176     UnwindLogMsgVerbose("passing along to the live register context for reg %d",
2177                         lldb_regnum);
2178     return m_thread.GetRegisterContext()->ReadRegister(reg_info, value);
2179   }
2180 
2181   bool is_pc_regnum = false;
2182   if (reg_info->kinds[eRegisterKindGeneric] == LLDB_REGNUM_GENERIC_PC ||
2183       reg_info->kinds[eRegisterKindGeneric] == LLDB_REGNUM_GENERIC_RA) {
2184     is_pc_regnum = true;
2185   }
2186 
2187   lldb_private::UnwindLLDB::RegisterLocation regloc;
2188   // Find out where the NEXT frame saved THIS frame's register contents
2189   if (!m_parent_unwind.SearchForSavedLocationForRegister(
2190           lldb_regnum, regloc, m_frame_number - 1, is_pc_regnum))
2191     return false;
2192 
2193   bool result = ReadRegisterValueFromRegisterLocation(regloc, reg_info, value);
2194   if (result) {
2195     if (is_pc_regnum && value.GetType() == RegisterValue::eTypeUInt64) {
2196       addr_t reg_value = value.GetAsUInt64(LLDB_INVALID_ADDRESS);
2197       if (reg_value != LLDB_INVALID_ADDRESS) {
2198         if(ProcessSP process_sp = m_thread.GetProcess()) {
2199           if (ABISP abi = process_sp->GetABI())
2200             value = abi->FixCodeAddress(reg_value);
2201         }
2202       }
2203     }
2204   }
2205   return result;
2206 }
2207 
2208 bool RegisterContextUnwind::WriteRegister(const RegisterInfo *reg_info,
2209                                           const RegisterValue &value) {
2210   if (!IsValid())
2211     return false;
2212 
2213   const uint32_t lldb_regnum = reg_info->kinds[eRegisterKindLLDB];
2214   UnwindLogMsgVerbose("looking for register saved location for reg %d",
2215                       lldb_regnum);
2216 
2217   // If this is the 0th frame, hand this over to the live register context
2218   if (IsFrameZero()) {
2219     UnwindLogMsgVerbose("passing along to the live register context for reg %d",
2220                         lldb_regnum);
2221     return m_thread.GetRegisterContext()->WriteRegister(reg_info, value);
2222   }
2223 
2224   lldb_private::UnwindLLDB::RegisterLocation regloc;
2225   // Find out where the NEXT frame saved THIS frame's register contents
2226   if (!m_parent_unwind.SearchForSavedLocationForRegister(
2227           lldb_regnum, regloc, m_frame_number - 1, false))
2228     return false;
2229 
2230   return WriteRegisterValueToRegisterLocation(regloc, reg_info, value);
2231 }
2232 
2233 // Don't need to implement this one
2234 bool RegisterContextUnwind::ReadAllRegisterValues(
2235     lldb::WritableDataBufferSP &data_sp) {
2236   return false;
2237 }
2238 
2239 // Don't need to implement this one
2240 bool RegisterContextUnwind::WriteAllRegisterValues(
2241     const lldb::DataBufferSP &data_sp) {
2242   return false;
2243 }
2244 
2245 // Retrieve the pc value for THIS from
2246 
2247 bool RegisterContextUnwind::GetCFA(addr_t &cfa) {
2248   if (!IsValid()) {
2249     return false;
2250   }
2251   if (m_cfa == LLDB_INVALID_ADDRESS) {
2252     return false;
2253   }
2254   cfa = m_cfa;
2255   return true;
2256 }
2257 
2258 RegisterContextUnwind::SharedPtr RegisterContextUnwind::GetNextFrame() const {
2259   RegisterContextUnwind::SharedPtr regctx;
2260   if (m_frame_number == 0)
2261     return regctx;
2262   return m_parent_unwind.GetRegisterContextForFrameNum(m_frame_number - 1);
2263 }
2264 
2265 RegisterContextUnwind::SharedPtr RegisterContextUnwind::GetPrevFrame() const {
2266   RegisterContextUnwind::SharedPtr regctx;
2267   return m_parent_unwind.GetRegisterContextForFrameNum(m_frame_number + 1);
2268 }
2269 
2270 // Retrieve the address of the start of the function of THIS frame
2271 
2272 bool RegisterContextUnwind::GetStartPC(addr_t &start_pc) {
2273   if (!IsValid())
2274     return false;
2275 
2276   if (!m_start_pc.IsValid()) {
2277         bool read_successfully = ReadPC (start_pc);
2278         if (read_successfully)
2279         {
2280             ProcessSP process_sp (m_thread.GetProcess());
2281             if (process_sp)
2282             {
2283                 ABI *abi = process_sp->GetABI().get();
2284                 if (abi)
2285                     start_pc = abi->FixCodeAddress(start_pc);
2286             }
2287         }
2288         return read_successfully;
2289   }
2290   start_pc = m_start_pc.GetLoadAddress(CalculateTarget().get());
2291   return true;
2292 }
2293 
2294 // Retrieve the current pc value for THIS frame, as saved by the NEXT frame.
2295 
2296 bool RegisterContextUnwind::ReadPC(addr_t &pc) {
2297   if (!IsValid())
2298     return false;
2299 
2300   bool above_trap_handler = false;
2301   if (GetNextFrame().get() && GetNextFrame()->IsValid() &&
2302       GetNextFrame()->IsTrapHandlerFrame())
2303     above_trap_handler = true;
2304 
2305   if (ReadGPRValue(eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC, pc)) {
2306     // A pc value of 0 or 1 is impossible in the middle of the stack -- it
2307     // indicates the end of a stack walk.
2308     // On the currently executing frame (or such a frame interrupted
2309     // asynchronously by sigtramp et al) this may occur if code has jumped
2310     // through a NULL pointer -- we want to be able to unwind past that frame
2311     // to help find the bug.
2312 
2313     ProcessSP process_sp (m_thread.GetProcess());
2314     if (process_sp)
2315     {
2316         ABI *abi = process_sp->GetABI().get();
2317         if (abi)
2318             pc = abi->FixCodeAddress(pc);
2319     }
2320 
2321     return !(m_all_registers_available == false &&
2322              above_trap_handler == false && (pc == 0 || pc == 1));
2323   } else {
2324     return false;
2325   }
2326 }
2327 
2328 void RegisterContextUnwind::UnwindLogMsg(const char *fmt, ...) {
2329   Log *log = GetLog(LLDBLog::Unwind);
2330   if (!log)
2331     return;
2332 
2333   va_list args;
2334   va_start(args, fmt);
2335 
2336   llvm::SmallString<0> logmsg;
2337   if (VASprintf(logmsg, fmt, args)) {
2338     LLDB_LOGF(log, "%*sth%d/fr%u %s",
2339               m_frame_number < 100 ? m_frame_number : 100, "",
2340               m_thread.GetIndexID(), m_frame_number, logmsg.c_str());
2341   }
2342   va_end(args);
2343 }
2344 
2345 void RegisterContextUnwind::UnwindLogMsgVerbose(const char *fmt, ...) {
2346   Log *log = GetLog(LLDBLog::Unwind);
2347   if (!log || !log->GetVerbose())
2348     return;
2349 
2350   va_list args;
2351   va_start(args, fmt);
2352 
2353   llvm::SmallString<0> logmsg;
2354   if (VASprintf(logmsg, fmt, args)) {
2355     LLDB_LOGF(log, "%*sth%d/fr%u %s",
2356               m_frame_number < 100 ? m_frame_number : 100, "",
2357               m_thread.GetIndexID(), m_frame_number, logmsg.c_str());
2358   }
2359   va_end(args);
2360 }
2361