1 //===-- RegisterContextLLDB.cpp --------------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "lldb/Core/Address.h"
11 #include "lldb/Core/AddressRange.h"
12 #include "lldb/Core/Module.h"
13 #include "lldb/Core/RegisterValue.h"
14 #include "lldb/Core/Value.h"
15 #include "lldb/Expression/DWARFExpression.h"
16 #include "lldb/Symbol/ArmUnwindInfo.h"
17 #include "lldb/Symbol/DWARFCallFrameInfo.h"
18 #include "lldb/Symbol/FuncUnwinders.h"
19 #include "lldb/Symbol/Function.h"
20 #include "lldb/Symbol/ObjectFile.h"
21 #include "lldb/Symbol/Symbol.h"
22 #include "lldb/Symbol/SymbolContext.h"
23 #include "lldb/Target/ABI.h"
24 #include "lldb/Target/DynamicLoader.h"
25 #include "lldb/Target/ExecutionContext.h"
26 #include "lldb/Target/Platform.h"
27 #include "lldb/Target/Process.h"
28 #include "lldb/Target/SectionLoadList.h"
29 #include "lldb/Target/StackFrame.h"
30 #include "lldb/Target/Target.h"
31 #include "lldb/Target/Thread.h"
32 #include "lldb/Utility/DataBufferHeap.h"
33 #include "lldb/Utility/Log.h"
34 #include "lldb/lldb-private.h"
36 #include "RegisterContextLLDB.h"
39 using namespace lldb_private;
41 static ConstString GetSymbolOrFunctionName(const SymbolContext &sym_ctx) {
43 return sym_ctx.symbol->GetName();
44 else if (sym_ctx.function)
45 return sym_ctx.function->GetName();
49 RegisterContextLLDB::RegisterContextLLDB(Thread &thread,
50 const SharedPtr &next_frame,
51 SymbolContext &sym_ctx,
52 uint32_t frame_number,
53 UnwindLLDB &unwind_lldb)
54 : RegisterContext(thread, frame_number), m_thread(thread),
55 m_fast_unwind_plan_sp(), m_full_unwind_plan_sp(),
56 m_fallback_unwind_plan_sp(), m_all_registers_available(false),
57 m_frame_type(-1), m_cfa(LLDB_INVALID_ADDRESS), m_start_pc(),
58 m_current_pc(), m_current_offset(0), m_current_offset_backed_up_one(0),
59 m_sym_ctx(sym_ctx), m_sym_ctx_valid(false), m_frame_number(frame_number),
60 m_registers(), m_parent_unwind(unwind_lldb) {
61 m_sym_ctx.Clear(false);
62 m_sym_ctx_valid = false;
65 InitializeZerothFrame();
67 InitializeNonZerothFrame();
70 // This same code exists over in the GetFullUnwindPlanForFrame() but it may
71 // not have been executed yet
72 if (IsFrameZero() || next_frame->m_frame_type == eTrapHandlerFrame ||
73 next_frame->m_frame_type == eDebuggerFrame) {
74 m_all_registers_available = true;
78 bool RegisterContextLLDB::IsUnwindPlanValidForCurrentPC(
79 lldb::UnwindPlanSP unwind_plan_sp, int &valid_pc_offset) {
83 // check if m_current_pc is valid
84 if (unwind_plan_sp->PlanValidAtAddress(m_current_pc)) {
85 // yes - current offset can be used as is
86 valid_pc_offset = m_current_offset;
90 // if m_current_offset <= 0, we've got nothing else to try
91 if (m_current_offset <= 0)
94 // check pc - 1 to see if it's valid
95 Address pc_minus_one(m_current_pc);
96 pc_minus_one.SetOffset(m_current_pc.GetOffset() - 1);
97 if (unwind_plan_sp->PlanValidAtAddress(pc_minus_one)) {
98 // *valid_pc_offset = m_current_offset - 1;
99 valid_pc_offset = m_current_pc.GetOffset() - 1;
106 // Initialize a RegisterContextLLDB which is the first frame of a stack -- the
107 // zeroth frame or currently executing frame.
109 void RegisterContextLLDB::InitializeZerothFrame() {
110 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_UNWIND));
111 ExecutionContext exe_ctx(m_thread.shared_from_this());
112 RegisterContextSP reg_ctx_sp = m_thread.GetRegisterContext();
114 if (reg_ctx_sp.get() == NULL) {
115 m_frame_type = eNotAValidFrame;
116 UnwindLogMsg("frame does not have a register context");
120 addr_t current_pc = reg_ctx_sp->GetPC();
122 if (current_pc == LLDB_INVALID_ADDRESS) {
123 m_frame_type = eNotAValidFrame;
124 UnwindLogMsg("frame does not have a pc");
128 Process *process = exe_ctx.GetProcessPtr();
130 // Let ABIs fixup code addresses to make sure they are valid. In ARM ABIs
131 // this will strip bit zero in case we read a PC from memory or from the LR.
132 // (which would be a no-op in frame 0 where we get it from the register set,
133 // but still a good idea to make the call here for other ABIs that may
135 ABI *abi = process->GetABI().get();
137 current_pc = abi->FixCodeAddress(current_pc);
139 // Initialize m_current_pc, an Address object, based on current_pc, an
141 m_current_pc.SetLoadAddress(current_pc, &process->GetTarget());
143 // If we don't have a Module for some reason, we're not going to find
144 // symbol/function information - just stick in some reasonable defaults and
145 // hope we can unwind past this frame.
146 ModuleSP pc_module_sp(m_current_pc.GetModule());
147 if (!m_current_pc.IsValid() || !pc_module_sp) {
148 UnwindLogMsg("using architectural default unwind method");
151 // We require either a symbol or function in the symbols context to be
152 // successfully filled in or this context is of no use to us.
153 const uint32_t resolve_scope = eSymbolContextFunction | eSymbolContextSymbol;
154 if (pc_module_sp.get() && (pc_module_sp->ResolveSymbolContextForAddress(
155 m_current_pc, resolve_scope, m_sym_ctx) &
157 m_sym_ctx_valid = true;
160 if (m_sym_ctx.symbol) {
161 UnwindLogMsg("with pc value of 0x%" PRIx64 ", symbol name is '%s'",
162 current_pc, GetSymbolOrFunctionName(m_sym_ctx).AsCString(""));
163 } else if (m_sym_ctx.function) {
164 UnwindLogMsg("with pc value of 0x%" PRIx64 ", function name is '%s'",
165 current_pc, GetSymbolOrFunctionName(m_sym_ctx).AsCString(""));
167 UnwindLogMsg("with pc value of 0x%" PRIx64
168 ", no symbol/function name is known.",
172 AddressRange addr_range;
173 m_sym_ctx.GetAddressRange(resolve_scope, 0, false, addr_range);
175 if (IsTrapHandlerSymbol(process, m_sym_ctx)) {
176 m_frame_type = eTrapHandlerFrame;
178 // FIXME: Detect eDebuggerFrame here.
179 m_frame_type = eNormalFrame;
182 // If we were able to find a symbol/function, set addr_range to the bounds of
183 // that symbol/function. else treat the current pc value as the start_pc and
185 if (addr_range.GetBaseAddress().IsValid()) {
186 m_start_pc = addr_range.GetBaseAddress();
187 if (m_current_pc.GetSection() == m_start_pc.GetSection()) {
188 m_current_offset = m_current_pc.GetOffset() - m_start_pc.GetOffset();
189 } else if (m_current_pc.GetModule() == m_start_pc.GetModule()) {
190 // This means that whatever symbol we kicked up isn't really correct ---
191 // we should not cross section boundaries ... We really should NULL out
192 // the function/symbol in this case unless there is a bad assumption here
193 // due to inlined functions?
195 m_current_pc.GetFileAddress() - m_start_pc.GetFileAddress();
197 m_current_offset_backed_up_one = m_current_offset;
199 m_start_pc = m_current_pc;
200 m_current_offset = -1;
201 m_current_offset_backed_up_one = -1;
204 // We've set m_frame_type and m_sym_ctx before these calls.
206 m_fast_unwind_plan_sp = GetFastUnwindPlanForFrame();
207 m_full_unwind_plan_sp = GetFullUnwindPlanForFrame();
209 UnwindPlan::RowSP active_row;
210 lldb::RegisterKind row_register_kind = eRegisterKindGeneric;
211 if (m_full_unwind_plan_sp &&
212 m_full_unwind_plan_sp->PlanValidAtAddress(m_current_pc)) {
214 m_full_unwind_plan_sp->GetRowForFunctionOffset(m_current_offset);
215 row_register_kind = m_full_unwind_plan_sp->GetRegisterKind();
216 if (active_row.get() && log) {
217 StreamString active_row_strm;
218 active_row->Dump(active_row_strm, m_full_unwind_plan_sp.get(), &m_thread,
219 m_start_pc.GetLoadAddress(exe_ctx.GetTargetPtr()));
220 UnwindLogMsg("%s", active_row_strm.GetData());
224 if (!active_row.get()) {
225 UnwindLogMsg("could not find an unwindplan row for this frame's pc");
226 m_frame_type = eNotAValidFrame;
230 if (!ReadCFAValueForRow(row_register_kind, active_row, m_cfa)) {
231 // Try the fall back unwind plan since the
232 // full unwind plan failed.
233 FuncUnwindersSP func_unwinders_sp;
234 UnwindPlanSP call_site_unwind_plan;
235 bool cfa_status = false;
237 if (m_sym_ctx_valid) {
239 pc_module_sp->GetObjectFile()
241 .GetFuncUnwindersContainingAddress(m_current_pc, m_sym_ctx);
244 if (func_unwinders_sp.get() != nullptr)
245 call_site_unwind_plan = func_unwinders_sp->GetUnwindPlanAtCallSite(
246 process->GetTarget(), m_current_offset_backed_up_one);
248 if (call_site_unwind_plan.get() != nullptr) {
249 m_fallback_unwind_plan_sp = call_site_unwind_plan;
250 if (TryFallbackUnwindPlan())
254 UnwindLogMsg("could not read CFA value for first frame.");
255 m_frame_type = eNotAValidFrame;
260 UnwindLogMsg("initialized frame current pc is 0x%" PRIx64 " cfa is 0x%" PRIx64
261 " using %s UnwindPlan",
262 (uint64_t)m_current_pc.GetLoadAddress(exe_ctx.GetTargetPtr()),
264 m_full_unwind_plan_sp->GetSourceName().GetCString());
267 // Initialize a RegisterContextLLDB for the non-zeroth frame -- rely on the
268 // RegisterContextLLDB "below" it to provide things like its current pc value.
270 void RegisterContextLLDB::InitializeNonZerothFrame() {
271 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_UNWIND));
273 m_frame_type = eNotAValidFrame;
274 UnwindLogMsg("non-zeroth frame tests positive for IsFrameZero -- that "
275 "shouldn't happen.");
279 if (!GetNextFrame().get() || !GetNextFrame()->IsValid()) {
280 m_frame_type = eNotAValidFrame;
281 UnwindLogMsg("Could not get next frame, marking this frame as invalid.");
284 if (!m_thread.GetRegisterContext()) {
285 m_frame_type = eNotAValidFrame;
286 UnwindLogMsg("Could not get register context for this thread, marking this "
287 "frame as invalid.");
292 if (!ReadGPRValue(eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC, pc)) {
293 UnwindLogMsg("could not get pc value");
294 m_frame_type = eNotAValidFrame;
298 ExecutionContext exe_ctx(m_thread.shared_from_this());
299 Process *process = exe_ctx.GetProcessPtr();
300 // Let ABIs fixup code addresses to make sure they are valid. In ARM ABIs
301 // this will strip bit zero in case we read a PC from memory or from the LR.
302 ABI *abi = process->GetABI().get();
304 pc = abi->FixCodeAddress(pc);
307 UnwindLogMsg("pc = 0x%" PRIx64, pc);
309 if (ReadGPRValue(eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FP, reg_val))
310 UnwindLogMsg("fp = 0x%" PRIx64, reg_val);
311 if (ReadGPRValue(eRegisterKindGeneric, LLDB_REGNUM_GENERIC_SP, reg_val))
312 UnwindLogMsg("sp = 0x%" PRIx64, reg_val);
315 // A pc of 0x0 means it's the end of the stack crawl unless we're above a trap
317 bool above_trap_handler = false;
318 if (GetNextFrame().get() && GetNextFrame()->IsValid() &&
319 GetNextFrame()->IsTrapHandlerFrame())
320 above_trap_handler = true;
322 if (pc == 0 || pc == 0x1) {
323 if (above_trap_handler == false) {
324 m_frame_type = eNotAValidFrame;
325 UnwindLogMsg("this frame has a pc of 0x0");
330 const bool allow_section_end = true;
331 m_current_pc.SetLoadAddress(pc, &process->GetTarget(), allow_section_end);
333 // If we don't have a Module for some reason, we're not going to find
334 // symbol/function information - just stick in some reasonable defaults and
335 // hope we can unwind past this frame.
336 ModuleSP pc_module_sp(m_current_pc.GetModule());
337 if (!m_current_pc.IsValid() || !pc_module_sp) {
338 UnwindLogMsg("using architectural default unwind method");
340 // Test the pc value to see if we know it's in an unmapped/non-executable
342 uint32_t permissions;
343 if (process->GetLoadAddressPermissions(pc, permissions) &&
344 (permissions & ePermissionsExecutable) == 0) {
345 // If this is the second frame off the stack, we may have unwound the
346 // first frame incorrectly. But using the architecture default unwind
347 // plan may get us back on track -- albeit possibly skipping a real
348 // frame. Give this frame a clearly-invalid pc and see if we can get any
350 if (GetNextFrame().get() && GetNextFrame()->IsValid() &&
351 GetNextFrame()->IsFrameZero()) {
352 UnwindLogMsg("had a pc of 0x%" PRIx64 " which is not in executable "
353 "memory but on frame 1 -- "
356 m_frame_type = eSkipFrame;
358 // anywhere other than the second frame, a non-executable pc means
359 // we're off in the weeds -- stop now.
360 m_frame_type = eNotAValidFrame;
361 UnwindLogMsg("pc is in a non-executable section of memory and this "
362 "isn't the 2nd frame in the stack walk.");
368 m_fast_unwind_plan_sp.reset();
369 m_full_unwind_plan_sp.reset(new UnwindPlan(lldb::eRegisterKindGeneric));
370 abi->CreateDefaultUnwindPlan(*m_full_unwind_plan_sp);
371 if (m_frame_type != eSkipFrame) // don't override eSkipFrame
373 m_frame_type = eNormalFrame;
375 m_all_registers_available = false;
376 m_current_offset = -1;
377 m_current_offset_backed_up_one = -1;
378 RegisterKind row_register_kind = m_full_unwind_plan_sp->GetRegisterKind();
379 UnwindPlan::RowSP row = m_full_unwind_plan_sp->GetRowForFunctionOffset(0);
381 if (!ReadCFAValueForRow(row_register_kind, row, m_cfa)) {
382 UnwindLogMsg("failed to get cfa value");
383 if (m_frame_type != eSkipFrame) // don't override eSkipFrame
385 m_frame_type = eNotAValidFrame;
390 // A couple of sanity checks..
391 if (m_cfa == LLDB_INVALID_ADDRESS || m_cfa == 0 || m_cfa == 1) {
392 UnwindLogMsg("could not find a valid cfa address");
393 m_frame_type = eNotAValidFrame;
397 // m_cfa should point into the stack memory; if we can query memory
398 // region permissions, see if the memory is allocated & readable.
399 if (process->GetLoadAddressPermissions(m_cfa, permissions) &&
400 (permissions & ePermissionsReadable) == 0) {
401 m_frame_type = eNotAValidFrame;
403 "the CFA points to a region of memory that is not readable");
407 UnwindLogMsg("could not find a row for function offset zero");
408 m_frame_type = eNotAValidFrame;
412 if (CheckIfLoopingStack()) {
413 TryFallbackUnwindPlan();
414 if (CheckIfLoopingStack()) {
415 UnwindLogMsg("same CFA address as next frame, assuming the unwind is "
416 "looping - stopping");
417 m_frame_type = eNotAValidFrame;
422 UnwindLogMsg("initialized frame cfa is 0x%" PRIx64, (uint64_t)m_cfa);
425 m_frame_type = eNotAValidFrame;
426 UnwindLogMsg("could not find any symbol for this pc, or a default unwind "
427 "plan, to continue unwind.");
431 bool resolve_tail_call_address = false; // m_current_pc can be one past the
432 // address range of the function...
433 // If the saved pc does not point to a function/symbol because it is beyond
434 // the bounds of the correct function and there's no symbol there, we do
435 // *not* want ResolveSymbolContextForAddress to back up the pc by 1, because
436 // then we might not find the correct unwind information later. Instead, let
437 // ResolveSymbolContextForAddress fail, and handle the case via
438 // decr_pc_and_recompute_addr_range below.
439 const uint32_t resolve_scope = eSymbolContextFunction | eSymbolContextSymbol;
440 uint32_t resolved_scope = pc_module_sp->ResolveSymbolContextForAddress(
441 m_current_pc, resolve_scope, m_sym_ctx, resolve_tail_call_address);
443 // We require either a symbol or function in the symbols context to be
444 // successfully filled in or this context is of no use to us.
445 if (resolve_scope & resolved_scope) {
446 m_sym_ctx_valid = true;
449 if (m_sym_ctx.symbol) {
450 UnwindLogMsg("with pc value of 0x%" PRIx64 ", symbol name is '%s'", pc,
451 GetSymbolOrFunctionName(m_sym_ctx).AsCString(""));
452 } else if (m_sym_ctx.function) {
453 UnwindLogMsg("with pc value of 0x%" PRIx64 ", function name is '%s'", pc,
454 GetSymbolOrFunctionName(m_sym_ctx).AsCString(""));
456 UnwindLogMsg("with pc value of 0x%" PRIx64
457 ", no symbol/function name is known.",
461 AddressRange addr_range;
462 if (!m_sym_ctx.GetAddressRange(resolve_scope, 0, false, addr_range)) {
463 m_sym_ctx_valid = false;
466 bool decr_pc_and_recompute_addr_range = false;
468 // If the symbol lookup failed...
469 if (m_sym_ctx_valid == false)
470 decr_pc_and_recompute_addr_range = true;
472 // Or if we're in the middle of the stack (and not "above" an asynchronous
473 // event like sigtramp), and our "current" pc is the start of a function...
474 if (GetNextFrame()->m_frame_type != eTrapHandlerFrame &&
475 GetNextFrame()->m_frame_type != eDebuggerFrame &&
477 (addr_range.GetBaseAddress().IsValid() &&
478 addr_range.GetBaseAddress().GetSection() == m_current_pc.GetSection() &&
479 addr_range.GetBaseAddress().GetOffset() == m_current_pc.GetOffset()))) {
480 decr_pc_and_recompute_addr_range = true;
483 // We need to back up the pc by 1 byte and re-search for the Symbol to handle
484 // the case where the "saved pc" value is pointing to the next function, e.g.
485 // if a function ends with a CALL instruction.
486 // FIXME this may need to be an architectural-dependent behavior; if so we'll
487 // need to add a member function
488 // to the ABI plugin and consult that.
489 if (decr_pc_and_recompute_addr_range) {
490 UnwindLogMsg("Backing up the pc value of 0x%" PRIx64
491 " by 1 and re-doing symbol lookup; old symbol was %s",
492 pc, GetSymbolOrFunctionName(m_sym_ctx).AsCString(""));
493 Address temporary_pc;
494 temporary_pc.SetLoadAddress(pc - 1, &process->GetTarget());
495 m_sym_ctx.Clear(false);
496 m_sym_ctx_valid = false;
497 uint32_t resolve_scope = eSymbolContextFunction | eSymbolContextSymbol;
499 ModuleSP temporary_module_sp = temporary_pc.GetModule();
500 if (temporary_module_sp &&
501 temporary_module_sp->ResolveSymbolContextForAddress(
502 temporary_pc, resolve_scope, m_sym_ctx) &
504 if (m_sym_ctx.GetAddressRange(resolve_scope, 0, false, addr_range))
505 m_sym_ctx_valid = true;
507 UnwindLogMsg("Symbol is now %s",
508 GetSymbolOrFunctionName(m_sym_ctx).AsCString(""));
511 // If we were able to find a symbol/function, set addr_range_ptr to the
512 // bounds of that symbol/function. else treat the current pc value as the
513 // start_pc and record no offset.
514 if (addr_range.GetBaseAddress().IsValid()) {
515 m_start_pc = addr_range.GetBaseAddress();
516 m_current_offset = pc - m_start_pc.GetLoadAddress(&process->GetTarget());
517 m_current_offset_backed_up_one = m_current_offset;
518 if (decr_pc_and_recompute_addr_range &&
519 m_current_offset_backed_up_one > 0) {
520 m_current_offset_backed_up_one--;
521 if (m_sym_ctx_valid) {
522 m_current_pc.SetLoadAddress(pc - 1, &process->GetTarget());
526 m_start_pc = m_current_pc;
527 m_current_offset = -1;
528 m_current_offset_backed_up_one = -1;
531 if (IsTrapHandlerSymbol(process, m_sym_ctx)) {
532 m_frame_type = eTrapHandlerFrame;
534 // FIXME: Detect eDebuggerFrame here.
535 if (m_frame_type != eSkipFrame) // don't override eSkipFrame
537 m_frame_type = eNormalFrame;
541 // We've set m_frame_type and m_sym_ctx before this call.
542 m_fast_unwind_plan_sp = GetFastUnwindPlanForFrame();
544 UnwindPlan::RowSP active_row;
545 RegisterKind row_register_kind = eRegisterKindGeneric;
547 // Try to get by with just the fast UnwindPlan if possible - the full
548 // UnwindPlan may be expensive to get (e.g. if we have to parse the entire
549 // eh_frame section of an ObjectFile for the first time.)
551 if (m_fast_unwind_plan_sp &&
552 m_fast_unwind_plan_sp->PlanValidAtAddress(m_current_pc)) {
554 m_fast_unwind_plan_sp->GetRowForFunctionOffset(m_current_offset);
555 row_register_kind = m_fast_unwind_plan_sp->GetRegisterKind();
556 if (active_row.get() && log) {
557 StreamString active_row_strm;
558 active_row->Dump(active_row_strm, m_fast_unwind_plan_sp.get(), &m_thread,
559 m_start_pc.GetLoadAddress(exe_ctx.GetTargetPtr()));
560 UnwindLogMsg("active row: %s", active_row_strm.GetData());
563 m_full_unwind_plan_sp = GetFullUnwindPlanForFrame();
564 int valid_offset = -1;
565 if (IsUnwindPlanValidForCurrentPC(m_full_unwind_plan_sp, valid_offset)) {
566 active_row = m_full_unwind_plan_sp->GetRowForFunctionOffset(valid_offset);
567 row_register_kind = m_full_unwind_plan_sp->GetRegisterKind();
568 if (active_row.get() && log) {
569 StreamString active_row_strm;
570 active_row->Dump(active_row_strm, m_full_unwind_plan_sp.get(),
572 m_start_pc.GetLoadAddress(exe_ctx.GetTargetPtr()));
573 UnwindLogMsg("active row: %s", active_row_strm.GetData());
578 if (!active_row.get()) {
579 m_frame_type = eNotAValidFrame;
580 UnwindLogMsg("could not find unwind row for this pc");
584 if (!ReadCFAValueForRow(row_register_kind, active_row, m_cfa)) {
585 UnwindLogMsg("failed to get cfa");
586 m_frame_type = eNotAValidFrame;
590 UnwindLogMsg("m_cfa = 0x%" PRIx64, m_cfa);
592 if (CheckIfLoopingStack()) {
593 TryFallbackUnwindPlan();
594 if (CheckIfLoopingStack()) {
595 UnwindLogMsg("same CFA address as next frame, assuming the unwind is "
596 "looping - stopping");
597 m_frame_type = eNotAValidFrame;
602 UnwindLogMsg("initialized frame current pc is 0x%" PRIx64
603 " cfa is 0x%" PRIx64,
604 (uint64_t)m_current_pc.GetLoadAddress(exe_ctx.GetTargetPtr()),
608 bool RegisterContextLLDB::CheckIfLoopingStack() {
609 // If we have a bad stack setup, we can get the same CFA value multiple times
610 // -- or even more devious, we can actually oscillate between two CFA values.
611 // Detect that here and break out to avoid a possible infinite loop in lldb
612 // trying to unwind the stack. To detect when we have the same CFA value
613 // multiple times, we compare the
614 // CFA of the current
615 // frame with the 2nd next frame because in some specail case (e.g. signal
616 // hanlders, hand written assembly without ABI compiance) we can have 2
617 // frames with the same
619 // can have arbitrary number of frames with the same CFA, but more then 2 is
620 // very very unlikely)
622 RegisterContextLLDB::SharedPtr next_frame = GetNextFrame();
624 RegisterContextLLDB::SharedPtr next_next_frame = next_frame->GetNextFrame();
625 addr_t next_next_frame_cfa = LLDB_INVALID_ADDRESS;
626 if (next_next_frame && next_next_frame->GetCFA(next_next_frame_cfa)) {
627 if (next_next_frame_cfa == m_cfa) {
628 // We have a loop in the stack unwind
636 bool RegisterContextLLDB::IsFrameZero() const { return m_frame_number == 0; }
638 // Find a fast unwind plan for this frame, if possible.
640 // On entry to this method,
642 // 1. m_frame_type should already be set to eTrapHandlerFrame/eDebuggerFrame
643 // if either of those are correct,
644 // 2. m_sym_ctx should already be filled in, and
645 // 3. m_current_pc should have the current pc value for this frame
646 // 4. m_current_offset_backed_up_one should have the current byte offset into
647 // the function, maybe backed up by 1, -1 if unknown
649 UnwindPlanSP RegisterContextLLDB::GetFastUnwindPlanForFrame() {
650 UnwindPlanSP unwind_plan_sp;
651 ModuleSP pc_module_sp(m_current_pc.GetModule());
653 if (!m_current_pc.IsValid() || !pc_module_sp ||
654 pc_module_sp->GetObjectFile() == NULL)
655 return unwind_plan_sp;
658 return unwind_plan_sp;
660 FuncUnwindersSP func_unwinders_sp(
661 pc_module_sp->GetObjectFile()
663 .GetFuncUnwindersContainingAddress(m_current_pc, m_sym_ctx));
664 if (!func_unwinders_sp)
665 return unwind_plan_sp;
667 // If we're in _sigtramp(), unwinding past this frame requires special
669 if (m_frame_type == eTrapHandlerFrame || m_frame_type == eDebuggerFrame)
670 return unwind_plan_sp;
672 unwind_plan_sp = func_unwinders_sp->GetUnwindPlanFastUnwind(
673 *m_thread.CalculateTarget(), m_thread);
674 if (unwind_plan_sp) {
675 if (unwind_plan_sp->PlanValidAtAddress(m_current_pc)) {
676 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_UNWIND));
677 if (log && log->GetVerbose()) {
678 if (m_fast_unwind_plan_sp)
679 UnwindLogMsgVerbose("frame, and has a fast UnwindPlan");
681 UnwindLogMsgVerbose("frame");
683 m_frame_type = eNormalFrame;
684 return unwind_plan_sp;
686 unwind_plan_sp.reset();
689 return unwind_plan_sp;
692 // On entry to this method,
694 // 1. m_frame_type should already be set to eTrapHandlerFrame/eDebuggerFrame
695 // if either of those are correct,
696 // 2. m_sym_ctx should already be filled in, and
697 // 3. m_current_pc should have the current pc value for this frame
698 // 4. m_current_offset_backed_up_one should have the current byte offset into
699 // the function, maybe backed up by 1, -1 if unknown
701 UnwindPlanSP RegisterContextLLDB::GetFullUnwindPlanForFrame() {
702 UnwindPlanSP unwind_plan_sp;
703 UnwindPlanSP arch_default_unwind_plan_sp;
704 ExecutionContext exe_ctx(m_thread.shared_from_this());
705 Process *process = exe_ctx.GetProcessPtr();
706 ABI *abi = process ? process->GetABI().get() : NULL;
708 arch_default_unwind_plan_sp.reset(
709 new UnwindPlan(lldb::eRegisterKindGeneric));
710 abi->CreateDefaultUnwindPlan(*arch_default_unwind_plan_sp);
713 "unable to get architectural default UnwindPlan from ABI plugin");
716 bool behaves_like_zeroth_frame = false;
717 if (IsFrameZero() || GetNextFrame()->m_frame_type == eTrapHandlerFrame ||
718 GetNextFrame()->m_frame_type == eDebuggerFrame) {
719 behaves_like_zeroth_frame = true;
720 // If this frame behaves like a 0th frame (currently executing or
721 // interrupted asynchronously), all registers can be retrieved.
722 m_all_registers_available = true;
725 // If we've done a jmp 0x0 / bl 0x0 (called through a null function pointer)
726 // so the pc is 0x0 in the zeroth frame, we need to use the "unwind at first
727 // instruction" arch default UnwindPlan Also, if this Process can report on
728 // memory region attributes, any non-executable region means we jumped
729 // through a bad function pointer - handle the same way as 0x0. Note, if we
730 // have a symbol context & a symbol, we don't want to follow this code path.
731 // This is for jumping to memory regions without any information available.
733 if ((!m_sym_ctx_valid ||
734 (m_sym_ctx.function == NULL && m_sym_ctx.symbol == NULL)) &&
735 behaves_like_zeroth_frame && m_current_pc.IsValid()) {
736 uint32_t permissions;
737 addr_t current_pc_addr =
738 m_current_pc.GetLoadAddress(exe_ctx.GetTargetPtr());
739 if (current_pc_addr == 0 ||
741 process->GetLoadAddressPermissions(current_pc_addr, permissions) &&
742 (permissions & ePermissionsExecutable) == 0)) {
744 unwind_plan_sp.reset(new UnwindPlan(lldb::eRegisterKindGeneric));
745 abi->CreateFunctionEntryUnwindPlan(*unwind_plan_sp);
746 m_frame_type = eNormalFrame;
747 return unwind_plan_sp;
752 // No Module for the current pc, try using the architecture default unwind.
753 ModuleSP pc_module_sp(m_current_pc.GetModule());
754 if (!m_current_pc.IsValid() || !pc_module_sp ||
755 pc_module_sp->GetObjectFile() == NULL) {
756 m_frame_type = eNormalFrame;
757 return arch_default_unwind_plan_sp;
760 FuncUnwindersSP func_unwinders_sp;
761 if (m_sym_ctx_valid) {
763 pc_module_sp->GetObjectFile()
765 .GetFuncUnwindersContainingAddress(m_current_pc, m_sym_ctx);
768 // No FuncUnwinders available for this pc (stripped function symbols, lldb
769 // could not augment its function table with another source, like
770 // LC_FUNCTION_STARTS or eh_frame in ObjectFileMachO). See if eh_frame or the
771 // .ARM.exidx tables have unwind information for this address, else fall back
772 // to the architectural default unwind.
773 if (!func_unwinders_sp) {
774 m_frame_type = eNormalFrame;
776 if (!pc_module_sp || !pc_module_sp->GetObjectFile() ||
777 !m_current_pc.IsValid())
778 return arch_default_unwind_plan_sp;
780 // Even with -fomit-frame-pointer, we can try eh_frame to get back on
782 DWARFCallFrameInfo *eh_frame =
783 pc_module_sp->GetObjectFile()->GetUnwindTable().GetEHFrameInfo();
785 unwind_plan_sp.reset(new UnwindPlan(lldb::eRegisterKindGeneric));
786 if (eh_frame->GetUnwindPlan(m_current_pc, *unwind_plan_sp))
787 return unwind_plan_sp;
789 unwind_plan_sp.reset();
792 ArmUnwindInfo *arm_exidx =
793 pc_module_sp->GetObjectFile()->GetUnwindTable().GetArmUnwindInfo();
795 unwind_plan_sp.reset(new UnwindPlan(lldb::eRegisterKindGeneric));
796 if (arm_exidx->GetUnwindPlan(exe_ctx.GetTargetRef(), m_current_pc,
798 return unwind_plan_sp;
800 unwind_plan_sp.reset();
803 return arch_default_unwind_plan_sp;
806 // If we're in _sigtramp(), unwinding past this frame requires special
807 // knowledge. On Mac OS X this knowledge is properly encoded in the eh_frame
808 // section, so prefer that if available. On other platforms we may need to
809 // provide a platform-specific UnwindPlan which encodes the details of how to
810 // unwind out of sigtramp.
811 if (m_frame_type == eTrapHandlerFrame && process) {
812 m_fast_unwind_plan_sp.reset();
813 unwind_plan_sp = func_unwinders_sp->GetEHFrameUnwindPlan(
814 process->GetTarget(), m_current_offset_backed_up_one);
815 if (unwind_plan_sp && unwind_plan_sp->PlanValidAtAddress(m_current_pc) &&
816 unwind_plan_sp->GetSourcedFromCompiler() == eLazyBoolYes) {
817 return unwind_plan_sp;
821 // Ask the DynamicLoader if the eh_frame CFI should be trusted in this frame
822 // even when it's frame zero This comes up if we have hand-written functions
823 // in a Module and hand-written eh_frame. The assembly instruction
824 // inspection may fail and the eh_frame CFI were probably written with some
825 // care to do the right thing. It'd be nice if there was a way to ask the
826 // eh_frame directly if it is asynchronous (can be trusted at every
827 // instruction point) or synchronous (the normal case - only at call sites).
829 if (process && process->GetDynamicLoader() &&
830 process->GetDynamicLoader()->AlwaysRelyOnEHUnwindInfo(m_sym_ctx)) {
831 // We must specifically call the GetEHFrameUnwindPlan() method here --
832 // normally we would call GetUnwindPlanAtCallSite() -- because CallSite may
833 // return an unwind plan sourced from either eh_frame (that's what we
834 // intend) or compact unwind (this won't work)
835 unwind_plan_sp = func_unwinders_sp->GetEHFrameUnwindPlan(
836 process->GetTarget(), m_current_offset_backed_up_one);
837 if (unwind_plan_sp && unwind_plan_sp->PlanValidAtAddress(m_current_pc)) {
838 UnwindLogMsgVerbose("frame uses %s for full UnwindPlan because the "
839 "DynamicLoader suggested we prefer it",
840 unwind_plan_sp->GetSourceName().GetCString());
841 return unwind_plan_sp;
845 // Typically the NonCallSite UnwindPlan is the unwind created by inspecting
846 // the assembly language instructions
847 if (behaves_like_zeroth_frame && process) {
848 unwind_plan_sp = func_unwinders_sp->GetUnwindPlanAtNonCallSite(
849 process->GetTarget(), m_thread, m_current_offset_backed_up_one);
850 if (unwind_plan_sp && unwind_plan_sp->PlanValidAtAddress(m_current_pc)) {
851 if (unwind_plan_sp->GetSourcedFromCompiler() == eLazyBoolNo) {
852 // We probably have an UnwindPlan created by inspecting assembly
853 // instructions. The assembly profilers work really well with compiler-
854 // generated functions but hand- written assembly can be problematic.
855 // We set the eh_frame based unwind plan as our fallback unwind plan if
856 // instruction emulation doesn't work out even for non call sites if it
857 // is available and use the architecture default unwind plan if it is
858 // not available. The eh_frame unwind plan is more reliable even on non
859 // call sites then the architecture default plan and for hand written
860 // assembly code it is often written in a way that it valid at all
861 // location what helps in the most common cases when the instruction
863 UnwindPlanSP call_site_unwind_plan =
864 func_unwinders_sp->GetUnwindPlanAtCallSite(
865 process->GetTarget(), m_current_offset_backed_up_one);
866 if (call_site_unwind_plan &&
867 call_site_unwind_plan.get() != unwind_plan_sp.get() &&
868 call_site_unwind_plan->GetSourceName() !=
869 unwind_plan_sp->GetSourceName()) {
870 m_fallback_unwind_plan_sp = call_site_unwind_plan;
872 m_fallback_unwind_plan_sp = arch_default_unwind_plan_sp;
875 UnwindLogMsgVerbose("frame uses %s for full UnwindPlan",
876 unwind_plan_sp->GetSourceName().GetCString());
877 return unwind_plan_sp;
881 // Typically this is unwind info from an eh_frame section intended for
882 // exception handling; only valid at call sites
884 unwind_plan_sp = func_unwinders_sp->GetUnwindPlanAtCallSite(
885 process->GetTarget(), m_current_offset_backed_up_one);
887 int valid_offset = -1;
888 if (IsUnwindPlanValidForCurrentPC(unwind_plan_sp, valid_offset)) {
889 UnwindLogMsgVerbose("frame uses %s for full UnwindPlan",
890 unwind_plan_sp->GetSourceName().GetCString());
891 return unwind_plan_sp;
894 // We'd prefer to use an UnwindPlan intended for call sites when we're at a
895 // call site but if we've struck out on that, fall back to using the non-
896 // call-site assembly inspection UnwindPlan if possible.
898 unwind_plan_sp = func_unwinders_sp->GetUnwindPlanAtNonCallSite(
899 process->GetTarget(), m_thread, m_current_offset_backed_up_one);
901 if (unwind_plan_sp &&
902 unwind_plan_sp->GetSourcedFromCompiler() == eLazyBoolNo) {
903 // We probably have an UnwindPlan created by inspecting assembly
904 // instructions. The assembly profilers work really well with compiler-
905 // generated functions but hand- written assembly can be problematic. We
906 // set the eh_frame based unwind plan as our fallback unwind plan if
907 // instruction emulation doesn't work out even for non call sites if it is
908 // available and use the architecture default unwind plan if it is not
909 // available. The eh_frame unwind plan is more reliable even on non call
910 // sites then the architecture default plan and for hand written assembly
911 // code it is often written in a way that it valid at all location what
912 // helps in the most common cases when the instruction emulation fails.
913 UnwindPlanSP call_site_unwind_plan =
914 func_unwinders_sp->GetUnwindPlanAtCallSite(
915 process->GetTarget(), m_current_offset_backed_up_one);
916 if (call_site_unwind_plan &&
917 call_site_unwind_plan.get() != unwind_plan_sp.get() &&
918 call_site_unwind_plan->GetSourceName() !=
919 unwind_plan_sp->GetSourceName()) {
920 m_fallback_unwind_plan_sp = call_site_unwind_plan;
922 m_fallback_unwind_plan_sp = arch_default_unwind_plan_sp;
926 if (IsUnwindPlanValidForCurrentPC(unwind_plan_sp, valid_offset)) {
927 UnwindLogMsgVerbose("frame uses %s for full UnwindPlan",
928 unwind_plan_sp->GetSourceName().GetCString());
929 return unwind_plan_sp;
932 // If we're on the first instruction of a function, and we have an
933 // architectural default UnwindPlan for the initial instruction of a
934 // function, use that.
935 if (m_current_offset_backed_up_one == 0) {
937 func_unwinders_sp->GetUnwindPlanArchitectureDefaultAtFunctionEntry(
939 if (unwind_plan_sp) {
940 UnwindLogMsgVerbose("frame uses %s for full UnwindPlan",
941 unwind_plan_sp->GetSourceName().GetCString());
942 return unwind_plan_sp;
946 // If nothing else, use the architectural default UnwindPlan and hope that
948 if (arch_default_unwind_plan_sp)
950 "frame uses %s for full UnwindPlan",
951 arch_default_unwind_plan_sp->GetSourceName().GetCString());
954 "Unable to find any UnwindPlan for full unwind of this frame.");
956 return arch_default_unwind_plan_sp;
959 void RegisterContextLLDB::InvalidateAllRegisters() {
960 m_frame_type = eNotAValidFrame;
963 size_t RegisterContextLLDB::GetRegisterCount() {
964 return m_thread.GetRegisterContext()->GetRegisterCount();
967 const RegisterInfo *RegisterContextLLDB::GetRegisterInfoAtIndex(size_t reg) {
968 return m_thread.GetRegisterContext()->GetRegisterInfoAtIndex(reg);
971 size_t RegisterContextLLDB::GetRegisterSetCount() {
972 return m_thread.GetRegisterContext()->GetRegisterSetCount();
975 const RegisterSet *RegisterContextLLDB::GetRegisterSet(size_t reg_set) {
976 return m_thread.GetRegisterContext()->GetRegisterSet(reg_set);
979 uint32_t RegisterContextLLDB::ConvertRegisterKindToRegisterNumber(
980 lldb::RegisterKind kind, uint32_t num) {
981 return m_thread.GetRegisterContext()->ConvertRegisterKindToRegisterNumber(
985 bool RegisterContextLLDB::ReadRegisterValueFromRegisterLocation(
986 lldb_private::UnwindLLDB::RegisterLocation regloc,
987 const RegisterInfo *reg_info, RegisterValue &value) {
990 bool success = false;
992 switch (regloc.type) {
993 case UnwindLLDB::RegisterLocation::eRegisterInLiveRegisterContext: {
994 const RegisterInfo *other_reg_info =
995 GetRegisterInfoAtIndex(regloc.location.register_number);
1001 m_thread.GetRegisterContext()->ReadRegister(other_reg_info, value);
1003 case UnwindLLDB::RegisterLocation::eRegisterInRegister: {
1004 const RegisterInfo *other_reg_info =
1005 GetRegisterInfoAtIndex(regloc.location.register_number);
1007 if (!other_reg_info)
1010 if (IsFrameZero()) {
1012 m_thread.GetRegisterContext()->ReadRegister(other_reg_info, value);
1014 success = GetNextFrame()->ReadRegister(other_reg_info, value);
1017 case UnwindLLDB::RegisterLocation::eRegisterValueInferred:
1019 value.SetUInt(regloc.location.inferred_value, reg_info->byte_size);
1022 case UnwindLLDB::RegisterLocation::eRegisterNotSaved:
1024 case UnwindLLDB::RegisterLocation::eRegisterSavedAtHostMemoryLocation:
1025 llvm_unreachable("FIXME debugger inferior function call unwind");
1026 case UnwindLLDB::RegisterLocation::eRegisterSavedAtMemoryLocation: {
1027 Status error(ReadRegisterValueFromMemory(
1028 reg_info, regloc.location.target_memory_location, reg_info->byte_size,
1030 success = error.Success();
1033 llvm_unreachable("Unknown RegisterLocation type.");
1038 bool RegisterContextLLDB::WriteRegisterValueToRegisterLocation(
1039 lldb_private::UnwindLLDB::RegisterLocation regloc,
1040 const RegisterInfo *reg_info, const RegisterValue &value) {
1044 bool success = false;
1046 switch (regloc.type) {
1047 case UnwindLLDB::RegisterLocation::eRegisterInLiveRegisterContext: {
1048 const RegisterInfo *other_reg_info =
1049 GetRegisterInfoAtIndex(regloc.location.register_number);
1051 m_thread.GetRegisterContext()->WriteRegister(other_reg_info, value);
1053 case UnwindLLDB::RegisterLocation::eRegisterInRegister: {
1054 const RegisterInfo *other_reg_info =
1055 GetRegisterInfoAtIndex(regloc.location.register_number);
1056 if (IsFrameZero()) {
1058 m_thread.GetRegisterContext()->WriteRegister(other_reg_info, value);
1060 success = GetNextFrame()->WriteRegister(other_reg_info, value);
1063 case UnwindLLDB::RegisterLocation::eRegisterValueInferred:
1064 case UnwindLLDB::RegisterLocation::eRegisterNotSaved:
1066 case UnwindLLDB::RegisterLocation::eRegisterSavedAtHostMemoryLocation:
1067 llvm_unreachable("FIXME debugger inferior function call unwind");
1068 case UnwindLLDB::RegisterLocation::eRegisterSavedAtMemoryLocation: {
1069 Status error(WriteRegisterValueToMemory(
1070 reg_info, regloc.location.target_memory_location, reg_info->byte_size,
1072 success = error.Success();
1075 llvm_unreachable("Unknown RegisterLocation type.");
1080 bool RegisterContextLLDB::IsValid() const {
1081 return m_frame_type != eNotAValidFrame;
1084 // After the final stack frame in a stack walk we'll get one invalid
1085 // (eNotAValidFrame) stack frame -- one past the end of the stack walk. But
1086 // higher-level code will need to tell the differnece between "the unwind plan
1087 // below this frame failed" versus "we successfully completed the stack walk"
1088 // so this method helps to disambiguate that.
1090 bool RegisterContextLLDB::IsTrapHandlerFrame() const {
1091 return m_frame_type == eTrapHandlerFrame;
1094 // A skip frame is a bogus frame on the stack -- but one where we're likely to
1095 // find a real frame farther
1096 // up the stack if we keep looking. It's always the second frame in an unwind
1097 // (i.e. the first frame after frame zero) where unwinding can be the
1098 // trickiest. Ideally we'll mark up this frame in some way so the user knows
1099 // we're displaying bad data and we may have skipped one frame of their real
1100 // program in the process of getting back on track.
1102 bool RegisterContextLLDB::IsSkipFrame() const {
1103 return m_frame_type == eSkipFrame;
1106 bool RegisterContextLLDB::IsTrapHandlerSymbol(
1107 lldb_private::Process *process,
1108 const lldb_private::SymbolContext &m_sym_ctx) const {
1109 PlatformSP platform_sp(process->GetTarget().GetPlatform());
1111 const std::vector<ConstString> trap_handler_names(
1112 platform_sp->GetTrapHandlerSymbolNames());
1113 for (ConstString name : trap_handler_names) {
1114 if ((m_sym_ctx.function && m_sym_ctx.function->GetName() == name) ||
1115 (m_sym_ctx.symbol && m_sym_ctx.symbol->GetName() == name)) {
1120 const std::vector<ConstString> user_specified_trap_handler_names(
1121 m_parent_unwind.GetUserSpecifiedTrapHandlerFunctionNames());
1122 for (ConstString name : user_specified_trap_handler_names) {
1123 if ((m_sym_ctx.function && m_sym_ctx.function->GetName() == name) ||
1124 (m_sym_ctx.symbol && m_sym_ctx.symbol->GetName() == name)) {
1132 // Answer the question: Where did THIS frame save the CALLER frame ("previous"
1133 // frame)'s register value?
1135 enum UnwindLLDB::RegisterSearchResult
1136 RegisterContextLLDB::SavedLocationForRegister(
1137 uint32_t lldb_regnum, lldb_private::UnwindLLDB::RegisterLocation ®loc) {
1138 RegisterNumber regnum(m_thread, eRegisterKindLLDB, lldb_regnum);
1140 // Have we already found this register location?
1141 if (!m_registers.empty()) {
1143 lldb_private::UnwindLLDB::RegisterLocation>::const_iterator
1145 iterator = m_registers.find(regnum.GetAsKind(eRegisterKindLLDB));
1146 if (iterator != m_registers.end()) {
1147 regloc = iterator->second;
1148 UnwindLogMsg("supplying caller's saved %s (%d)'s location, cached",
1149 regnum.GetName(), regnum.GetAsKind(eRegisterKindLLDB));
1150 return UnwindLLDB::RegisterSearchResult::eRegisterFound;
1154 // Look through the available UnwindPlans for the register location.
1156 UnwindPlan::Row::RegisterLocation unwindplan_regloc;
1157 bool have_unwindplan_regloc = false;
1158 RegisterKind unwindplan_registerkind = kNumRegisterKinds;
1160 if (m_fast_unwind_plan_sp) {
1161 UnwindPlan::RowSP active_row =
1162 m_fast_unwind_plan_sp->GetRowForFunctionOffset(m_current_offset);
1163 unwindplan_registerkind = m_fast_unwind_plan_sp->GetRegisterKind();
1164 if (regnum.GetAsKind(unwindplan_registerkind) == LLDB_INVALID_REGNUM) {
1165 UnwindLogMsg("could not convert lldb regnum %s (%d) into %d RegisterKind "
1166 "reg numbering scheme",
1167 regnum.GetName(), regnum.GetAsKind(eRegisterKindLLDB),
1168 (int)unwindplan_registerkind);
1169 return UnwindLLDB::RegisterSearchResult::eRegisterNotFound;
1171 if (active_row->GetRegisterInfo(regnum.GetAsKind(unwindplan_registerkind),
1172 unwindplan_regloc)) {
1174 "supplying caller's saved %s (%d)'s location using FastUnwindPlan",
1175 regnum.GetName(), regnum.GetAsKind(eRegisterKindLLDB));
1176 have_unwindplan_regloc = true;
1180 if (!have_unwindplan_regloc) {
1181 // m_full_unwind_plan_sp being NULL means that we haven't tried to find a
1182 // full UnwindPlan yet
1183 if (!m_full_unwind_plan_sp)
1184 m_full_unwind_plan_sp = GetFullUnwindPlanForFrame();
1186 if (m_full_unwind_plan_sp) {
1187 RegisterNumber pc_regnum(m_thread, eRegisterKindGeneric,
1188 LLDB_REGNUM_GENERIC_PC);
1190 UnwindPlan::RowSP active_row =
1191 m_full_unwind_plan_sp->GetRowForFunctionOffset(m_current_offset);
1192 unwindplan_registerkind = m_full_unwind_plan_sp->GetRegisterKind();
1194 RegisterNumber return_address_reg;
1196 // If we're fetching the saved pc and this UnwindPlan defines a
1197 // ReturnAddress register (e.g. lr on arm), look for the return address
1198 // register number in the UnwindPlan's row.
1199 if (pc_regnum.IsValid() && pc_regnum == regnum &&
1200 m_full_unwind_plan_sp->GetReturnAddressRegister() !=
1201 LLDB_INVALID_REGNUM) {
1203 return_address_reg.init(
1204 m_thread, m_full_unwind_plan_sp->GetRegisterKind(),
1205 m_full_unwind_plan_sp->GetReturnAddressRegister());
1206 regnum = return_address_reg;
1207 UnwindLogMsg("requested caller's saved PC but this UnwindPlan uses a "
1208 "RA reg; getting %s (%d) instead",
1209 return_address_reg.GetName(),
1210 return_address_reg.GetAsKind(eRegisterKindLLDB));
1212 if (regnum.GetAsKind(unwindplan_registerkind) == LLDB_INVALID_REGNUM) {
1213 if (unwindplan_registerkind == eRegisterKindGeneric) {
1214 UnwindLogMsg("could not convert lldb regnum %s (%d) into "
1215 "eRegisterKindGeneric reg numbering scheme",
1216 regnum.GetName(), regnum.GetAsKind(eRegisterKindLLDB));
1218 UnwindLogMsg("could not convert lldb regnum %s (%d) into %d "
1219 "RegisterKind reg numbering scheme",
1220 regnum.GetName(), regnum.GetAsKind(eRegisterKindLLDB),
1221 (int)unwindplan_registerkind);
1223 return UnwindLLDB::RegisterSearchResult::eRegisterNotFound;
1227 if (regnum.IsValid() &&
1228 active_row->GetRegisterInfo(regnum.GetAsKind(unwindplan_registerkind),
1229 unwindplan_regloc)) {
1230 have_unwindplan_regloc = true;
1232 "supplying caller's saved %s (%d)'s location using %s UnwindPlan",
1233 regnum.GetName(), regnum.GetAsKind(eRegisterKindLLDB),
1234 m_full_unwind_plan_sp->GetSourceName().GetCString());
1237 // This is frame 0 and we're retrieving the PC and it's saved in a Return
1238 // Address register and it hasn't been saved anywhere yet -- that is,
1239 // it's still live in the actual register. Handle this specially.
1241 if (have_unwindplan_regloc == false && return_address_reg.IsValid() &&
1243 if (return_address_reg.GetAsKind(eRegisterKindLLDB) !=
1244 LLDB_INVALID_REGNUM) {
1245 lldb_private::UnwindLLDB::RegisterLocation new_regloc;
1247 UnwindLLDB::RegisterLocation::eRegisterInLiveRegisterContext;
1248 new_regloc.location.register_number =
1249 return_address_reg.GetAsKind(eRegisterKindLLDB);
1250 m_registers[regnum.GetAsKind(eRegisterKindLLDB)] = new_regloc;
1251 regloc = new_regloc;
1252 UnwindLogMsg("supplying caller's register %s (%d) from the live "
1253 "RegisterContext at frame 0, saved in %d",
1254 return_address_reg.GetName(),
1255 return_address_reg.GetAsKind(eRegisterKindLLDB),
1256 return_address_reg.GetAsKind(eRegisterKindLLDB));
1257 return UnwindLLDB::RegisterSearchResult::eRegisterFound;
1261 // If this architecture stores the return address in a register (it
1262 // defines a Return Address register) and we're on a non-zero stack frame
1263 // and the Full UnwindPlan says that the pc is stored in the
1264 // RA registers (e.g. lr on arm), then we know that the full unwindplan is
1265 // not trustworthy -- this
1266 // is an impossible situation and the instruction emulation code has
1267 // likely been misled. If this stack frame meets those criteria, we need
1268 // to throw away the Full UnwindPlan that the instruction emulation came
1269 // up with and fall back to the architecture's Default UnwindPlan so the
1270 // stack walk can get past this point.
1272 // Special note: If the Full UnwindPlan was generated from the compiler,
1273 // don't second-guess it when we're at a call site location.
1275 // arch_default_ra_regnum is the return address register # in the Full
1276 // UnwindPlan register numbering
1277 RegisterNumber arch_default_ra_regnum(m_thread, eRegisterKindGeneric,
1278 LLDB_REGNUM_GENERIC_RA);
1280 if (arch_default_ra_regnum.GetAsKind(unwindplan_registerkind) !=
1281 LLDB_INVALID_REGNUM &&
1282 pc_regnum == regnum && unwindplan_regloc.IsInOtherRegister() &&
1283 unwindplan_regloc.GetRegisterNumber() ==
1284 arch_default_ra_regnum.GetAsKind(unwindplan_registerkind) &&
1285 m_full_unwind_plan_sp->GetSourcedFromCompiler() != eLazyBoolYes &&
1286 !m_all_registers_available) {
1287 UnwindLogMsg("%s UnwindPlan tried to restore the pc from the link "
1288 "register but this is a non-zero frame",
1289 m_full_unwind_plan_sp->GetSourceName().GetCString());
1291 // Throw away the full unwindplan; install the arch default unwindplan
1292 if (ForceSwitchToFallbackUnwindPlan()) {
1293 // Update for the possibly new unwind plan
1294 unwindplan_registerkind = m_full_unwind_plan_sp->GetRegisterKind();
1295 UnwindPlan::RowSP active_row =
1296 m_full_unwind_plan_sp->GetRowForFunctionOffset(m_current_offset);
1298 // Sanity check: Verify that we can fetch a pc value and CFA value
1299 // with this unwind plan
1301 RegisterNumber arch_default_pc_reg(m_thread, eRegisterKindGeneric,
1302 LLDB_REGNUM_GENERIC_PC);
1303 bool can_fetch_pc_value = false;
1304 bool can_fetch_cfa = false;
1307 if (arch_default_pc_reg.GetAsKind(unwindplan_registerkind) !=
1308 LLDB_INVALID_REGNUM &&
1309 active_row->GetRegisterInfo(
1310 arch_default_pc_reg.GetAsKind(unwindplan_registerkind),
1311 unwindplan_regloc)) {
1312 can_fetch_pc_value = true;
1314 if (ReadCFAValueForRow(unwindplan_registerkind, active_row,
1316 can_fetch_cfa = true;
1320 if (can_fetch_pc_value && can_fetch_cfa) {
1321 have_unwindplan_regloc = true;
1323 have_unwindplan_regloc = false;
1326 // We were unable to fall back to another unwind plan
1327 have_unwindplan_regloc = false;
1333 ExecutionContext exe_ctx(m_thread.shared_from_this());
1334 Process *process = exe_ctx.GetProcessPtr();
1335 if (have_unwindplan_regloc == false) {
1336 // If the UnwindPlan failed to give us an unwind location for this
1337 // register, we may be able to fall back to some ABI-defined default. For
1338 // example, some ABIs allow to determine the caller's SP via the CFA. Also,
1339 // the ABI may set volatile registers to the undefined state.
1340 ABI *abi = process ? process->GetABI().get() : NULL;
1342 const RegisterInfo *reg_info =
1343 GetRegisterInfoAtIndex(regnum.GetAsKind(eRegisterKindLLDB));
1345 abi->GetFallbackRegisterLocation(reg_info, unwindplan_regloc)) {
1347 "supplying caller's saved %s (%d)'s location using ABI default",
1348 regnum.GetName(), regnum.GetAsKind(eRegisterKindLLDB));
1349 have_unwindplan_regloc = true;
1354 if (have_unwindplan_regloc == false) {
1355 if (IsFrameZero()) {
1356 // This is frame 0 - we should return the actual live register context
1358 lldb_private::UnwindLLDB::RegisterLocation new_regloc;
1360 UnwindLLDB::RegisterLocation::eRegisterInLiveRegisterContext;
1361 new_regloc.location.register_number = regnum.GetAsKind(eRegisterKindLLDB);
1362 m_registers[regnum.GetAsKind(eRegisterKindLLDB)] = new_regloc;
1363 regloc = new_regloc;
1364 UnwindLogMsg("supplying caller's register %s (%d) from the live "
1365 "RegisterContext at frame 0",
1366 regnum.GetName(), regnum.GetAsKind(eRegisterKindLLDB));
1367 return UnwindLLDB::RegisterSearchResult::eRegisterFound;
1369 std::string unwindplan_name("");
1370 if (m_full_unwind_plan_sp) {
1371 unwindplan_name += "via '";
1372 unwindplan_name += m_full_unwind_plan_sp->GetSourceName().AsCString();
1373 unwindplan_name += "'";
1375 UnwindLogMsg("no save location for %s (%d) %s", regnum.GetName(),
1376 regnum.GetAsKind(eRegisterKindLLDB),
1377 unwindplan_name.c_str());
1379 return UnwindLLDB::RegisterSearchResult::eRegisterNotFound;
1382 // unwindplan_regloc has valid contents about where to retrieve the register
1383 if (unwindplan_regloc.IsUnspecified()) {
1384 lldb_private::UnwindLLDB::RegisterLocation new_regloc;
1385 new_regloc.type = UnwindLLDB::RegisterLocation::eRegisterNotSaved;
1386 m_registers[regnum.GetAsKind(eRegisterKindLLDB)] = new_regloc;
1387 UnwindLogMsg("save location for %s (%d) is unspecified, continue searching",
1388 regnum.GetName(), regnum.GetAsKind(eRegisterKindLLDB));
1389 return UnwindLLDB::RegisterSearchResult::eRegisterNotFound;
1392 if (unwindplan_regloc.IsUndefined()) {
1394 "did not supply reg location for %s (%d) because it is volatile",
1395 regnum.GetName(), regnum.GetAsKind(eRegisterKindLLDB));
1396 return UnwindLLDB::RegisterSearchResult::eRegisterIsVolatile;
1399 if (unwindplan_regloc.IsSame()) {
1400 if (IsFrameZero() == false &&
1401 (regnum.GetAsKind(eRegisterKindGeneric) == LLDB_REGNUM_GENERIC_PC ||
1402 regnum.GetAsKind(eRegisterKindGeneric) == LLDB_REGNUM_GENERIC_RA)) {
1403 UnwindLogMsg("register %s (%d) is marked as 'IsSame' - it is a pc or "
1404 "return address reg on a non-zero frame -- treat as if we "
1405 "have no information",
1406 regnum.GetName(), regnum.GetAsKind(eRegisterKindLLDB));
1407 return UnwindLLDB::RegisterSearchResult::eRegisterNotFound;
1409 regloc.type = UnwindLLDB::RegisterLocation::eRegisterInRegister;
1410 regloc.location.register_number = regnum.GetAsKind(eRegisterKindLLDB);
1411 m_registers[regnum.GetAsKind(eRegisterKindLLDB)] = regloc;
1413 "supplying caller's register %s (%d), saved in register %s (%d)",
1414 regnum.GetName(), regnum.GetAsKind(eRegisterKindLLDB),
1415 regnum.GetName(), regnum.GetAsKind(eRegisterKindLLDB));
1416 return UnwindLLDB::RegisterSearchResult::eRegisterFound;
1420 if (unwindplan_regloc.IsCFAPlusOffset()) {
1421 int offset = unwindplan_regloc.GetOffset();
1422 regloc.type = UnwindLLDB::RegisterLocation::eRegisterValueInferred;
1423 regloc.location.inferred_value = m_cfa + offset;
1424 m_registers[regnum.GetAsKind(eRegisterKindLLDB)] = regloc;
1425 UnwindLogMsg("supplying caller's register %s (%d), value is CFA plus "
1426 "offset %d [value is 0x%" PRIx64 "]",
1427 regnum.GetName(), regnum.GetAsKind(eRegisterKindLLDB), offset,
1428 regloc.location.inferred_value);
1429 return UnwindLLDB::RegisterSearchResult::eRegisterFound;
1432 if (unwindplan_regloc.IsAtCFAPlusOffset()) {
1433 int offset = unwindplan_regloc.GetOffset();
1434 regloc.type = UnwindLLDB::RegisterLocation::eRegisterSavedAtMemoryLocation;
1435 regloc.location.target_memory_location = m_cfa + offset;
1436 m_registers[regnum.GetAsKind(eRegisterKindLLDB)] = regloc;
1437 UnwindLogMsg("supplying caller's register %s (%d) from the stack, saved at "
1438 "CFA plus offset %d [saved at 0x%" PRIx64 "]",
1439 regnum.GetName(), regnum.GetAsKind(eRegisterKindLLDB), offset,
1440 regloc.location.target_memory_location);
1441 return UnwindLLDB::RegisterSearchResult::eRegisterFound;
1444 if (unwindplan_regloc.IsInOtherRegister()) {
1445 uint32_t unwindplan_regnum = unwindplan_regloc.GetRegisterNumber();
1446 RegisterNumber row_regnum(m_thread, unwindplan_registerkind,
1448 if (row_regnum.GetAsKind(eRegisterKindLLDB) == LLDB_INVALID_REGNUM) {
1449 UnwindLogMsg("could not supply caller's %s (%d) location - was saved in "
1450 "another reg but couldn't convert that regnum",
1451 regnum.GetName(), regnum.GetAsKind(eRegisterKindLLDB));
1452 return UnwindLLDB::RegisterSearchResult::eRegisterNotFound;
1454 regloc.type = UnwindLLDB::RegisterLocation::eRegisterInRegister;
1455 regloc.location.register_number = row_regnum.GetAsKind(eRegisterKindLLDB);
1456 m_registers[regnum.GetAsKind(eRegisterKindLLDB)] = regloc;
1458 "supplying caller's register %s (%d), saved in register %s (%d)",
1459 regnum.GetName(), regnum.GetAsKind(eRegisterKindLLDB),
1460 row_regnum.GetName(), row_regnum.GetAsKind(eRegisterKindLLDB));
1461 return UnwindLLDB::RegisterSearchResult::eRegisterFound;
1464 if (unwindplan_regloc.IsDWARFExpression() ||
1465 unwindplan_regloc.IsAtDWARFExpression()) {
1466 DataExtractor dwarfdata(unwindplan_regloc.GetDWARFExpressionBytes(),
1467 unwindplan_regloc.GetDWARFExpressionLength(),
1468 process->GetByteOrder(),
1469 process->GetAddressByteSize());
1470 ModuleSP opcode_ctx;
1471 DWARFExpression dwarfexpr(opcode_ctx, dwarfdata, nullptr, 0,
1472 unwindplan_regloc.GetDWARFExpressionLength());
1473 dwarfexpr.SetRegisterKind(unwindplan_registerkind);
1476 if (dwarfexpr.Evaluate(&exe_ctx, this, 0, nullptr, nullptr, result,
1479 val = result.GetScalar().ULongLong();
1480 if (unwindplan_regloc.IsDWARFExpression()) {
1481 regloc.type = UnwindLLDB::RegisterLocation::eRegisterValueInferred;
1482 regloc.location.inferred_value = val;
1483 m_registers[regnum.GetAsKind(eRegisterKindLLDB)] = regloc;
1484 UnwindLogMsg("supplying caller's register %s (%d) via DWARF expression "
1485 "(IsDWARFExpression)",
1486 regnum.GetName(), regnum.GetAsKind(eRegisterKindLLDB));
1487 return UnwindLLDB::RegisterSearchResult::eRegisterFound;
1490 UnwindLLDB::RegisterLocation::eRegisterSavedAtMemoryLocation;
1491 regloc.location.target_memory_location = val;
1492 m_registers[regnum.GetAsKind(eRegisterKindLLDB)] = regloc;
1493 UnwindLogMsg("supplying caller's register %s (%d) via DWARF expression "
1494 "(IsAtDWARFExpression)",
1495 regnum.GetName(), regnum.GetAsKind(eRegisterKindLLDB));
1496 return UnwindLLDB::RegisterSearchResult::eRegisterFound;
1499 UnwindLogMsg("tried to use IsDWARFExpression or IsAtDWARFExpression for %s "
1501 regnum.GetName(), regnum.GetAsKind(eRegisterKindLLDB));
1502 return UnwindLLDB::RegisterSearchResult::eRegisterNotFound;
1505 UnwindLogMsg("no save location for %s (%d) in this stack frame",
1506 regnum.GetName(), regnum.GetAsKind(eRegisterKindLLDB));
1508 // FIXME UnwindPlan::Row types atDWARFExpression and isDWARFExpression are
1511 return UnwindLLDB::RegisterSearchResult::eRegisterNotFound;
1514 // TryFallbackUnwindPlan() -- this method is a little tricky.
1516 // When this is called, the frame above -- the caller frame, the "previous"
1517 // frame -- is invalid or bad.
1519 // Instead of stopping the stack walk here, we'll try a different UnwindPlan
1520 // and see if we can get a valid frame above us.
1522 // This most often happens when an unwind plan based on assembly instruction
1523 // inspection is not correct -- mostly with hand-written assembly functions or
1524 // functions where the stack frame is set up "out of band", e.g. the kernel
1525 // saved the register context and then called an asynchronous trap handler like
1528 // Often in these cases, if we just do a dumb stack walk we'll get past this
1529 // tricky frame and our usual techniques can continue to be used.
1531 bool RegisterContextLLDB::TryFallbackUnwindPlan() {
1532 if (m_fallback_unwind_plan_sp.get() == nullptr)
1535 if (m_full_unwind_plan_sp.get() == nullptr)
1538 if (m_full_unwind_plan_sp.get() == m_fallback_unwind_plan_sp.get() ||
1539 m_full_unwind_plan_sp->GetSourceName() ==
1540 m_fallback_unwind_plan_sp->GetSourceName()) {
1544 // If a compiler generated unwind plan failed, trying the arch default
1545 // unwindplan isn't going to do any better.
1546 if (m_full_unwind_plan_sp->GetSourcedFromCompiler() == eLazyBoolYes)
1549 // Get the caller's pc value and our own CFA value. Swap in the fallback
1550 // unwind plan, re-fetch the caller's pc value and CFA value. If they're the
1551 // same, then the fallback unwind plan provides no benefit.
1553 RegisterNumber pc_regnum(m_thread, eRegisterKindGeneric,
1554 LLDB_REGNUM_GENERIC_PC);
1556 addr_t old_caller_pc_value = LLDB_INVALID_ADDRESS;
1557 addr_t new_caller_pc_value = LLDB_INVALID_ADDRESS;
1558 addr_t old_this_frame_cfa_value = m_cfa;
1559 UnwindLLDB::RegisterLocation regloc;
1560 if (SavedLocationForRegister(pc_regnum.GetAsKind(eRegisterKindLLDB),
1562 UnwindLLDB::RegisterSearchResult::eRegisterFound) {
1563 const RegisterInfo *reg_info =
1564 GetRegisterInfoAtIndex(pc_regnum.GetAsKind(eRegisterKindLLDB));
1566 RegisterValue reg_value;
1567 if (ReadRegisterValueFromRegisterLocation(regloc, reg_info, reg_value)) {
1568 old_caller_pc_value = reg_value.GetAsUInt64();
1573 // This is a tricky wrinkle! If SavedLocationForRegister() detects a really
1574 // impossible register location for the full unwind plan, it may call
1575 // ForceSwitchToFallbackUnwindPlan() which in turn replaces the full
1576 // unwindplan with the fallback... in short, we're done, we're using the
1577 // fallback UnwindPlan. We checked if m_fallback_unwind_plan_sp was nullptr
1578 // at the top -- the only way it became nullptr since then is via
1579 // SavedLocationForRegister().
1580 if (m_fallback_unwind_plan_sp.get() == nullptr)
1583 // Switch the full UnwindPlan to be the fallback UnwindPlan. If we decide
1584 // this isn't working, we need to restore. We'll also need to save & restore
1585 // the value of the m_cfa ivar. Save is down below a bit in 'old_cfa'.
1586 UnwindPlanSP original_full_unwind_plan_sp = m_full_unwind_plan_sp;
1587 addr_t old_cfa = m_cfa;
1589 m_registers.clear();
1591 m_full_unwind_plan_sp = m_fallback_unwind_plan_sp;
1593 UnwindPlan::RowSP active_row =
1594 m_fallback_unwind_plan_sp->GetRowForFunctionOffset(m_current_offset);
1597 active_row->GetCFAValue().GetValueType() !=
1598 UnwindPlan::Row::CFAValue::unspecified) {
1600 if (!ReadCFAValueForRow(m_fallback_unwind_plan_sp->GetRegisterKind(),
1601 active_row, new_cfa) ||
1602 new_cfa == 0 || new_cfa == 1 || new_cfa == LLDB_INVALID_ADDRESS) {
1603 UnwindLogMsg("failed to get cfa with fallback unwindplan");
1604 m_fallback_unwind_plan_sp.reset();
1605 m_full_unwind_plan_sp = original_full_unwind_plan_sp;
1611 if (SavedLocationForRegister(pc_regnum.GetAsKind(eRegisterKindLLDB),
1613 UnwindLLDB::RegisterSearchResult::eRegisterFound) {
1614 const RegisterInfo *reg_info =
1615 GetRegisterInfoAtIndex(pc_regnum.GetAsKind(eRegisterKindLLDB));
1617 RegisterValue reg_value;
1618 if (ReadRegisterValueFromRegisterLocation(regloc, reg_info,
1620 new_caller_pc_value = reg_value.GetAsUInt64();
1625 if (new_caller_pc_value == LLDB_INVALID_ADDRESS) {
1626 UnwindLogMsg("failed to get a pc value for the caller frame with the "
1627 "fallback unwind plan");
1628 m_fallback_unwind_plan_sp.reset();
1629 m_full_unwind_plan_sp = original_full_unwind_plan_sp;
1634 if (old_caller_pc_value != LLDB_INVALID_ADDRESS) {
1635 if (old_caller_pc_value == new_caller_pc_value &&
1636 new_cfa == old_this_frame_cfa_value) {
1637 UnwindLogMsg("fallback unwind plan got the same values for this frame "
1638 "CFA and caller frame pc, not using");
1639 m_fallback_unwind_plan_sp.reset();
1640 m_full_unwind_plan_sp = original_full_unwind_plan_sp;
1646 UnwindLogMsg("trying to unwind from this function with the UnwindPlan '%s' "
1647 "because UnwindPlan '%s' failed.",
1648 m_fallback_unwind_plan_sp->GetSourceName().GetCString(),
1649 original_full_unwind_plan_sp->GetSourceName().GetCString());
1651 // We've copied the fallback unwind plan into the full - now clear the
1653 m_fallback_unwind_plan_sp.reset();
1659 bool RegisterContextLLDB::ForceSwitchToFallbackUnwindPlan() {
1660 if (m_fallback_unwind_plan_sp.get() == NULL)
1663 if (m_full_unwind_plan_sp.get() == NULL)
1666 if (m_full_unwind_plan_sp.get() == m_fallback_unwind_plan_sp.get() ||
1667 m_full_unwind_plan_sp->GetSourceName() ==
1668 m_fallback_unwind_plan_sp->GetSourceName()) {
1672 UnwindPlan::RowSP active_row =
1673 m_fallback_unwind_plan_sp->GetRowForFunctionOffset(m_current_offset);
1676 active_row->GetCFAValue().GetValueType() !=
1677 UnwindPlan::Row::CFAValue::unspecified) {
1679 if (!ReadCFAValueForRow(m_fallback_unwind_plan_sp->GetRegisterKind(),
1680 active_row, new_cfa) ||
1681 new_cfa == 0 || new_cfa == 1 || new_cfa == LLDB_INVALID_ADDRESS) {
1682 UnwindLogMsg("failed to get cfa with fallback unwindplan");
1683 m_fallback_unwind_plan_sp.reset();
1687 m_full_unwind_plan_sp = m_fallback_unwind_plan_sp;
1688 m_fallback_unwind_plan_sp.reset();
1690 m_registers.clear();
1694 UnwindLogMsg("switched unconditionally to the fallback unwindplan %s",
1695 m_full_unwind_plan_sp->GetSourceName().GetCString());
1701 bool RegisterContextLLDB::ReadCFAValueForRow(
1702 lldb::RegisterKind row_register_kind, const UnwindPlan::RowSP &row,
1703 addr_t &cfa_value) {
1704 RegisterValue reg_value;
1706 cfa_value = LLDB_INVALID_ADDRESS;
1707 addr_t cfa_reg_contents;
1709 switch (row->GetCFAValue().GetValueType()) {
1710 case UnwindPlan::Row::CFAValue::isRegisterDereferenced: {
1711 RegisterNumber cfa_reg(m_thread, row_register_kind,
1712 row->GetCFAValue().GetRegisterNumber());
1713 if (ReadGPRValue(cfa_reg, cfa_reg_contents)) {
1714 const RegisterInfo *reg_info =
1715 GetRegisterInfoAtIndex(cfa_reg.GetAsKind(eRegisterKindLLDB));
1716 RegisterValue reg_value;
1718 Status error = ReadRegisterValueFromMemory(
1719 reg_info, cfa_reg_contents, reg_info->byte_size, reg_value);
1720 if (error.Success()) {
1721 cfa_value = reg_value.GetAsUInt64();
1723 "CFA value via dereferencing reg %s (%d): reg has val 0x%" PRIx64
1724 ", CFA value is 0x%" PRIx64,
1725 cfa_reg.GetName(), cfa_reg.GetAsKind(eRegisterKindLLDB),
1726 cfa_reg_contents, cfa_value);
1729 UnwindLogMsg("Tried to deref reg %s (%d) [0x%" PRIx64
1730 "] but memory read failed.",
1731 cfa_reg.GetName(), cfa_reg.GetAsKind(eRegisterKindLLDB),
1738 case UnwindPlan::Row::CFAValue::isRegisterPlusOffset: {
1739 RegisterNumber cfa_reg(m_thread, row_register_kind,
1740 row->GetCFAValue().GetRegisterNumber());
1741 if (ReadGPRValue(cfa_reg, cfa_reg_contents)) {
1742 if (cfa_reg_contents == LLDB_INVALID_ADDRESS || cfa_reg_contents == 0 ||
1743 cfa_reg_contents == 1) {
1745 "Got an invalid CFA register value - reg %s (%d), value 0x%" PRIx64,
1746 cfa_reg.GetName(), cfa_reg.GetAsKind(eRegisterKindLLDB),
1748 cfa_reg_contents = LLDB_INVALID_ADDRESS;
1751 cfa_value = cfa_reg_contents + row->GetCFAValue().GetOffset();
1753 "CFA is 0x%" PRIx64 ": Register %s (%d) contents are 0x%" PRIx64
1755 cfa_value, cfa_reg.GetName(), cfa_reg.GetAsKind(eRegisterKindLLDB),
1756 cfa_reg_contents, row->GetCFAValue().GetOffset());
1761 case UnwindPlan::Row::CFAValue::isDWARFExpression: {
1762 ExecutionContext exe_ctx(m_thread.shared_from_this());
1763 Process *process = exe_ctx.GetProcessPtr();
1764 DataExtractor dwarfdata(row->GetCFAValue().GetDWARFExpressionBytes(),
1765 row->GetCFAValue().GetDWARFExpressionLength(),
1766 process->GetByteOrder(),
1767 process->GetAddressByteSize());
1768 ModuleSP opcode_ctx;
1769 DWARFExpression dwarfexpr(opcode_ctx, dwarfdata, nullptr, 0,
1770 row->GetCFAValue().GetDWARFExpressionLength());
1771 dwarfexpr.SetRegisterKind(row_register_kind);
1774 if (dwarfexpr.Evaluate(&exe_ctx, this, 0, nullptr, nullptr, result,
1776 cfa_value = result.GetScalar().ULongLong();
1778 UnwindLogMsg("CFA value set by DWARF expression is 0x%" PRIx64,
1782 UnwindLogMsg("Failed to set CFA value via DWARF expression: %s",
1792 // Retrieve a general purpose register value for THIS frame, as saved by the
1793 // NEXT frame, i.e. the frame that
1794 // this frame called. e.g.
1797 // bar () { foo (); }
1798 // main () { bar (); }
1800 // stopped in foo() so
1804 // and this RegisterContext is for frame 1 (bar) - if we want to get the pc
1805 // value for frame 1, we need to ask
1806 // where frame 0 (the "next" frame) saved that and retrieve the value.
1808 bool RegisterContextLLDB::ReadGPRValue(lldb::RegisterKind register_kind,
1809 uint32_t regnum, addr_t &value) {
1813 uint32_t lldb_regnum;
1814 if (register_kind == eRegisterKindLLDB) {
1815 lldb_regnum = regnum;
1816 } else if (!m_thread.GetRegisterContext()->ConvertBetweenRegisterKinds(
1817 register_kind, regnum, eRegisterKindLLDB, lldb_regnum)) {
1821 const RegisterInfo *reg_info = GetRegisterInfoAtIndex(lldb_regnum);
1822 RegisterValue reg_value;
1823 // if this is frame 0 (currently executing frame), get the requested reg
1824 // contents from the actual thread registers
1825 if (IsFrameZero()) {
1826 if (m_thread.GetRegisterContext()->ReadRegister(reg_info, reg_value)) {
1827 value = reg_value.GetAsUInt64();
1833 bool pc_register = false;
1834 uint32_t generic_regnum;
1835 if (register_kind == eRegisterKindGeneric &&
1836 (regnum == LLDB_REGNUM_GENERIC_PC || regnum == LLDB_REGNUM_GENERIC_RA)) {
1838 } else if (m_thread.GetRegisterContext()->ConvertBetweenRegisterKinds(
1839 register_kind, regnum, eRegisterKindGeneric, generic_regnum) &&
1840 (generic_regnum == LLDB_REGNUM_GENERIC_PC ||
1841 generic_regnum == LLDB_REGNUM_GENERIC_RA)) {
1845 lldb_private::UnwindLLDB::RegisterLocation regloc;
1846 if (!m_parent_unwind.SearchForSavedLocationForRegister(
1847 lldb_regnum, regloc, m_frame_number - 1, pc_register)) {
1850 if (ReadRegisterValueFromRegisterLocation(regloc, reg_info, reg_value)) {
1851 value = reg_value.GetAsUInt64();
1857 bool RegisterContextLLDB::ReadGPRValue(const RegisterNumber ®num,
1859 return ReadGPRValue(regnum.GetRegisterKind(), regnum.GetRegisterNumber(),
1863 // Find the value of a register in THIS frame
1865 bool RegisterContextLLDB::ReadRegister(const RegisterInfo *reg_info,
1866 RegisterValue &value) {
1870 const uint32_t lldb_regnum = reg_info->kinds[eRegisterKindLLDB];
1871 UnwindLogMsgVerbose("looking for register saved location for reg %d",
1874 // If this is the 0th frame, hand this over to the live register context
1875 if (IsFrameZero()) {
1876 UnwindLogMsgVerbose("passing along to the live register context for reg %d",
1878 return m_thread.GetRegisterContext()->ReadRegister(reg_info, value);
1881 bool is_pc_regnum = false;
1882 if (reg_info->kinds[eRegisterKindGeneric] == LLDB_REGNUM_GENERIC_PC ||
1883 reg_info->kinds[eRegisterKindGeneric] == LLDB_REGNUM_GENERIC_RA) {
1884 is_pc_regnum = true;
1887 lldb_private::UnwindLLDB::RegisterLocation regloc;
1888 // Find out where the NEXT frame saved THIS frame's register contents
1889 if (!m_parent_unwind.SearchForSavedLocationForRegister(
1890 lldb_regnum, regloc, m_frame_number - 1, is_pc_regnum))
1893 return ReadRegisterValueFromRegisterLocation(regloc, reg_info, value);
1896 bool RegisterContextLLDB::WriteRegister(const RegisterInfo *reg_info,
1897 const RegisterValue &value) {
1901 const uint32_t lldb_regnum = reg_info->kinds[eRegisterKindLLDB];
1902 UnwindLogMsgVerbose("looking for register saved location for reg %d",
1905 // If this is the 0th frame, hand this over to the live register context
1906 if (IsFrameZero()) {
1907 UnwindLogMsgVerbose("passing along to the live register context for reg %d",
1909 return m_thread.GetRegisterContext()->WriteRegister(reg_info, value);
1912 lldb_private::UnwindLLDB::RegisterLocation regloc;
1913 // Find out where the NEXT frame saved THIS frame's register contents
1914 if (!m_parent_unwind.SearchForSavedLocationForRegister(
1915 lldb_regnum, regloc, m_frame_number - 1, false))
1918 return WriteRegisterValueToRegisterLocation(regloc, reg_info, value);
1921 // Don't need to implement this one
1922 bool RegisterContextLLDB::ReadAllRegisterValues(lldb::DataBufferSP &data_sp) {
1926 // Don't need to implement this one
1927 bool RegisterContextLLDB::WriteAllRegisterValues(
1928 const lldb::DataBufferSP &data_sp) {
1932 // Retrieve the pc value for THIS from
1934 bool RegisterContextLLDB::GetCFA(addr_t &cfa) {
1938 if (m_cfa == LLDB_INVALID_ADDRESS) {
1945 RegisterContextLLDB::SharedPtr RegisterContextLLDB::GetNextFrame() const {
1946 RegisterContextLLDB::SharedPtr regctx;
1947 if (m_frame_number == 0)
1949 return m_parent_unwind.GetRegisterContextForFrameNum(m_frame_number - 1);
1952 RegisterContextLLDB::SharedPtr RegisterContextLLDB::GetPrevFrame() const {
1953 RegisterContextLLDB::SharedPtr regctx;
1954 return m_parent_unwind.GetRegisterContextForFrameNum(m_frame_number + 1);
1957 // Retrieve the address of the start of the function of THIS frame
1959 bool RegisterContextLLDB::GetStartPC(addr_t &start_pc) {
1963 if (!m_start_pc.IsValid()) {
1964 bool read_successfully = ReadPC (start_pc);
1965 if (read_successfully)
1967 ProcessSP process_sp (m_thread.GetProcess());
1970 ABI *abi = process_sp->GetABI().get();
1972 start_pc = abi->FixCodeAddress(start_pc);
1975 return read_successfully;
1977 start_pc = m_start_pc.GetLoadAddress(CalculateTarget().get());
1981 // Retrieve the current pc value for THIS frame, as saved by the NEXT frame.
1983 bool RegisterContextLLDB::ReadPC(addr_t &pc) {
1987 bool above_trap_handler = false;
1988 if (GetNextFrame().get() && GetNextFrame()->IsValid() &&
1989 GetNextFrame()->IsTrapHandlerFrame())
1990 above_trap_handler = true;
1992 if (ReadGPRValue(eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC, pc)) {
1993 // A pc value of 0 or 1 is impossible in the middle of the stack -- it
1994 // indicates the end of a stack walk.
1995 // On the currently executing frame (or such a frame interrupted
1996 // asynchronously by sigtramp et al) this may occur if code has jumped
1997 // through a NULL pointer -- we want to be able to unwind past that frame
1998 // to help find the bug.
2000 ProcessSP process_sp (m_thread.GetProcess());
2003 ABI *abi = process_sp->GetABI().get();
2005 pc = abi->FixCodeAddress(pc);
2008 if (m_all_registers_available == false && above_trap_handler == false &&
2009 (pc == 0 || pc == 1)) {
2019 void RegisterContextLLDB::UnwindLogMsg(const char *fmt, ...) {
2020 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_UNWIND));
2023 va_start(args, fmt);
2026 if (vasprintf(&logmsg, fmt, args) == -1 || logmsg == NULL) {
2034 log->Printf("%*sth%d/fr%u %s", m_frame_number < 100 ? m_frame_number : 100,
2035 "", m_thread.GetIndexID(), m_frame_number, logmsg);
2040 void RegisterContextLLDB::UnwindLogMsgVerbose(const char *fmt, ...) {
2041 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_UNWIND));
2042 if (log && log->GetVerbose()) {
2044 va_start(args, fmt);
2047 if (vasprintf(&logmsg, fmt, args) == -1 || logmsg == NULL) {
2055 log->Printf("%*sth%d/fr%u %s", m_frame_number < 100 ? m_frame_number : 100,
2056 "", m_thread.GetIndexID(), m_frame_number, logmsg);