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