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