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