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