2461 lines · cpp
1//===-- RegisterContextUnwind.cpp -----------------------------------------===//2//3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.4// See https://llvm.org/LICENSE.txt for license information.5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception6//7//===----------------------------------------------------------------------===//8 9#include "lldb/Target/RegisterContextUnwind.h"10#include "lldb/Core/Address.h"11#include "lldb/Core/AddressRange.h"12#include "lldb/Core/Module.h"13#include "lldb/Core/Value.h"14#include "lldb/Expression/DWARFExpressionList.h"15#include "lldb/Symbol/ArmUnwindInfo.h"16#include "lldb/Symbol/CallFrameInfo.h"17#include "lldb/Symbol/DWARFCallFrameInfo.h"18#include "lldb/Symbol/FuncUnwinders.h"19#include "lldb/Symbol/Function.h"20#include "lldb/Symbol/ObjectFile.h"21#include "lldb/Symbol/Symbol.h"22#include "lldb/Symbol/SymbolContext.h"23#include "lldb/Symbol/SymbolFile.h"24#include "lldb/Target/ABI.h"25#include "lldb/Target/DynamicLoader.h"26#include "lldb/Target/ExecutionContext.h"27#include "lldb/Target/LanguageRuntime.h"28#include "lldb/Target/Platform.h"29#include "lldb/Target/Process.h"30#include "lldb/Target/SectionLoadList.h"31#include "lldb/Target/StackFrame.h"32#include "lldb/Target/Target.h"33#include "lldb/Target/Thread.h"34#include "lldb/Utility/DataBufferHeap.h"35#include "lldb/Utility/LLDBLog.h"36#include "lldb/Utility/Log.h"37#include "lldb/Utility/RegisterValue.h"38#include "lldb/Utility/VASPrintf.h"39#include "lldb/lldb-private.h"40 41#include <cassert>42#include <memory>43 44using namespace lldb;45using namespace lldb_private;46 47static ConstString GetSymbolOrFunctionName(const SymbolContext &sym_ctx) {48 if (sym_ctx.symbol)49 return sym_ctx.symbol->GetName();50 else if (sym_ctx.function)51 return sym_ctx.function->GetName();52 return ConstString();53}54 55static bool CallFrameAddressIsValid(ABISP abi_sp, lldb::addr_t cfa) {56 if (cfa == LLDB_INVALID_ADDRESS)57 return false;58 if (abi_sp)59 return abi_sp->CallFrameAddressIsValid(cfa);60 return cfa != 0 && cfa != 1;61}62 63RegisterContextUnwind::RegisterContextUnwind(Thread &thread,64 const SharedPtr &next_frame,65 SymbolContext &sym_ctx,66 uint32_t frame_number,67 UnwindLLDB &unwind_lldb)68 : RegisterContext(thread, frame_number), m_thread(thread),69 m_fast_unwind_plan_sp(), m_full_unwind_plan_sp(),70 m_fallback_unwind_plan_sp(), m_all_registers_available(false),71 m_frame_type(-1), m_cfa(LLDB_INVALID_ADDRESS),72 m_afa(LLDB_INVALID_ADDRESS), m_start_pc(), m_current_pc(),73 m_current_offset(0), m_current_offset_backed_up_one(0),74 m_behaves_like_zeroth_frame(false), m_sym_ctx(sym_ctx),75 m_sym_ctx_valid(false), m_frame_number(frame_number), m_registers(),76 m_parent_unwind(unwind_lldb) {77 m_sym_ctx.Clear(false);78 m_sym_ctx_valid = false;79 80 if (IsFrameZero()) {81 InitializeZerothFrame();82 } else {83 InitializeNonZerothFrame();84 }85 86 // This same code exists over in the GetFullUnwindPlanForFrame() but it may87 // not have been executed yet88 if (IsFrameZero() || next_frame->m_frame_type == eTrapHandlerFrame ||89 next_frame->m_frame_type == eDebuggerFrame) {90 m_all_registers_available = true;91 }92}93 94bool RegisterContextUnwind::IsUnwindPlanValidForCurrentPC(95 std::shared_ptr<const UnwindPlan> unwind_plan_sp) {96 if (!unwind_plan_sp)97 return false;98 99 // check if m_current_pc is valid100 if (unwind_plan_sp->PlanValidAtAddress(m_current_pc)) {101 // yes - current offset can be used as is102 return true;103 }104 105 // If don't have an offset or we're at the start of the function, we've got106 // nothing else to try.107 if (!m_current_offset || m_current_offset == 0)108 return false;109 110 // check pc - 1 to see if it's valid111 Address pc_minus_one(m_current_pc);112 pc_minus_one.SetOffset(m_current_pc.GetOffset() - 1);113 if (unwind_plan_sp->PlanValidAtAddress(pc_minus_one)) {114 return true;115 }116 117 return false;118}119 120// Initialize a RegisterContextUnwind which is the first frame of a stack -- the121// zeroth frame or currently executing frame.122 123void RegisterContextUnwind::InitializeZerothFrame() {124 Log *log = GetLog(LLDBLog::Unwind);125 ExecutionContext exe_ctx(m_thread.shared_from_this());126 RegisterContextSP reg_ctx_sp = m_thread.GetRegisterContext();127 128 if (reg_ctx_sp.get() == nullptr) {129 m_frame_type = eNotAValidFrame;130 UnwindLogMsg("frame does not have a register context");131 return;132 }133 134 addr_t current_pc = reg_ctx_sp->GetPC();135 136 if (current_pc == LLDB_INVALID_ADDRESS) {137 m_frame_type = eNotAValidFrame;138 UnwindLogMsg("frame does not have a pc");139 return;140 }141 142 Process *process = exe_ctx.GetProcessPtr();143 144 // Let ABIs fixup code addresses to make sure they are valid. In ARM ABIs145 // this will strip bit zero in case we read a PC from memory or from the LR.146 // (which would be a no-op in frame 0 where we get it from the register set,147 // but still a good idea to make the call here for other ABIs that may148 // exist.)149 if (ABISP abi_sp = process->GetABI())150 current_pc = abi_sp->FixCodeAddress(current_pc);151 152 std::shared_ptr<const UnwindPlan> lang_runtime_plan_sp =153 LanguageRuntime::GetRuntimeUnwindPlan(m_thread, this,154 m_behaves_like_zeroth_frame);155 if (lang_runtime_plan_sp.get()) {156 UnwindLogMsg("This is an async frame");157 }158 159 // Initialize m_current_pc, an Address object, based on current_pc, an160 // addr_t.161 m_current_pc.SetLoadAddress(current_pc, &process->GetTarget());162 163 // If we don't have a Module for some reason, we're not going to find164 // symbol/function information - just stick in some reasonable defaults and165 // hope we can unwind past this frame.166 ModuleSP pc_module_sp(m_current_pc.GetModule());167 if (!m_current_pc.IsValid() || !pc_module_sp) {168 UnwindLogMsg("using architectural default unwind method");169 }170 171 m_sym_ctx_valid = m_current_pc.ResolveFunctionScope(m_sym_ctx);172 173 if (m_sym_ctx.symbol) {174 UnwindLogMsg("with pc value of 0x%" PRIx64 ", symbol name is '%s'",175 current_pc, GetSymbolOrFunctionName(m_sym_ctx).AsCString(""));176 } else if (m_sym_ctx.function) {177 UnwindLogMsg("with pc value of 0x%" PRIx64 ", function name is '%s'",178 current_pc, GetSymbolOrFunctionName(m_sym_ctx).AsCString(""));179 } else {180 UnwindLogMsg("with pc value of 0x%" PRIx64181 ", no symbol/function name is known.",182 current_pc);183 }184 185 if (IsTrapHandlerSymbol(process, m_sym_ctx)) {186 m_frame_type = eTrapHandlerFrame;187 } else {188 // FIXME: Detect eDebuggerFrame here.189 m_frame_type = eNormalFrame;190 }191 192 // If we were able to find a symbol/function, set addr_range to the bounds of193 // that symbol/function. else treat the current pc value as the start_pc and194 // record no offset.195 if (m_sym_ctx_valid) {196 m_start_pc = m_sym_ctx.GetFunctionOrSymbolAddress();197 if (m_current_pc.GetModule() == m_start_pc.GetModule()) {198 m_current_offset =199 m_current_pc.GetFileAddress() - m_start_pc.GetFileAddress();200 }201 m_current_offset_backed_up_one = m_current_offset;202 } else {203 m_start_pc = m_current_pc;204 m_current_offset = std::nullopt;205 m_current_offset_backed_up_one = std::nullopt;206 }207 208 // We've set m_frame_type and m_sym_ctx before these calls.209 210 m_fast_unwind_plan_sp = GetFastUnwindPlanForFrame();211 m_full_unwind_plan_sp = GetFullUnwindPlanForFrame();212 213 const UnwindPlan::Row *active_row = nullptr;214 lldb::RegisterKind row_register_kind = eRegisterKindGeneric;215 216 // If we have LanguageRuntime UnwindPlan for this unwind, use those217 // rules to find the caller frame instead of the function's normal218 // UnwindPlans. The full unwind plan for this frame will be219 // the LanguageRuntime-provided unwind plan, and there will not be a220 // fast unwind plan.221 if (lang_runtime_plan_sp.get()) {222 active_row =223 lang_runtime_plan_sp->GetRowForFunctionOffset(m_current_offset);224 row_register_kind = lang_runtime_plan_sp->GetRegisterKind();225 if (!ReadFrameAddress(row_register_kind, active_row->GetCFAValue(),226 m_cfa)) {227 UnwindLogMsg("Cannot set cfa");228 } else {229 m_full_unwind_plan_sp = lang_runtime_plan_sp;230 if (log) {231 StreamString active_row_strm;232 active_row->Dump(active_row_strm, lang_runtime_plan_sp.get(), &m_thread,233 m_start_pc.GetLoadAddress(exe_ctx.GetTargetPtr()));234 UnwindLogMsg("async active row: %s", active_row_strm.GetData());235 }236 UnwindLogMsg("m_cfa = 0x%" PRIx64 " m_afa = 0x%" PRIx64, m_cfa, m_afa);237 UnwindLogMsg(238 "initialized async frame current pc is 0x%" PRIx64239 " cfa is 0x%" PRIx64 " afa is 0x%" PRIx64,240 (uint64_t)m_current_pc.GetLoadAddress(exe_ctx.GetTargetPtr()),241 (uint64_t)m_cfa, (uint64_t)m_afa);242 243 return;244 }245 }246 247 if (m_full_unwind_plan_sp &&248 m_full_unwind_plan_sp->PlanValidAtAddress(m_current_pc)) {249 active_row =250 m_full_unwind_plan_sp->GetRowForFunctionOffset(m_current_offset);251 row_register_kind = m_full_unwind_plan_sp->GetRegisterKind();252 PropagateTrapHandlerFlagFromUnwindPlan(m_full_unwind_plan_sp);253 if (active_row && log) {254 StreamString active_row_strm;255 active_row->Dump(active_row_strm, m_full_unwind_plan_sp.get(), &m_thread,256 m_start_pc.GetLoadAddress(exe_ctx.GetTargetPtr()));257 UnwindLogMsg("%s", active_row_strm.GetData());258 }259 }260 261 if (!active_row) {262 UnwindLogMsg("could not find an unwindplan row for this frame's pc");263 m_frame_type = eNotAValidFrame;264 return;265 }266 267 if (!ReadFrameAddress(row_register_kind, active_row->GetCFAValue(), m_cfa)) {268 // Try the fall back unwind plan since the269 // full unwind plan failed.270 FuncUnwindersSP func_unwinders_sp;271 std::shared_ptr<const UnwindPlan> call_site_unwind_plan;272 bool cfa_status = false;273 274 if (m_sym_ctx_valid) {275 func_unwinders_sp =276 pc_module_sp->GetUnwindTable().GetFuncUnwindersContainingAddress(277 m_current_pc, m_sym_ctx);278 }279 280 if (func_unwinders_sp.get() != nullptr)281 call_site_unwind_plan = func_unwinders_sp->GetUnwindPlanAtCallSite(282 process->GetTarget(), m_thread);283 284 if (call_site_unwind_plan != nullptr) {285 m_fallback_unwind_plan_sp = call_site_unwind_plan;286 if (TryFallbackUnwindPlan())287 cfa_status = true;288 }289 if (!cfa_status) {290 UnwindLogMsg("could not read CFA value for first frame.");291 m_frame_type = eNotAValidFrame;292 return;293 }294 } else295 ReadFrameAddress(row_register_kind, active_row->GetAFAValue(), m_afa);296 297 if (m_cfa == LLDB_INVALID_ADDRESS && m_afa == LLDB_INVALID_ADDRESS) {298 UnwindLogMsg(299 "could not read CFA or AFA values for first frame, not valid.");300 m_frame_type = eNotAValidFrame;301 return;302 }303 304 // Give the Architecture a chance to replace the UnwindPlan.305 TryAdoptArchitectureUnwindPlan();306 307 UnwindLogMsg("initialized frame current pc is 0x%" PRIx64 " cfa is 0x%" PRIx64308 " afa is 0x%" PRIx64 " using %s UnwindPlan",309 (uint64_t)m_current_pc.GetLoadAddress(exe_ctx.GetTargetPtr()),310 (uint64_t)m_cfa,311 (uint64_t)m_afa,312 m_full_unwind_plan_sp->GetSourceName().GetCString());313}314 315// Initialize a RegisterContextUnwind for the non-zeroth frame -- rely on the316// RegisterContextUnwind "below" it to provide things like its current pc value.317 318void RegisterContextUnwind::InitializeNonZerothFrame() {319 Log *log = GetLog(LLDBLog::Unwind);320 if (IsFrameZero()) {321 m_frame_type = eNotAValidFrame;322 UnwindLogMsg("non-zeroth frame tests positive for IsFrameZero -- that "323 "shouldn't happen.");324 return;325 }326 327 if (!GetNextFrame().get() || !GetNextFrame()->IsValid()) {328 m_frame_type = eNotAValidFrame;329 UnwindLogMsg("Could not get next frame, marking this frame as invalid.");330 return;331 }332 if (!m_thread.GetRegisterContext()) {333 m_frame_type = eNotAValidFrame;334 UnwindLogMsg("Could not get register context for this thread, marking this "335 "frame as invalid.");336 return;337 }338 339 ExecutionContext exe_ctx(m_thread.shared_from_this());340 Process *process = exe_ctx.GetProcessPtr();341 342 // Some languages may have a logical parent stack frame which is343 // not a real stack frame, but the programmer would consider it to344 // be the caller of the frame, e.g. Swift asynchronous frames.345 //346 // A LanguageRuntime may provide an UnwindPlan that is used in this347 // stack trace base on the RegisterContext contents, intsead348 // of the normal UnwindPlans we would use for the return-pc.349 std::shared_ptr<const UnwindPlan> lang_runtime_plan_sp =350 LanguageRuntime::GetRuntimeUnwindPlan(m_thread, this,351 m_behaves_like_zeroth_frame);352 if (lang_runtime_plan_sp.get()) {353 UnwindLogMsg("This is an async frame");354 }355 356 addr_t pc;357 if (!ReadGPRValue(eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC, pc)) {358 UnwindLogMsg("could not get pc value");359 m_frame_type = eNotAValidFrame;360 return;361 }362 363 // Let ABIs fixup code addresses to make sure they are valid. In ARM ABIs364 // this will strip bit zero in case we read a PC from memory or from the LR.365 ABISP abi_sp = process->GetABI();366 if (abi_sp)367 pc = abi_sp->FixCodeAddress(pc);368 369 if (log) {370 UnwindLogMsg("pc = 0x%" PRIx64, pc);371 addr_t reg_val;372 if (ReadGPRValue(eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FP, reg_val))373 UnwindLogMsg("fp = 0x%" PRIx64, reg_val);374 if (ReadGPRValue(eRegisterKindGeneric, LLDB_REGNUM_GENERIC_SP, reg_val))375 UnwindLogMsg("sp = 0x%" PRIx64, reg_val);376 }377 378 // A pc of 0x0 means it's the end of the stack crawl unless we're above a trap379 // handler function380 bool above_trap_handler = false;381 if (GetNextFrame().get() && GetNextFrame()->IsValid() &&382 GetNextFrame()->IsTrapHandlerFrame())383 above_trap_handler = true;384 385 if (pc == 0 || pc == 0x1) {386 if (!above_trap_handler) {387 m_frame_type = eNotAValidFrame;388 UnwindLogMsg("this frame has a pc of 0x0");389 return;390 }391 }392 393 const bool allow_section_end = true;394 m_current_pc.SetLoadAddress(pc, &process->GetTarget(), allow_section_end);395 396 // If we don't have a Module for some reason, we're not going to find397 // symbol/function information - just stick in some reasonable defaults and398 // hope we can unwind past this frame. If we're above a trap handler,399 // we may be at a bogus address because we jumped through a bogus function400 // pointer and trapped, so don't force the arch default unwind plan in that401 // case.402 ModuleSP pc_module_sp(m_current_pc.GetModule());403 if ((!m_current_pc.IsValid() || !pc_module_sp) &&404 above_trap_handler == false) {405 UnwindLogMsg("using architectural default unwind method");406 407 // Test the pc value to see if we know it's in an unmapped/non-executable408 // region of memory.409 uint32_t permissions;410 if (process->GetLoadAddressPermissions(pc, permissions) &&411 (permissions & ePermissionsExecutable) == 0) {412 // If this is the second frame off the stack, we may have unwound the413 // first frame incorrectly. But using the architecture default unwind414 // plan may get us back on track -- albeit possibly skipping a real415 // frame. Give this frame a clearly-invalid pc and see if we can get any416 // further.417 if (GetNextFrame().get() && GetNextFrame()->IsValid() &&418 GetNextFrame()->IsFrameZero()) {419 UnwindLogMsg("had a pc of 0x%" PRIx64 " which is not in executable "420 "memory but on frame 1 -- "421 "allowing it once.",422 (uint64_t)pc);423 m_frame_type = eSkipFrame;424 } else {425 // anywhere other than the second frame, a non-executable pc means426 // we're off in the weeds -- stop now.427 m_frame_type = eNotAValidFrame;428 UnwindLogMsg("pc is in a non-executable section of memory and this "429 "isn't the 2nd frame in the stack walk.");430 return;431 }432 }433 434 if (abi_sp) {435 m_fast_unwind_plan_sp.reset();436 m_full_unwind_plan_sp = abi_sp->CreateDefaultUnwindPlan();437 if (m_frame_type != eSkipFrame) // don't override eSkipFrame438 {439 m_frame_type = eNormalFrame;440 }441 m_all_registers_available = false;442 m_current_offset = std::nullopt;443 m_current_offset_backed_up_one = std::nullopt;444 RegisterKind row_register_kind = m_full_unwind_plan_sp->GetRegisterKind();445 if (const UnwindPlan::Row *row =446 m_full_unwind_plan_sp->GetRowForFunctionOffset(0)) {447 if (!ReadFrameAddress(row_register_kind, row->GetCFAValue(), m_cfa)) {448 UnwindLogMsg("failed to get cfa value");449 if (m_frame_type != eSkipFrame) // don't override eSkipFrame450 {451 m_frame_type = eNotAValidFrame;452 }453 return;454 }455 456 ReadFrameAddress(row_register_kind, row->GetAFAValue(), m_afa);457 458 // A couple of sanity checks..459 if (!CallFrameAddressIsValid(abi_sp, m_cfa)) {460 UnwindLogMsg("could not find a valid cfa address");461 m_frame_type = eNotAValidFrame;462 return;463 }464 465 // m_cfa should point into the stack memory; if we can query memory466 // region permissions, see if the memory is allocated & readable.467 if (process->GetLoadAddressPermissions(m_cfa, permissions) &&468 (permissions & ePermissionsReadable) == 0) {469 m_frame_type = eNotAValidFrame;470 UnwindLogMsg(471 "the CFA points to a region of memory that is not readable");472 return;473 }474 } else {475 UnwindLogMsg("could not find a row for function offset zero");476 m_frame_type = eNotAValidFrame;477 return;478 }479 480 if (CheckIfLoopingStack()) {481 TryFallbackUnwindPlan();482 if (CheckIfLoopingStack()) {483 UnwindLogMsg("same CFA address as next frame, assuming the unwind is "484 "looping - stopping");485 m_frame_type = eNotAValidFrame;486 return;487 }488 }489 490 // Give the Architecture a chance to replace the UnwindPlan.491 TryAdoptArchitectureUnwindPlan();492 493 UnwindLogMsg("initialized frame cfa is 0x%" PRIx64 " afa is 0x%" PRIx64,494 (uint64_t)m_cfa, (uint64_t)m_afa);495 return;496 }497 m_frame_type = eNotAValidFrame;498 UnwindLogMsg("could not find any symbol for this pc, or a default unwind "499 "plan, to continue unwind.");500 return;501 }502 503 m_sym_ctx_valid = m_current_pc.ResolveFunctionScope(m_sym_ctx);504 505 if (m_sym_ctx.symbol) {506 UnwindLogMsg("with pc value of 0x%" PRIx64 ", symbol name is '%s'", pc,507 GetSymbolOrFunctionName(m_sym_ctx).AsCString(""));508 } else if (m_sym_ctx.function) {509 UnwindLogMsg("with pc value of 0x%" PRIx64 ", function name is '%s'", pc,510 GetSymbolOrFunctionName(m_sym_ctx).AsCString(""));511 } else {512 UnwindLogMsg("with pc value of 0x%" PRIx64513 ", no symbol/function name is known.",514 pc);515 }516 517 bool decr_pc_and_recompute_addr_range;518 519 if (!m_sym_ctx_valid) {520 // Always decrement and recompute if the symbol lookup failed521 decr_pc_and_recompute_addr_range = true;522 } else if (GetNextFrame()->m_frame_type == eTrapHandlerFrame ||523 GetNextFrame()->m_frame_type == eDebuggerFrame) {524 // Don't decrement if we're "above" an asynchronous event like525 // sigtramp.526 decr_pc_and_recompute_addr_range = false;527 } else if (Address addr = m_sym_ctx.GetFunctionOrSymbolAddress();528 addr != m_current_pc) {529 // If our "current" pc isn't the start of a function, decrement the pc530 // if we're up the stack.531 if (m_behaves_like_zeroth_frame)532 decr_pc_and_recompute_addr_range = false;533 else534 decr_pc_and_recompute_addr_range = true;535 } else if (IsTrapHandlerSymbol(process, m_sym_ctx)) {536 // Signal dispatch may set the return address of the handler it calls to537 // point to the first byte of a return trampoline (like __kernel_rt_sigreturn),538 // so do not decrement and recompute if the symbol we already found is a trap539 // handler.540 decr_pc_and_recompute_addr_range = false;541 } else if (m_behaves_like_zeroth_frame) {542 decr_pc_and_recompute_addr_range = false;543 } else {544 // Decrement to find the function containing the call.545 decr_pc_and_recompute_addr_range = true;546 }547 548 // We need to back up the pc by 1 byte and re-search for the Symbol to handle549 // the case where the "saved pc" value is pointing to the next function, e.g.550 // if a function ends with a CALL instruction.551 // FIXME this may need to be an architectural-dependent behavior; if so we'll552 // need to add a member function553 // to the ABI plugin and consult that.554 if (decr_pc_and_recompute_addr_range) {555 UnwindLogMsg("Backing up the pc value of 0x%" PRIx64556 " by 1 and re-doing symbol lookup; old symbol was %s",557 pc, GetSymbolOrFunctionName(m_sym_ctx).AsCString(""));558 Address temporary_pc;559 temporary_pc.SetLoadAddress(pc - 1, &process->GetTarget());560 m_sym_ctx.Clear(false);561 m_sym_ctx_valid = temporary_pc.ResolveFunctionScope(m_sym_ctx);562 563 UnwindLogMsg("Symbol is now %s",564 GetSymbolOrFunctionName(m_sym_ctx).AsCString(""));565 }566 567 // If we were able to find a symbol/function, set addr_range_ptr to the568 // bounds of that symbol/function. else treat the current pc value as the569 // start_pc and record no offset.570 if (m_sym_ctx_valid) {571 m_start_pc = m_sym_ctx.GetFunctionOrSymbolAddress();572 m_current_offset = pc - m_start_pc.GetLoadAddress(&process->GetTarget());573 m_current_offset_backed_up_one = m_current_offset;574 if (decr_pc_and_recompute_addr_range &&575 m_current_offset_backed_up_one != 0) {576 --*m_current_offset_backed_up_one;577 if (m_sym_ctx_valid) {578 m_current_pc.SetLoadAddress(pc - 1, &process->GetTarget());579 }580 }581 } else {582 m_start_pc = m_current_pc;583 m_current_offset = std::nullopt;584 m_current_offset_backed_up_one = std::nullopt;585 }586 587 if (IsTrapHandlerSymbol(process, m_sym_ctx)) {588 m_frame_type = eTrapHandlerFrame;589 } else {590 // FIXME: Detect eDebuggerFrame here.591 if (m_frame_type != eSkipFrame) // don't override eSkipFrame592 {593 m_frame_type = eNormalFrame;594 }595 }596 597 const UnwindPlan::Row *active_row;598 RegisterKind row_register_kind = eRegisterKindGeneric;599 600 // If we have LanguageRuntime UnwindPlan for this unwind, use those601 // rules to find the caller frame instead of the function's normal602 // UnwindPlans. The full unwind plan for this frame will be603 // the LanguageRuntime-provided unwind plan, and there will not be a604 // fast unwind plan.605 if (lang_runtime_plan_sp.get()) {606 active_row =607 lang_runtime_plan_sp->GetRowForFunctionOffset(m_current_offset);608 row_register_kind = lang_runtime_plan_sp->GetRegisterKind();609 if (!ReadFrameAddress(row_register_kind, active_row->GetCFAValue(),610 m_cfa)) {611 UnwindLogMsg("Cannot set cfa");612 } else {613 m_full_unwind_plan_sp = lang_runtime_plan_sp;614 if (log) {615 StreamString active_row_strm;616 active_row->Dump(active_row_strm, lang_runtime_plan_sp.get(), &m_thread,617 m_start_pc.GetLoadAddress(exe_ctx.GetTargetPtr()));618 UnwindLogMsg("async active row: %s", active_row_strm.GetData());619 }620 UnwindLogMsg("m_cfa = 0x%" PRIx64 " m_afa = 0x%" PRIx64, m_cfa, m_afa);621 UnwindLogMsg(622 "initialized async frame current pc is 0x%" PRIx64623 " cfa is 0x%" PRIx64 " afa is 0x%" PRIx64,624 (uint64_t)m_current_pc.GetLoadAddress(exe_ctx.GetTargetPtr()),625 (uint64_t)m_cfa, (uint64_t)m_afa);626 627 return;628 }629 }630 631 // We've set m_frame_type and m_sym_ctx before this call.632 m_fast_unwind_plan_sp = GetFastUnwindPlanForFrame();633 634 // Try to get by with just the fast UnwindPlan if possible - the full635 // UnwindPlan may be expensive to get (e.g. if we have to parse the entire636 // eh_frame section of an ObjectFile for the first time.)637 638 if (m_fast_unwind_plan_sp &&639 m_fast_unwind_plan_sp->PlanValidAtAddress(m_current_pc)) {640 active_row =641 m_fast_unwind_plan_sp->GetRowForFunctionOffset(m_current_offset);642 row_register_kind = m_fast_unwind_plan_sp->GetRegisterKind();643 PropagateTrapHandlerFlagFromUnwindPlan(m_fast_unwind_plan_sp);644 if (active_row && log) {645 StreamString active_row_strm;646 active_row->Dump(active_row_strm, m_fast_unwind_plan_sp.get(), &m_thread,647 m_start_pc.GetLoadAddress(exe_ctx.GetTargetPtr()));648 UnwindLogMsg("Using fast unwind plan '%s'",649 m_fast_unwind_plan_sp->GetSourceName().AsCString());650 UnwindLogMsg("active row: %s", active_row_strm.GetData());651 }652 } else {653 m_full_unwind_plan_sp = GetFullUnwindPlanForFrame();654 if (IsUnwindPlanValidForCurrentPC(m_full_unwind_plan_sp)) {655 active_row = m_full_unwind_plan_sp->GetRowForFunctionOffset(656 m_current_offset_backed_up_one);657 row_register_kind = m_full_unwind_plan_sp->GetRegisterKind();658 PropagateTrapHandlerFlagFromUnwindPlan(m_full_unwind_plan_sp);659 if (active_row && log) {660 StreamString active_row_strm;661 active_row->Dump(active_row_strm, m_full_unwind_plan_sp.get(),662 &m_thread,663 m_start_pc.GetLoadAddress(exe_ctx.GetTargetPtr()));664 UnwindLogMsg("Using full unwind plan '%s'",665 m_full_unwind_plan_sp->GetSourceName().AsCString());666 UnwindLogMsg("active row: %s", active_row_strm.GetData());667 }668 }669 }670 671 if (!active_row) {672 m_frame_type = eNotAValidFrame;673 UnwindLogMsg("could not find unwind row for this pc");674 return;675 }676 677 if (!ReadFrameAddress(row_register_kind, active_row->GetCFAValue(), m_cfa)) {678 UnwindLogMsg("failed to get cfa");679 m_frame_type = eNotAValidFrame;680 return;681 }682 683 ReadFrameAddress(row_register_kind, active_row->GetAFAValue(), m_afa);684 685 UnwindLogMsg("m_cfa = 0x%" PRIx64 " m_afa = 0x%" PRIx64, m_cfa, m_afa);686 687 if (CheckIfLoopingStack()) {688 TryFallbackUnwindPlan();689 if (CheckIfLoopingStack()) {690 UnwindLogMsg("same CFA address as next frame, assuming the unwind is "691 "looping - stopping");692 m_frame_type = eNotAValidFrame;693 return;694 }695 }696 697 // Give the Architecture a chance to replace the UnwindPlan.698 TryAdoptArchitectureUnwindPlan();699 700 UnwindLogMsg("initialized frame current pc is 0x%" PRIx64701 " cfa is 0x%" PRIx64 " afa is 0x%" PRIx64,702 (uint64_t)m_current_pc.GetLoadAddress(exe_ctx.GetTargetPtr()),703 (uint64_t)m_cfa,704 (uint64_t)m_afa);705}706 707bool RegisterContextUnwind::CheckIfLoopingStack() {708 // If we have a bad stack setup, we can get the same CFA value multiple times709 // -- or even more devious, we can actually oscillate between two CFA values.710 // Detect that here and break out to avoid a possible infinite loop in lldb711 // trying to unwind the stack. To detect when we have the same CFA value712 // multiple times, we compare the713 // CFA of the current714 // frame with the 2nd next frame because in some specail case (e.g. signal715 // hanlders, hand written assembly without ABI compliance) we can have 2716 // frames with the same717 // CFA (in theory we718 // can have arbitrary number of frames with the same CFA, but more then 2 is719 // very unlikely)720 721 RegisterContextUnwind::SharedPtr next_frame = GetNextFrame();722 if (next_frame) {723 RegisterContextUnwind::SharedPtr next_next_frame =724 next_frame->GetNextFrame();725 addr_t next_next_frame_cfa = LLDB_INVALID_ADDRESS;726 if (next_next_frame && next_next_frame->GetCFA(next_next_frame_cfa)) {727 if (next_next_frame_cfa == m_cfa) {728 // We have a loop in the stack unwind729 return true;730 }731 }732 }733 return false;734}735 736bool RegisterContextUnwind::IsFrameZero() const { return m_frame_number == 0; }737 738bool RegisterContextUnwind::BehavesLikeZerothFrame() const {739 if (m_frame_number == 0)740 return true;741 if (m_behaves_like_zeroth_frame)742 return true;743 return false;744}745 746// Find a fast unwind plan for this frame, if possible.747//748// On entry to this method,749//750// 1. m_frame_type should already be set to eTrapHandlerFrame/eDebuggerFrame751// if either of those are correct,752// 2. m_sym_ctx should already be filled in, and753// 3. m_current_pc should have the current pc value for this frame754// 4. m_current_offset_backed_up_one should have the current byte offset into755// the function, maybe backed up by 1, std::nullopt if unknown756 757std::shared_ptr<const UnwindPlan>758RegisterContextUnwind::GetFastUnwindPlanForFrame() {759 ModuleSP pc_module_sp(m_current_pc.GetModule());760 761 if (!m_current_pc.IsValid() || !pc_module_sp ||762 pc_module_sp->GetObjectFile() == nullptr)763 return nullptr;764 765 if (IsFrameZero())766 return nullptr;767 768 FuncUnwindersSP func_unwinders_sp(769 pc_module_sp->GetUnwindTable().GetFuncUnwindersContainingAddress(770 m_current_pc, m_sym_ctx));771 if (!func_unwinders_sp)772 return nullptr;773 774 // If we're in _sigtramp(), unwinding past this frame requires special775 // knowledge.776 if (m_frame_type == eTrapHandlerFrame || m_frame_type == eDebuggerFrame)777 return nullptr;778 779 if (std::shared_ptr<const UnwindPlan> unwind_plan_sp =780 func_unwinders_sp->GetUnwindPlanFastUnwind(781 *m_thread.CalculateTarget(), m_thread)) {782 if (unwind_plan_sp->PlanValidAtAddress(m_current_pc)) {783 m_frame_type = eNormalFrame;784 return unwind_plan_sp;785 }786 }787 return nullptr;788}789 790// On entry to this method,791//792// 1. m_frame_type should already be set to eTrapHandlerFrame/eDebuggerFrame793// if either of those are correct,794// 2. m_sym_ctx should already be filled in, and795// 3. m_current_pc should have the current pc value for this frame796// 4. m_current_offset_backed_up_one should have the current byte offset into797// the function, maybe backed up by 1, std::nullopt if unknown798 799std::shared_ptr<const UnwindPlan>800RegisterContextUnwind::GetFullUnwindPlanForFrame() {801 std::shared_ptr<const UnwindPlan> arch_default_unwind_plan_sp;802 ExecutionContext exe_ctx(m_thread.shared_from_this());803 Process *process = exe_ctx.GetProcessPtr();804 ABI *abi = process ? process->GetABI().get() : nullptr;805 if (abi) {806 arch_default_unwind_plan_sp = abi->CreateDefaultUnwindPlan();807 } else {808 UnwindLogMsg(809 "unable to get architectural default UnwindPlan from ABI plugin");810 }811 812 if (IsFrameZero() || GetNextFrame()->m_frame_type == eTrapHandlerFrame ||813 GetNextFrame()->m_frame_type == eDebuggerFrame) {814 m_behaves_like_zeroth_frame = true;815 // If this frame behaves like a 0th frame (currently executing or816 // interrupted asynchronously), all registers can be retrieved.817 m_all_registers_available = true;818 }819 820 // If we've done a jmp 0x0 / bl 0x0 (called through a null function pointer)821 // so the pc is 0x0 in the zeroth frame, we need to use the "unwind at first822 // instruction" arch default UnwindPlan Also, if this Process can report on823 // memory region attributes, any non-executable region means we jumped824 // through a bad function pointer - handle the same way as 0x0. Note, if we825 // have a symbol context & a symbol, we don't want to follow this code path.826 // This is for jumping to memory regions without any information available.827 828 if ((!m_sym_ctx_valid ||829 (m_sym_ctx.function == nullptr && m_sym_ctx.symbol == nullptr)) &&830 m_behaves_like_zeroth_frame && m_current_pc.IsValid()) {831 uint32_t permissions;832 addr_t current_pc_addr =833 m_current_pc.GetLoadAddress(exe_ctx.GetTargetPtr());834 if (current_pc_addr == 0 ||835 (process &&836 process->GetLoadAddressPermissions(current_pc_addr, permissions) &&837 (permissions & ePermissionsExecutable) == 0)) {838 if (abi) {839 m_frame_type = eNormalFrame;840 return abi->CreateFunctionEntryUnwindPlan();841 }842 }843 }844 845 // No Module for the current pc, try using the architecture default unwind.846 ModuleSP pc_module_sp(m_current_pc.GetModule());847 if (!m_current_pc.IsValid() || !pc_module_sp ||848 pc_module_sp->GetObjectFile() == nullptr) {849 m_frame_type = eNormalFrame;850 return arch_default_unwind_plan_sp;851 }852 853 FuncUnwindersSP func_unwinders_sp;854 if (m_sym_ctx_valid) {855 func_unwinders_sp =856 pc_module_sp->GetUnwindTable().GetFuncUnwindersContainingAddress(857 m_current_pc, m_sym_ctx);858 }859 860 // No FuncUnwinders available for this pc (stripped function symbols, lldb861 // could not augment its function table with another source, like862 // LC_FUNCTION_STARTS or eh_frame in ObjectFileMachO). See if eh_frame or the863 // .ARM.exidx tables have unwind information for this address, else fall back864 // to the architectural default unwind.865 if (!func_unwinders_sp) {866 m_frame_type = eNormalFrame;867 868 if (!pc_module_sp || !pc_module_sp->GetObjectFile() ||869 !m_current_pc.IsValid())870 return arch_default_unwind_plan_sp;871 872 // Even with -fomit-frame-pointer, we can try eh_frame to get back on873 // track.874 if (DWARFCallFrameInfo *eh_frame =875 pc_module_sp->GetUnwindTable().GetEHFrameInfo()) {876 if (std::unique_ptr<UnwindPlan> plan_up =877 eh_frame->GetUnwindPlan(m_current_pc))878 return plan_up;879 }880 881 ArmUnwindInfo *arm_exidx =882 pc_module_sp->GetUnwindTable().GetArmUnwindInfo();883 if (arm_exidx) {884 auto unwind_plan_sp =885 std::make_shared<UnwindPlan>(lldb::eRegisterKindGeneric);886 if (arm_exidx->GetUnwindPlan(exe_ctx.GetTargetRef(), m_current_pc,887 *unwind_plan_sp))888 return unwind_plan_sp;889 }890 891 CallFrameInfo *object_file_unwind =892 pc_module_sp->GetUnwindTable().GetObjectFileUnwindInfo();893 if (object_file_unwind) {894 if (std::unique_ptr<UnwindPlan> plan_up =895 object_file_unwind->GetUnwindPlan(m_current_pc))896 return plan_up;897 }898 899 return arch_default_unwind_plan_sp;900 }901 902 if (m_frame_type == eTrapHandlerFrame && process) {903 m_fast_unwind_plan_sp.reset();904 905 // On some platforms the unwind information for signal handlers is not906 // present or correct. Give the platform plugins a chance to provide907 // substitute plan. Otherwise, use eh_frame.908 if (m_sym_ctx_valid) {909 lldb::PlatformSP platform = process->GetTarget().GetPlatform();910 if (auto unwind_plan_sp = platform->GetTrapHandlerUnwindPlan(911 process->GetTarget().GetArchitecture().GetTriple(),912 GetSymbolOrFunctionName(m_sym_ctx)))913 return unwind_plan_sp;914 }915 916 auto unwind_plan_sp =917 func_unwinders_sp->GetEHFrameUnwindPlan(process->GetTarget());918 if (!unwind_plan_sp)919 unwind_plan_sp =920 func_unwinders_sp->GetObjectFileUnwindPlan(process->GetTarget());921 if (unwind_plan_sp && unwind_plan_sp->PlanValidAtAddress(m_current_pc) &&922 unwind_plan_sp->GetSourcedFromCompiler() == eLazyBoolYes) {923 return unwind_plan_sp;924 }925 }926 927 // Ask the DynamicLoader if the eh_frame CFI should be trusted in this frame928 // even when it's frame zero This comes up if we have hand-written functions929 // in a Module and hand-written eh_frame. The assembly instruction930 // inspection may fail and the eh_frame CFI were probably written with some931 // care to do the right thing. It'd be nice if there was a way to ask the932 // eh_frame directly if it is asynchronous (can be trusted at every933 // instruction point) or synchronous (the normal case - only at call sites).934 // But there is not.935 if (process && process->GetDynamicLoader() &&936 process->GetDynamicLoader()->AlwaysRelyOnEHUnwindInfo(m_sym_ctx)) {937 // We must specifically call the GetEHFrameUnwindPlan() method here --938 // normally we would call GetUnwindPlanAtCallSite() -- because CallSite may939 // return an unwind plan sourced from either eh_frame (that's what we940 // intend) or compact unwind (this won't work)941 auto unwind_plan_sp =942 func_unwinders_sp->GetEHFrameUnwindPlan(process->GetTarget());943 if (!unwind_plan_sp)944 unwind_plan_sp =945 func_unwinders_sp->GetObjectFileUnwindPlan(process->GetTarget());946 if (unwind_plan_sp && unwind_plan_sp->PlanValidAtAddress(m_current_pc)) {947 UnwindLogMsgVerbose("frame uses %s for full UnwindPlan because the "948 "DynamicLoader suggested we prefer it",949 unwind_plan_sp->GetSourceName().GetCString());950 return unwind_plan_sp;951 }952 }953 954 // Typically the NonCallSite UnwindPlan is the unwind created by inspecting955 // the assembly language instructions956 if (m_behaves_like_zeroth_frame && process) {957 auto unwind_plan_sp = func_unwinders_sp->GetUnwindPlanAtNonCallSite(958 process->GetTarget(), m_thread);959 if (unwind_plan_sp && unwind_plan_sp->PlanValidAtAddress(m_current_pc)) {960 if (unwind_plan_sp->GetSourcedFromCompiler() == eLazyBoolNo) {961 // We probably have an UnwindPlan created by inspecting assembly962 // instructions. The assembly profilers work really well with compiler-963 // generated functions but hand- written assembly can be problematic.964 // We set the eh_frame based unwind plan as our fallback unwind plan if965 // instruction emulation doesn't work out even for non call sites if it966 // is available and use the architecture default unwind plan if it is967 // not available. The eh_frame unwind plan is more reliable even on non968 // call sites then the architecture default plan and for hand written969 // assembly code it is often written in a way that it valid at all970 // location what helps in the most common cases when the instruction971 // emulation fails.972 std::shared_ptr<const UnwindPlan> call_site_unwind_plan =973 func_unwinders_sp->GetUnwindPlanAtCallSite(process->GetTarget(),974 m_thread);975 if (call_site_unwind_plan &&976 call_site_unwind_plan.get() != unwind_plan_sp.get() &&977 call_site_unwind_plan->GetSourceName() !=978 unwind_plan_sp->GetSourceName()) {979 m_fallback_unwind_plan_sp = call_site_unwind_plan;980 } else {981 m_fallback_unwind_plan_sp = arch_default_unwind_plan_sp;982 }983 }984 UnwindLogMsgVerbose("frame uses %s for full UnwindPlan because this "985 "is the non-call site unwind plan and this is a "986 "zeroth frame",987 unwind_plan_sp->GetSourceName().GetCString());988 return unwind_plan_sp;989 }990 991 // If we're on the first instruction of a function, and we have an992 // architectural default UnwindPlan for the initial instruction of a993 // function, use that.994 if (m_current_offset == 0) {995 unwind_plan_sp =996 func_unwinders_sp->GetUnwindPlanArchitectureDefaultAtFunctionEntry(997 m_thread);998 if (unwind_plan_sp) {999 UnwindLogMsgVerbose("frame uses %s for full UnwindPlan because we are at "1000 "the first instruction of a function",1001 unwind_plan_sp->GetSourceName().GetCString());1002 return unwind_plan_sp;1003 }1004 }1005 }1006 1007 std::shared_ptr<const UnwindPlan> unwind_plan_sp;1008 // Typically this is unwind info from an eh_frame section intended for1009 // exception handling; only valid at call sites1010 if (process) {1011 unwind_plan_sp = func_unwinders_sp->GetUnwindPlanAtCallSite(1012 process->GetTarget(), m_thread);1013 }1014 if (IsUnwindPlanValidForCurrentPC(unwind_plan_sp)) {1015 UnwindLogMsgVerbose("frame uses %s for full UnwindPlan because this "1016 "is the call-site unwind plan",1017 unwind_plan_sp->GetSourceName().GetCString());1018 return unwind_plan_sp;1019 }1020 1021 // We'd prefer to use an UnwindPlan intended for call sites when we're at a1022 // call site but if we've struck out on that, fall back to using the non-1023 // call-site assembly inspection UnwindPlan if possible.1024 if (process) {1025 unwind_plan_sp = func_unwinders_sp->GetUnwindPlanAtNonCallSite(1026 process->GetTarget(), m_thread);1027 }1028 if (unwind_plan_sp &&1029 unwind_plan_sp->GetSourcedFromCompiler() == eLazyBoolNo) {1030 // We probably have an UnwindPlan created by inspecting assembly1031 // instructions. The assembly profilers work really well with compiler-1032 // generated functions but hand- written assembly can be problematic. We1033 // set the eh_frame based unwind plan as our fallback unwind plan if1034 // instruction emulation doesn't work out even for non call sites if it is1035 // available and use the architecture default unwind plan if it is not1036 // available. The eh_frame unwind plan is more reliable even on non call1037 // sites then the architecture default plan and for hand written assembly1038 // code it is often written in a way that it valid at all location what1039 // helps in the most common cases when the instruction emulation fails.1040 std::shared_ptr<const UnwindPlan> call_site_unwind_plan =1041 func_unwinders_sp->GetUnwindPlanAtCallSite(process->GetTarget(),1042 m_thread);1043 if (call_site_unwind_plan &&1044 call_site_unwind_plan.get() != unwind_plan_sp.get() &&1045 call_site_unwind_plan->GetSourceName() !=1046 unwind_plan_sp->GetSourceName()) {1047 m_fallback_unwind_plan_sp = call_site_unwind_plan;1048 } else {1049 m_fallback_unwind_plan_sp = arch_default_unwind_plan_sp;1050 }1051 }1052 1053 if (IsUnwindPlanValidForCurrentPC(unwind_plan_sp)) {1054 UnwindLogMsgVerbose("frame uses %s for full UnwindPlan because we "1055 "failed to find a call-site unwind plan that would work",1056 unwind_plan_sp->GetSourceName().GetCString());1057 return unwind_plan_sp;1058 }1059 1060 // If nothing else, use the architectural default UnwindPlan and hope that1061 // does the job.1062 if (arch_default_unwind_plan_sp)1063 UnwindLogMsgVerbose(1064 "frame uses %s for full UnwindPlan because we are falling back "1065 "to the arch default plan",1066 arch_default_unwind_plan_sp->GetSourceName().GetCString());1067 else1068 UnwindLogMsg(1069 "Unable to find any UnwindPlan for full unwind of this frame.");1070 1071 return arch_default_unwind_plan_sp;1072}1073 1074void RegisterContextUnwind::InvalidateAllRegisters() {1075 m_frame_type = eNotAValidFrame;1076}1077 1078size_t RegisterContextUnwind::GetRegisterCount() {1079 return m_thread.GetRegisterContext()->GetRegisterCount();1080}1081 1082const RegisterInfo *RegisterContextUnwind::GetRegisterInfoAtIndex(size_t reg) {1083 return m_thread.GetRegisterContext()->GetRegisterInfoAtIndex(reg);1084}1085 1086size_t RegisterContextUnwind::GetRegisterSetCount() {1087 return m_thread.GetRegisterContext()->GetRegisterSetCount();1088}1089 1090const RegisterSet *RegisterContextUnwind::GetRegisterSet(size_t reg_set) {1091 return m_thread.GetRegisterContext()->GetRegisterSet(reg_set);1092}1093 1094uint32_t RegisterContextUnwind::ConvertRegisterKindToRegisterNumber(1095 lldb::RegisterKind kind, uint32_t num) {1096 return m_thread.GetRegisterContext()->ConvertRegisterKindToRegisterNumber(1097 kind, num);1098}1099 1100bool RegisterContextUnwind::ReadRegisterValueFromRegisterLocation(1101 lldb_private::UnwindLLDB::ConcreteRegisterLocation regloc,1102 const RegisterInfo *reg_info, RegisterValue &value) {1103 if (!IsValid())1104 return false;1105 bool success = false;1106 1107 switch (regloc.type) {1108 case UnwindLLDB::ConcreteRegisterLocation::eRegisterInLiveRegisterContext: {1109 const RegisterInfo *other_reg_info =1110 GetRegisterInfoAtIndex(regloc.location.register_number);1111 1112 if (!other_reg_info)1113 return false;1114 1115 success =1116 m_thread.GetRegisterContext()->ReadRegister(other_reg_info, value);1117 } break;1118 case UnwindLLDB::ConcreteRegisterLocation::eRegisterInRegister: {1119 const RegisterInfo *other_reg_info =1120 GetRegisterInfoAtIndex(regloc.location.register_number);1121 1122 if (!other_reg_info)1123 return false;1124 1125 if (IsFrameZero()) {1126 success =1127 m_thread.GetRegisterContext()->ReadRegister(other_reg_info, value);1128 } else {1129 success = GetNextFrame()->ReadRegister(other_reg_info, value);1130 }1131 } break;1132 case UnwindLLDB::ConcreteRegisterLocation::eRegisterIsRegisterPlusOffset: {1133 auto regnum = regloc.location.reg_plus_offset.register_number;1134 const RegisterInfo *other_reg_info =1135 GetRegisterInfoAtIndex(regloc.location.reg_plus_offset.register_number);1136 1137 if (!other_reg_info)1138 return false;1139 1140 if (IsFrameZero()) {1141 success =1142 m_thread.GetRegisterContext()->ReadRegister(other_reg_info, value);1143 } else {1144 success = GetNextFrame()->ReadRegister(other_reg_info, value);1145 }1146 if (success) {1147 UnwindLogMsg("read (%d)'s location", regnum);1148 value = value.GetAsUInt64(~0ull, &success) +1149 regloc.location.reg_plus_offset.offset;1150 UnwindLogMsg("success %s", success ? "yes" : "no");1151 }1152 } break;1153 case UnwindLLDB::ConcreteRegisterLocation::eRegisterValueInferred:1154 success =1155 value.SetUInt(regloc.location.inferred_value, reg_info->byte_size);1156 break;1157 1158 case UnwindLLDB::ConcreteRegisterLocation::eRegisterNotSaved:1159 break;1160 case UnwindLLDB::ConcreteRegisterLocation::eRegisterSavedAtHostMemoryLocation:1161 llvm_unreachable("FIXME debugger inferior function call unwind");1162 case UnwindLLDB::ConcreteRegisterLocation::eRegisterSavedAtMemoryLocation: {1163 Status error(ReadRegisterValueFromMemory(1164 reg_info, regloc.location.target_memory_location, reg_info->byte_size,1165 value));1166 success = error.Success();1167 } break;1168 default:1169 llvm_unreachable("Unknown ConcreteRegisterLocation type.");1170 }1171 return success;1172}1173 1174bool RegisterContextUnwind::WriteRegisterValueToRegisterLocation(1175 lldb_private::UnwindLLDB::ConcreteRegisterLocation regloc,1176 const RegisterInfo *reg_info, const RegisterValue &value) {1177 if (!IsValid())1178 return false;1179 1180 bool success = false;1181 1182 switch (regloc.type) {1183 case UnwindLLDB::ConcreteRegisterLocation::eRegisterInLiveRegisterContext: {1184 const RegisterInfo *other_reg_info =1185 GetRegisterInfoAtIndex(regloc.location.register_number);1186 success =1187 m_thread.GetRegisterContext()->WriteRegister(other_reg_info, value);1188 } break;1189 case UnwindLLDB::ConcreteRegisterLocation::eRegisterInRegister: {1190 const RegisterInfo *other_reg_info =1191 GetRegisterInfoAtIndex(regloc.location.register_number);1192 if (IsFrameZero()) {1193 success =1194 m_thread.GetRegisterContext()->WriteRegister(other_reg_info, value);1195 } else {1196 success = GetNextFrame()->WriteRegister(other_reg_info, value);1197 }1198 } break;1199 case UnwindLLDB::ConcreteRegisterLocation::eRegisterIsRegisterPlusOffset:1200 case UnwindLLDB::ConcreteRegisterLocation::eRegisterValueInferred:1201 case UnwindLLDB::ConcreteRegisterLocation::eRegisterNotSaved:1202 break;1203 case UnwindLLDB::ConcreteRegisterLocation::eRegisterSavedAtHostMemoryLocation:1204 llvm_unreachable("FIXME debugger inferior function call unwind");1205 case UnwindLLDB::ConcreteRegisterLocation::eRegisterSavedAtMemoryLocation: {1206 Status error(WriteRegisterValueToMemory(1207 reg_info, regloc.location.target_memory_location, reg_info->byte_size,1208 value));1209 success = error.Success();1210 } break;1211 default:1212 llvm_unreachable("Unknown ConcreteRegisterLocation type.");1213 }1214 return success;1215}1216 1217bool RegisterContextUnwind::IsValid() const {1218 return m_frame_type != eNotAValidFrame;1219}1220 1221// After the final stack frame in a stack walk we'll get one invalid1222// (eNotAValidFrame) stack frame -- one past the end of the stack walk. But1223// higher-level code will need to tell the difference between "the unwind plan1224// below this frame failed" versus "we successfully completed the stack walk"1225// so this method helps to disambiguate that.1226 1227bool RegisterContextUnwind::IsTrapHandlerFrame() const {1228 return m_frame_type == eTrapHandlerFrame;1229}1230 1231// A skip frame is a bogus frame on the stack -- but one where we're likely to1232// find a real frame farther1233// up the stack if we keep looking. It's always the second frame in an unwind1234// (i.e. the first frame after frame zero) where unwinding can be the1235// trickiest. Ideally we'll mark up this frame in some way so the user knows1236// we're displaying bad data and we may have skipped one frame of their real1237// program in the process of getting back on track.1238 1239bool RegisterContextUnwind::IsSkipFrame() const {1240 return m_frame_type == eSkipFrame;1241}1242 1243bool RegisterContextUnwind::IsTrapHandlerSymbol(1244 lldb_private::Process *process,1245 const lldb_private::SymbolContext &m_sym_ctx) const {1246 PlatformSP platform_sp(process->GetTarget().GetPlatform());1247 if (platform_sp) {1248 const std::vector<ConstString> trap_handler_names(1249 platform_sp->GetTrapHandlerSymbolNames());1250 for (ConstString name : trap_handler_names) {1251 if ((m_sym_ctx.function && m_sym_ctx.function->GetName() == name) ||1252 (m_sym_ctx.symbol && m_sym_ctx.symbol->GetName() == name)) {1253 return true;1254 }1255 }1256 }1257 const std::vector<ConstString> user_specified_trap_handler_names(1258 m_parent_unwind.GetUserSpecifiedTrapHandlerFunctionNames());1259 for (ConstString name : user_specified_trap_handler_names) {1260 if ((m_sym_ctx.function && m_sym_ctx.function->GetName() == name) ||1261 (m_sym_ctx.symbol && m_sym_ctx.symbol->GetName() == name)) {1262 return true;1263 }1264 }1265 1266 return false;1267}1268 1269// Search this stack frame's UnwindPlans for the AbstractRegisterLocation1270// for this register.1271//1272// \param[in] lldb_regnum1273// The register number (in the eRegisterKindLLDB register numbering)1274// we are searching for.1275//1276// \param[out] kind1277// Set to the RegisterKind of the UnwindPlan which is the basis for1278// the returned AbstractRegisterLocation; if the location is in terms1279// of another register number, this Kind is needed to interpret it1280// correctly.1281//1282// \return1283// An empty optional indicaTes that there was an error in processing1284// the request.1285//1286// If there is no unwind rule for a volatile (caller-preserved) register,1287// the returned AbstractRegisterLocation will be IsUndefined,1288// indicating that we should stop searching.1289//1290// If there is no unwind rule for a non-volatile (callee-preserved)1291// register, the returned AbstractRegisterLocation will be IsSame.1292// In frame 0, IsSame means get the value from the live register context.1293// Else it means to continue descending down the stack to more-live frames1294// looking for a location/value.1295//1296// If an AbstractRegisterLocation is found in an UnwindPlan, that will1297// be returned, with no consideration of the current ABI rules for1298// registers. Functions using an alternate ABI calling convention1299// will work as long as the UnwindPlans are exhaustive about what1300// registers are volatile/non-volatile.1301std::optional<UnwindPlan::Row::AbstractRegisterLocation>1302RegisterContextUnwind::GetAbstractRegisterLocation(uint32_t lldb_regnum,1303 lldb::RegisterKind &kind) {1304 RegisterNumber regnum(m_thread, eRegisterKindLLDB, lldb_regnum);1305 Log *log = GetLog(LLDBLog::Unwind);1306 1307 kind = eRegisterKindLLDB;1308 UnwindPlan::Row::AbstractRegisterLocation unwindplan_regloc;1309 1310 // First, try to find a register location via the FastUnwindPlan1311 if (m_fast_unwind_plan_sp) {1312 const UnwindPlan::Row *active_row =1313 m_fast_unwind_plan_sp->GetRowForFunctionOffset(m_current_offset);1314 if (regnum.GetAsKind(kind) == LLDB_INVALID_REGNUM) {1315 UnwindLogMsg("could not convert lldb regnum %s (%d) into %d RegisterKind "1316 "reg numbering scheme",1317 regnum.GetName(), regnum.GetAsKind(eRegisterKindLLDB),1318 (int)kind);1319 return {};1320 }1321 kind = m_fast_unwind_plan_sp->GetRegisterKind();1322 // The Fast UnwindPlan typically only provides fp & pc as we move up1323 // the stack, without requiring additional parsing or memory reads.1324 // It may mark all other registers as IsUndefined() because, indicating1325 // that it doesn't know if they were spilled to stack or not.1326 // If this case, for an IsUndefined register, we should continue on1327 // to the Full UnwindPlan which may have more accurate information1328 // about register locations of all registers.1329 if (active_row &&1330 active_row->GetRegisterInfo(regnum.GetAsKind(kind),1331 unwindplan_regloc) &&1332 !unwindplan_regloc.IsUndefined()) {1333 UnwindLogMsg(1334 "supplying caller's saved %s (%d)'s location using FastUnwindPlan",1335 regnum.GetName(), regnum.GetAsKind(eRegisterKindLLDB));1336 return unwindplan_regloc;1337 }1338 }1339 1340 // Second, try to find a register location via the FullUnwindPlan.1341 bool got_new_full_unwindplan = false;1342 if (!m_full_unwind_plan_sp) {1343 m_full_unwind_plan_sp = GetFullUnwindPlanForFrame();1344 got_new_full_unwindplan = true;1345 }1346 if (m_full_unwind_plan_sp) {1347 RegisterNumber pc_regnum(m_thread, eRegisterKindGeneric,1348 LLDB_REGNUM_GENERIC_PC);1349 1350 const UnwindPlan::Row *active_row =1351 m_full_unwind_plan_sp->GetRowForFunctionOffset(1352 m_current_offset_backed_up_one);1353 kind = m_full_unwind_plan_sp->GetRegisterKind();1354 1355 if (got_new_full_unwindplan && active_row && log) {1356 StreamString active_row_strm;1357 ExecutionContext exe_ctx(m_thread.shared_from_this());1358 active_row->Dump(active_row_strm, m_full_unwind_plan_sp.get(), &m_thread,1359 m_start_pc.GetLoadAddress(exe_ctx.GetTargetPtr()));1360 UnwindLogMsg("Using full unwind plan '%s'",1361 m_full_unwind_plan_sp->GetSourceName().AsCString());1362 UnwindLogMsg("active row: %s", active_row_strm.GetData());1363 }1364 1365 if (regnum.GetAsKind(kind) == LLDB_INVALID_REGNUM) {1366 if (kind == eRegisterKindGeneric)1367 UnwindLogMsg("could not convert lldb regnum %s (%d) into "1368 "eRegisterKindGeneric reg numbering scheme",1369 regnum.GetName(), regnum.GetAsKind(eRegisterKindLLDB));1370 else1371 UnwindLogMsg("could not convert lldb regnum %s (%d) into %d "1372 "RegisterKind reg numbering scheme",1373 regnum.GetName(), regnum.GetAsKind(eRegisterKindLLDB),1374 (int)kind);1375 return {};1376 }1377 1378 if (regnum.IsValid() && active_row &&1379 active_row->GetRegisterInfo(regnum.GetAsKind(kind),1380 unwindplan_regloc)) {1381 UnwindLogMsg(1382 "supplying caller's saved %s (%d)'s location using %s UnwindPlan",1383 regnum.GetName(), regnum.GetAsKind(eRegisterKindLLDB),1384 m_full_unwind_plan_sp->GetSourceName().GetCString());1385 return unwindplan_regloc;1386 }1387 1388 // When asking for the caller's pc, and did not find a register1389 // location for PC above in the UnwindPlan. Check if we have a1390 // Return Address register on this target.1391 //1392 // On a Return Address Register architecture like arm/mips/riscv,1393 // the caller's pc is in the RA register, and will be spilled to1394 // stack before any other function is called. If no function1395 // has been called yet, the return address may still be in the1396 // live RA reg.1397 //1398 // There's a lot of variety of what we might see in an UnwindPlan.1399 // We may have1400 // ra=IsSame {unncessary}1401 // ra=StackAddr {caller's return addr spilled to stack}1402 // or no reg location for pc or ra at all, in a frameless function -1403 // the caller's return address is in live ra reg.1404 //1405 // If a function has been interrupted in a non-call way --1406 // async signal/sigtramp, or a hardware exception / interrupt / fault --1407 // then the "pc" and "ra" are two distinct values, and must be1408 // handled separately. The "pc" is the pc value at the point1409 // the function was interrupted. The "ra" is the return address1410 // register value at that point.1411 // The UnwindPlan for the sigtramp/trap handler will normally have1412 // register loations for both pc and lr, and so we'll have already1413 // fetched them above.1414 if (pc_regnum.IsValid() && pc_regnum == regnum) {1415 uint32_t return_address_regnum = LLDB_INVALID_REGNUM;1416 1417 // Get the return address register number from the UnwindPlan1418 // or the register set definition.1419 if (m_full_unwind_plan_sp->GetReturnAddressRegister() !=1420 LLDB_INVALID_REGNUM) {1421 return_address_regnum =1422 m_full_unwind_plan_sp->GetReturnAddressRegister();1423 } else {1424 RegisterNumber arch_default_ra_regnum(m_thread, eRegisterKindGeneric,1425 LLDB_REGNUM_GENERIC_RA);1426 return_address_regnum = arch_default_ra_regnum.GetAsKind(kind);1427 }1428 1429 // This system is using a return address register.1430 if (return_address_regnum != LLDB_INVALID_REGNUM) {1431 RegisterNumber return_address_reg;1432 return_address_reg.init(m_thread,1433 m_full_unwind_plan_sp->GetRegisterKind(),1434 return_address_regnum);1435 UnwindLogMsg("requested caller's saved PC but this UnwindPlan uses a "1436 "RA reg; getting %s (%d) instead",1437 return_address_reg.GetName(),1438 return_address_reg.GetAsKind(eRegisterKindLLDB));1439 1440 // Do we have a location for the ra register?1441 if (active_row &&1442 active_row->GetRegisterInfo(return_address_reg.GetAsKind(kind),1443 unwindplan_regloc)) {1444 UnwindLogMsg("supplying caller's saved %s (%d)'s location using "1445 "%s UnwindPlan",1446 return_address_reg.GetName(),1447 return_address_reg.GetAsKind(eRegisterKindLLDB),1448 m_full_unwind_plan_sp->GetSourceName().GetCString());1449 // If we have "ra=IsSame", rewrite to "ra=InRegister(ra)" because the1450 // calling function thinks it is fetching "pc" and if we return an1451 // IsSame register location, it will try to read pc.1452 if (unwindplan_regloc.IsSame())1453 unwindplan_regloc.SetInRegister(return_address_reg.GetAsKind(kind));1454 return unwindplan_regloc;1455 } else {1456 // No unwind rule for the return address reg on frame 0, or an1457 // interrupted function, means that the caller's address is still in1458 // RA reg (0th frame) or the trap handler below this one (sigtramp1459 // etc) has a save location for the RA reg.1460 if (BehavesLikeZerothFrame()) {1461 unwindplan_regloc.SetInRegister(return_address_reg.GetAsKind(kind));1462 return unwindplan_regloc;1463 }1464 }1465 }1466 }1467 }1468 1469 ExecutionContext exe_ctx(m_thread.shared_from_this());1470 Process *process = exe_ctx.GetProcessPtr();1471 1472 // Third, try finding a register location via the ABI1473 // FallbackRegisterLocation.1474 //1475 // If the UnwindPlan failed to give us an unwind location for this1476 // register, we may be able to fall back to some ABI-defined default. For1477 // example, some ABIs allow to determine the caller's SP via the CFA. Also,1478 // the ABI willset volatile registers to the undefined state.1479 ABI *abi = process ? process->GetABI().get() : nullptr;1480 if (abi) {1481 const RegisterInfo *reg_info =1482 GetRegisterInfoAtIndex(regnum.GetAsKind(eRegisterKindLLDB));1483 if (reg_info &&1484 abi->GetFallbackRegisterLocation(reg_info, unwindplan_regloc)) {1485 if (!unwindplan_regloc.IsUndefined())1486 UnwindLogMsg(1487 "supplying caller's saved %s (%d)'s location using ABI default",1488 regnum.GetName(), regnum.GetAsKind(eRegisterKindLLDB));1489 // ABI defined volatile registers with no register location1490 // will be returned as IsUndefined, stopping the search down1491 // the stack.1492 return unwindplan_regloc;1493 }1494 }1495 1496 // We have no AbstractRegisterLocation, and the ABI says this is a1497 // non-volatile / callee-preserved register. Continue down the stack1498 // or to frame 0 & the live RegisterContext.1499 std::string unwindplan_name;1500 if (m_full_unwind_plan_sp) {1501 unwindplan_name += "via '";1502 unwindplan_name += m_full_unwind_plan_sp->GetSourceName().AsCString();1503 unwindplan_name += "'";1504 }1505 UnwindLogMsg("no save location for %s (%d) %s", regnum.GetName(),1506 regnum.GetAsKind(eRegisterKindLLDB), unwindplan_name.c_str());1507 1508 unwindplan_regloc.SetSame();1509 return unwindplan_regloc;1510}1511 1512// Answer the question: Where did THIS frame save the CALLER frame ("previous"1513// frame)'s register value?1514 1515enum UnwindLLDB::RegisterSearchResult1516RegisterContextUnwind::SavedLocationForRegister(1517 uint32_t lldb_regnum,1518 lldb_private::UnwindLLDB::ConcreteRegisterLocation ®loc) {1519 RegisterNumber regnum(m_thread, eRegisterKindLLDB, lldb_regnum);1520 Log *log = GetLog(LLDBLog::Unwind);1521 1522 // Have we already found this register location?1523 if (!m_registers.empty()) {1524 auto iterator = m_registers.find(regnum.GetAsKind(eRegisterKindLLDB));1525 if (iterator != m_registers.end()) {1526 regloc = iterator->second;1527 UnwindLogMsg("supplying caller's saved %s (%d)'s location, cached",1528 regnum.GetName(), regnum.GetAsKind(eRegisterKindLLDB));1529 return UnwindLLDB::RegisterSearchResult::eRegisterFound;1530 }1531 }1532 1533 RegisterKind abs_regkind;1534 std::optional<UnwindPlan::Row::AbstractRegisterLocation> abs_regloc =1535 GetAbstractRegisterLocation(lldb_regnum, abs_regkind);1536 1537 if (!abs_regloc)1538 return UnwindLLDB::RegisterSearchResult::eRegisterNotFound;1539 1540 if (abs_regloc->IsUndefined()) {1541 UnwindLogMsg(1542 "did not supply reg location for %s (%d) because it is volatile",1543 regnum.GetName(), regnum.GetAsKind(eRegisterKindLLDB));1544 return UnwindLLDB::RegisterSearchResult::eRegisterIsVolatile;1545 }1546 1547 ExecutionContext exe_ctx(m_thread.shared_from_this());1548 Process *process = exe_ctx.GetProcessPtr();1549 // abs_regloc has valid contents about where to retrieve the register1550 if (abs_regloc->IsUnspecified()) {1551 lldb_private::UnwindLLDB::ConcreteRegisterLocation new_regloc = {};1552 new_regloc.type = UnwindLLDB::ConcreteRegisterLocation::eRegisterNotSaved;1553 m_registers[regnum.GetAsKind(eRegisterKindLLDB)] = new_regloc;1554 UnwindLogMsg("save location for %s (%d) is unspecified, continue searching",1555 regnum.GetName(), regnum.GetAsKind(eRegisterKindLLDB));1556 return UnwindLLDB::RegisterSearchResult::eRegisterNotFound;1557 }1558 1559 if (abs_regloc->IsSame()) {1560 if (IsFrameZero()) {1561 regloc.type =1562 UnwindLLDB::ConcreteRegisterLocation::eRegisterInLiveRegisterContext;1563 regloc.location.register_number = regnum.GetAsKind(eRegisterKindLLDB);1564 m_registers[regnum.GetAsKind(eRegisterKindLLDB)] = regloc;1565 UnwindLogMsg("supplying caller's register %s (%d) from the live "1566 "RegisterContext at frame 0",1567 regnum.GetName(), regnum.GetAsKind(eRegisterKindLLDB));1568 return UnwindLLDB::RegisterSearchResult::eRegisterFound;1569 }1570 // PC/RA reg don't follow the usual "callee-saved aka non-volatile" versus1571 // "caller saved aka volatile" system. A stack frame can provide its caller1572 // return address, but if we don't find a rule for pc/RA mid-stack, we1573 // never want to iterate further down the stack looking for it.1574 // Defensively prevent iterating down the stack for these two.1575 if (!BehavesLikeZerothFrame() &&1576 (regnum.GetAsKind(eRegisterKindGeneric) == LLDB_REGNUM_GENERIC_PC ||1577 regnum.GetAsKind(eRegisterKindGeneric) == LLDB_REGNUM_GENERIC_RA)) {1578 UnwindLogMsg("register %s (%d) is marked as 'IsSame' - it is a pc or "1579 "return address reg on a frame which does not have all "1580 "registers available -- treat as if we have no information",1581 regnum.GetName(), regnum.GetAsKind(eRegisterKindLLDB));1582 return UnwindLLDB::RegisterSearchResult::eRegisterNotFound;1583 }1584 1585 regloc.type = UnwindLLDB::ConcreteRegisterLocation::eRegisterInRegister;1586 regloc.location.register_number = regnum.GetAsKind(eRegisterKindLLDB);1587 m_registers[regnum.GetAsKind(eRegisterKindLLDB)] = regloc;1588 UnwindLogMsg(1589 "supplying caller's register %s (%d) value is unmodified in this frame",1590 regnum.GetName(), regnum.GetAsKind(eRegisterKindLLDB));1591 return UnwindLLDB::RegisterSearchResult::eRegisterFound;1592 }1593 1594 if (abs_regloc->IsCFAPlusOffset()) {1595 int offset = abs_regloc->GetOffset();1596 regloc.type = UnwindLLDB::ConcreteRegisterLocation::eRegisterValueInferred;1597 regloc.location.inferred_value = m_cfa + offset;1598 m_registers[regnum.GetAsKind(eRegisterKindLLDB)] = regloc;1599 UnwindLogMsg("supplying caller's register %s (%d), value is CFA plus "1600 "offset %d [value is 0x%" PRIx64 "]",1601 regnum.GetName(), regnum.GetAsKind(eRegisterKindLLDB), offset,1602 regloc.location.inferred_value);1603 return UnwindLLDB::RegisterSearchResult::eRegisterFound;1604 }1605 1606 if (abs_regloc->IsAtCFAPlusOffset()) {1607 int offset = abs_regloc->GetOffset();1608 regloc.type =1609 UnwindLLDB::ConcreteRegisterLocation::eRegisterSavedAtMemoryLocation;1610 regloc.location.target_memory_location = m_cfa + offset;1611 m_registers[regnum.GetAsKind(eRegisterKindLLDB)] = regloc;1612 UnwindLogMsg("supplying caller's register %s (%d) from the stack, saved at "1613 "CFA plus offset %d [saved at 0x%" PRIx64 "]",1614 regnum.GetName(), regnum.GetAsKind(eRegisterKindLLDB), offset,1615 regloc.location.target_memory_location);1616 return UnwindLLDB::RegisterSearchResult::eRegisterFound;1617 }1618 1619 if (abs_regloc->IsAFAPlusOffset()) {1620 if (m_afa == LLDB_INVALID_ADDRESS)1621 return UnwindLLDB::RegisterSearchResult::eRegisterNotFound;1622 1623 int offset = abs_regloc->GetOffset();1624 regloc.type = UnwindLLDB::ConcreteRegisterLocation::eRegisterValueInferred;1625 regloc.location.inferred_value = m_afa + offset;1626 m_registers[regnum.GetAsKind(eRegisterKindLLDB)] = regloc;1627 UnwindLogMsg("supplying caller's register %s (%d), value is AFA plus "1628 "offset %d [value is 0x%" PRIx64 "]",1629 regnum.GetName(), regnum.GetAsKind(eRegisterKindLLDB), offset,1630 regloc.location.inferred_value);1631 return UnwindLLDB::RegisterSearchResult::eRegisterFound;1632 }1633 1634 if (abs_regloc->IsAtAFAPlusOffset()) {1635 if (m_afa == LLDB_INVALID_ADDRESS)1636 return UnwindLLDB::RegisterSearchResult::eRegisterNotFound;1637 1638 int offset = abs_regloc->GetOffset();1639 regloc.type =1640 UnwindLLDB::ConcreteRegisterLocation::eRegisterSavedAtMemoryLocation;1641 regloc.location.target_memory_location = m_afa + offset;1642 m_registers[regnum.GetAsKind(eRegisterKindLLDB)] = regloc;1643 UnwindLogMsg("supplying caller's register %s (%d) from the stack, saved at "1644 "AFA plus offset %d [saved at 0x%" PRIx64 "]",1645 regnum.GetName(), regnum.GetAsKind(eRegisterKindLLDB), offset,1646 regloc.location.target_memory_location);1647 return UnwindLLDB::RegisterSearchResult::eRegisterFound;1648 }1649 1650 if (abs_regloc->IsInOtherRegister()) {1651 RegisterNumber row_regnum(m_thread, abs_regkind,1652 abs_regloc->GetRegisterNumber());1653 if (row_regnum.GetAsKind(eRegisterKindLLDB) == LLDB_INVALID_REGNUM) {1654 UnwindLogMsg("could not supply caller's %s (%d) location - was saved in "1655 "another reg but couldn't convert that regnum",1656 regnum.GetName(), regnum.GetAsKind(eRegisterKindLLDB));1657 return UnwindLLDB::RegisterSearchResult::eRegisterNotFound;1658 }1659 regloc.type = UnwindLLDB::ConcreteRegisterLocation::eRegisterInRegister;1660 regloc.location.register_number = row_regnum.GetAsKind(eRegisterKindLLDB);1661 m_registers[regnum.GetAsKind(eRegisterKindLLDB)] = regloc;1662 UnwindLogMsg(1663 "supplying caller's register %s (%d), saved in register %s (%d)",1664 regnum.GetName(), regnum.GetAsKind(eRegisterKindLLDB),1665 row_regnum.GetName(), row_regnum.GetAsKind(eRegisterKindLLDB));1666 return UnwindLLDB::RegisterSearchResult::eRegisterFound;1667 }1668 1669 if (abs_regloc->IsDWARFExpression() || abs_regloc->IsAtDWARFExpression()) {1670 DataExtractor dwarfdata(abs_regloc->GetDWARFExpressionBytes(),1671 abs_regloc->GetDWARFExpressionLength(),1672 process->GetByteOrder(),1673 process->GetAddressByteSize());1674 ModuleSP opcode_ctx;1675 DWARFExpressionList dwarfexpr(opcode_ctx, dwarfdata, nullptr);1676 dwarfexpr.GetMutableExpressionAtAddress()->SetRegisterKind(abs_regkind);1677 Value cfa_val = Scalar(m_cfa);1678 cfa_val.SetValueType(Value::ValueType::LoadAddress);1679 llvm::Expected<Value> result =1680 dwarfexpr.Evaluate(&exe_ctx, this, 0, &cfa_val, nullptr);1681 if (!result) {1682 LLDB_LOG_ERROR(log, result.takeError(),1683 "DWARF expression failed to evaluate: {0}");1684 } else {1685 addr_t val;1686 val = result->GetScalar().ULongLong();1687 if (abs_regloc->IsDWARFExpression()) {1688 regloc.type =1689 UnwindLLDB::ConcreteRegisterLocation::eRegisterValueInferred;1690 regloc.location.inferred_value = val;1691 m_registers[regnum.GetAsKind(eRegisterKindLLDB)] = regloc;1692 UnwindLogMsg("supplying caller's register %s (%d) via DWARF expression "1693 "(IsDWARFExpression)",1694 regnum.GetName(), regnum.GetAsKind(eRegisterKindLLDB));1695 return UnwindLLDB::RegisterSearchResult::eRegisterFound;1696 } else {1697 regloc.type = UnwindLLDB::ConcreteRegisterLocation::1698 eRegisterSavedAtMemoryLocation;1699 regloc.location.target_memory_location = val;1700 m_registers[regnum.GetAsKind(eRegisterKindLLDB)] = regloc;1701 UnwindLogMsg("supplying caller's register %s (%d) via DWARF expression "1702 "(IsAtDWARFExpression)",1703 regnum.GetName(), regnum.GetAsKind(eRegisterKindLLDB));1704 return UnwindLLDB::RegisterSearchResult::eRegisterFound;1705 }1706 }1707 UnwindLogMsg("tried to use IsDWARFExpression or IsAtDWARFExpression for %s "1708 "(%d) but failed",1709 regnum.GetName(), regnum.GetAsKind(eRegisterKindLLDB));1710 return UnwindLLDB::RegisterSearchResult::eRegisterNotFound;1711 }1712 1713 if (abs_regloc->IsConstant()) {1714 regloc.type = UnwindLLDB::ConcreteRegisterLocation::eRegisterValueInferred;1715 regloc.location.inferred_value = abs_regloc->GetConstant();1716 m_registers[regnum.GetAsKind(eRegisterKindLLDB)] = regloc;1717 UnwindLogMsg("supplying caller's register %s (%d) via constant value",1718 regnum.GetName(), regnum.GetAsKind(eRegisterKindLLDB));1719 return UnwindLLDB::RegisterSearchResult::eRegisterFound;1720 }1721 1722 UnwindLogMsg("no save location for %s (%d) in this stack frame",1723 regnum.GetName(), regnum.GetAsKind(eRegisterKindLLDB));1724 1725 // FIXME UnwindPlan::Row types atDWARFExpression and isDWARFExpression are1726 // unsupported.1727 1728 return UnwindLLDB::RegisterSearchResult::eRegisterNotFound;1729}1730 1731UnwindPlanSP RegisterContextUnwind::TryAdoptArchitectureUnwindPlan() {1732 if (!m_full_unwind_plan_sp)1733 return {};1734 ProcessSP process_sp = m_thread.GetProcess();1735 if (!process_sp)1736 return {};1737 1738 UnwindPlanSP arch_override_plan_sp;1739 if (Architecture *arch = process_sp->GetTarget().GetArchitecturePlugin())1740 arch_override_plan_sp =1741 arch->GetArchitectureUnwindPlan(m_thread, this, m_full_unwind_plan_sp);1742 1743 if (arch_override_plan_sp) {1744 m_full_unwind_plan_sp = arch_override_plan_sp;1745 PropagateTrapHandlerFlagFromUnwindPlan(m_full_unwind_plan_sp);1746 m_registers.clear();1747 if (GetLog(LLDBLog::Unwind)) {1748 UnwindLogMsg(1749 "Replacing Full Unwindplan with Architecture UnwindPlan, '%s'",1750 m_full_unwind_plan_sp->GetSourceName().AsCString());1751 const UnwindPlan::Row *active_row =1752 m_full_unwind_plan_sp->GetRowForFunctionOffset(m_current_offset);1753 if (active_row) {1754 StreamString active_row_strm;1755 active_row->Dump(active_row_strm, m_full_unwind_plan_sp.get(),1756 &m_thread,1757 m_start_pc.GetLoadAddress(&process_sp->GetTarget()));1758 UnwindLogMsg("%s", active_row_strm.GetData());1759 }1760 }1761 }1762 1763 return {};1764}1765 1766// TryFallbackUnwindPlan() -- this method is a little tricky.1767//1768// When this is called, the frame above -- the caller frame, the "previous"1769// frame -- is invalid or bad.1770//1771// Instead of stopping the stack walk here, we'll try a different UnwindPlan1772// and see if we can get a valid frame above us.1773//1774// This most often happens when an unwind plan based on assembly instruction1775// inspection is not correct -- mostly with hand-written assembly functions or1776// functions where the stack frame is set up "out of band", e.g. the kernel1777// saved the register context and then called an asynchronous trap handler like1778// _sigtramp.1779//1780// Often in these cases, if we just do a dumb stack walk we'll get past this1781// tricky frame and our usual techniques can continue to be used.1782 1783bool RegisterContextUnwind::TryFallbackUnwindPlan() {1784 if (m_fallback_unwind_plan_sp == nullptr)1785 return false;1786 1787 if (m_full_unwind_plan_sp == nullptr)1788 return false;1789 1790 if (m_full_unwind_plan_sp.get() == m_fallback_unwind_plan_sp.get() ||1791 m_full_unwind_plan_sp->GetSourceName() ==1792 m_fallback_unwind_plan_sp->GetSourceName()) {1793 return false;1794 }1795 1796 // If a compiler generated unwind plan failed, trying the arch default1797 // unwindplan isn't going to do any better.1798 if (m_full_unwind_plan_sp->GetSourcedFromCompiler() == eLazyBoolYes)1799 return false;1800 1801 // Get the caller's pc value and our own CFA value. Swap in the fallback1802 // unwind plan, re-fetch the caller's pc value and CFA value. If they're the1803 // same, then the fallback unwind plan provides no benefit.1804 1805 RegisterNumber pc_regnum(m_thread, eRegisterKindGeneric,1806 LLDB_REGNUM_GENERIC_PC);1807 1808 addr_t old_caller_pc_value = LLDB_INVALID_ADDRESS;1809 addr_t new_caller_pc_value = LLDB_INVALID_ADDRESS;1810 UnwindLLDB::ConcreteRegisterLocation regloc = {};1811 if (SavedLocationForRegister(pc_regnum.GetAsKind(eRegisterKindLLDB),1812 regloc) ==1813 UnwindLLDB::RegisterSearchResult::eRegisterFound) {1814 const RegisterInfo *reg_info =1815 GetRegisterInfoAtIndex(pc_regnum.GetAsKind(eRegisterKindLLDB));1816 if (reg_info) {1817 RegisterValue reg_value;1818 if (ReadRegisterValueFromRegisterLocation(regloc, reg_info, reg_value)) {1819 old_caller_pc_value = reg_value.GetAsUInt64();1820 if (ProcessSP process_sp = m_thread.GetProcess()) {1821 if (ABISP abi_sp = process_sp->GetABI())1822 old_caller_pc_value = abi_sp->FixCodeAddress(old_caller_pc_value);1823 }1824 }1825 }1826 }1827 1828 // This is a tricky wrinkle! If SavedLocationForRegister() detects a really1829 // impossible register location for the full unwind plan, it may call1830 // ForceSwitchToFallbackUnwindPlan() which in turn replaces the full1831 // unwindplan with the fallback... in short, we're done, we're using the1832 // fallback UnwindPlan. We checked if m_fallback_unwind_plan_sp was nullptr1833 // at the top -- the only way it became nullptr since then is via1834 // SavedLocationForRegister().1835 if (m_fallback_unwind_plan_sp == nullptr)1836 return true;1837 1838 // Switch the full UnwindPlan to be the fallback UnwindPlan. If we decide1839 // this isn't working, we need to restore. We'll also need to save & restore1840 // the value of the m_cfa ivar. Save is down below a bit in 'old_cfa'.1841 std::shared_ptr<const UnwindPlan> original_full_unwind_plan_sp =1842 m_full_unwind_plan_sp;1843 addr_t old_cfa = m_cfa;1844 addr_t old_afa = m_afa;1845 1846 m_registers.clear();1847 1848 m_full_unwind_plan_sp = m_fallback_unwind_plan_sp;1849 1850 const UnwindPlan::Row *active_row =1851 m_fallback_unwind_plan_sp->GetRowForFunctionOffset(1852 m_current_offset_backed_up_one);1853 1854 if (active_row &&1855 active_row->GetCFAValue().GetValueType() !=1856 UnwindPlan::Row::FAValue::unspecified) {1857 addr_t new_cfa;1858 ProcessSP process_sp = m_thread.GetProcess();1859 ABISP abi_sp = process_sp ? process_sp->GetABI() : nullptr;1860 if (!ReadFrameAddress(m_fallback_unwind_plan_sp->GetRegisterKind(),1861 active_row->GetCFAValue(), new_cfa) ||1862 !CallFrameAddressIsValid(abi_sp, new_cfa)) {1863 UnwindLogMsg("failed to get cfa with fallback unwindplan");1864 m_fallback_unwind_plan_sp.reset();1865 m_full_unwind_plan_sp = original_full_unwind_plan_sp;1866 return false;1867 }1868 m_cfa = new_cfa;1869 1870 ReadFrameAddress(m_fallback_unwind_plan_sp->GetRegisterKind(),1871 active_row->GetAFAValue(), m_afa);1872 1873 if (SavedLocationForRegister(pc_regnum.GetAsKind(eRegisterKindLLDB),1874 regloc) ==1875 UnwindLLDB::RegisterSearchResult::eRegisterFound) {1876 const RegisterInfo *reg_info =1877 GetRegisterInfoAtIndex(pc_regnum.GetAsKind(eRegisterKindLLDB));1878 if (reg_info) {1879 RegisterValue reg_value;1880 if (ReadRegisterValueFromRegisterLocation(regloc, reg_info,1881 reg_value)) {1882 new_caller_pc_value = reg_value.GetAsUInt64();1883 if (process_sp)1884 new_caller_pc_value =1885 process_sp->FixCodeAddress(new_caller_pc_value);1886 }1887 }1888 }1889 1890 if (new_caller_pc_value == LLDB_INVALID_ADDRESS) {1891 UnwindLogMsg("failed to get a pc value for the caller frame with the "1892 "fallback unwind plan");1893 m_fallback_unwind_plan_sp.reset();1894 m_full_unwind_plan_sp = original_full_unwind_plan_sp;1895 m_cfa = old_cfa;1896 m_afa = old_afa;1897 return false;1898 }1899 1900 if (old_caller_pc_value == new_caller_pc_value &&1901 m_cfa == old_cfa &&1902 m_afa == old_afa) {1903 UnwindLogMsg("fallback unwind plan got the same values for this frame "1904 "CFA and caller frame pc, not using");1905 m_fallback_unwind_plan_sp.reset();1906 m_full_unwind_plan_sp = original_full_unwind_plan_sp;1907 return false;1908 }1909 1910 UnwindLogMsg("trying to unwind from this function with the UnwindPlan '%s' "1911 "because UnwindPlan '%s' failed.",1912 m_fallback_unwind_plan_sp->GetSourceName().GetCString(),1913 original_full_unwind_plan_sp->GetSourceName().GetCString());1914 1915 // We've copied the fallback unwind plan into the full - now clear the1916 // fallback.1917 m_fallback_unwind_plan_sp.reset();1918 PropagateTrapHandlerFlagFromUnwindPlan(m_full_unwind_plan_sp);1919 }1920 1921 return true;1922}1923 1924bool RegisterContextUnwind::ForceSwitchToFallbackUnwindPlan() {1925 if (m_fallback_unwind_plan_sp == nullptr)1926 return false;1927 1928 if (m_full_unwind_plan_sp == nullptr)1929 return false;1930 1931 if (m_full_unwind_plan_sp.get() == m_fallback_unwind_plan_sp.get() ||1932 m_full_unwind_plan_sp->GetSourceName() ==1933 m_fallback_unwind_plan_sp->GetSourceName()) {1934 return false;1935 }1936 1937 const UnwindPlan::Row *active_row =1938 m_fallback_unwind_plan_sp->GetRowForFunctionOffset(m_current_offset);1939 1940 if (active_row &&1941 active_row->GetCFAValue().GetValueType() !=1942 UnwindPlan::Row::FAValue::unspecified) {1943 addr_t new_cfa;1944 ProcessSP process_sp = m_thread.GetProcess();1945 ABISP abi_sp = process_sp ? process_sp->GetABI() : nullptr;1946 if (!ReadFrameAddress(m_fallback_unwind_plan_sp->GetRegisterKind(),1947 active_row->GetCFAValue(), new_cfa) ||1948 !CallFrameAddressIsValid(abi_sp, new_cfa)) {1949 UnwindLogMsg("failed to get cfa with fallback unwindplan");1950 m_fallback_unwind_plan_sp.reset();1951 return false;1952 }1953 1954 ReadFrameAddress(m_fallback_unwind_plan_sp->GetRegisterKind(),1955 active_row->GetAFAValue(), m_afa);1956 1957 m_full_unwind_plan_sp = m_fallback_unwind_plan_sp;1958 m_fallback_unwind_plan_sp.reset();1959 1960 m_registers.clear();1961 1962 m_cfa = new_cfa;1963 1964 PropagateTrapHandlerFlagFromUnwindPlan(m_full_unwind_plan_sp);1965 1966 UnwindLogMsg("switched unconditionally to the fallback unwindplan %s",1967 m_full_unwind_plan_sp->GetSourceName().GetCString());1968 return true;1969 }1970 return false;1971}1972 1973void RegisterContextUnwind::PropagateTrapHandlerFlagFromUnwindPlan(1974 std::shared_ptr<const UnwindPlan> unwind_plan) {1975 if (unwind_plan->GetUnwindPlanForSignalTrap() != eLazyBoolYes) {1976 // Unwind plan does not indicate trap handler. Do nothing. We may1977 // already be flagged as trap handler flag due to the symbol being1978 // in the trap handler symbol list, and that should take precedence.1979 return;1980 } else if (m_frame_type != eNormalFrame) {1981 // If this is already a trap handler frame, nothing to do.1982 // If this is a skip or debug or invalid frame, don't override that.1983 return;1984 }1985 1986 m_frame_type = eTrapHandlerFrame;1987 UnwindLogMsg("This frame is marked as a trap handler via its UnwindPlan");1988 1989 if (m_current_offset_backed_up_one != m_current_offset) {1990 // We backed up the pc by 1 to compute the symbol context, but1991 // now need to undo that because the pc of the trap handler1992 // frame may in fact be the first instruction of a signal return1993 // trampoline, rather than the instruction after a call. This1994 // happens on systems where the signal handler dispatch code, rather1995 // than calling the handler and being returned to, jumps to the1996 // handler after pushing the address of a return trampoline on the1997 // stack -- on these systems, when the handler returns, control will1998 // be transferred to the return trampoline, so that's the best1999 // symbol we can present in the callstack.2000 UnwindLogMsg("Resetting current offset and re-doing symbol lookup; "2001 "old symbol was %s",2002 GetSymbolOrFunctionName(m_sym_ctx).AsCString(""));2003 m_current_offset_backed_up_one = m_current_offset;2004 2005 m_sym_ctx_valid = m_current_pc.ResolveFunctionScope(m_sym_ctx);2006 2007 UnwindLogMsg("Symbol is now %s",2008 GetSymbolOrFunctionName(m_sym_ctx).AsCString(""));2009 2010 ExecutionContext exe_ctx(m_thread.shared_from_this());2011 Process *process = exe_ctx.GetProcessPtr();2012 Target *target = &process->GetTarget();2013 2014 if (m_sym_ctx_valid) {2015 m_start_pc = m_sym_ctx.GetFunctionOrSymbolAddress();2016 m_current_offset = m_current_pc.GetLoadAddress(target) -2017 m_start_pc.GetLoadAddress(target);2018 }2019 }2020}2021 2022bool RegisterContextUnwind::ReadFrameAddress(2023 lldb::RegisterKind row_register_kind, const UnwindPlan::Row::FAValue &fa,2024 addr_t &address) {2025 RegisterValue reg_value;2026 2027 address = LLDB_INVALID_ADDRESS;2028 addr_t cfa_reg_contents;2029 ABISP abi_sp = m_thread.GetProcess()->GetABI();2030 2031 switch (fa.GetValueType()) {2032 case UnwindPlan::Row::FAValue::isRegisterDereferenced: {2033 UnwindLogMsg("CFA value via dereferencing reg");2034 RegisterNumber regnum_to_deref(m_thread, row_register_kind,2035 fa.GetRegisterNumber());2036 addr_t reg_to_deref_contents;2037 if (ReadGPRValue(regnum_to_deref, reg_to_deref_contents)) {2038 const RegisterInfo *reg_info =2039 GetRegisterInfoAtIndex(regnum_to_deref.GetAsKind(eRegisterKindLLDB));2040 RegisterValue reg_value;2041 if (reg_info) {2042 Status error = ReadRegisterValueFromMemory(2043 reg_info, reg_to_deref_contents, reg_info->byte_size, reg_value);2044 if (error.Success()) {2045 address = reg_value.GetAsUInt64();2046 UnwindLogMsg(2047 "CFA value via dereferencing reg %s (%d): reg has val 0x%" PRIx642048 ", CFA value is 0x%" PRIx64,2049 regnum_to_deref.GetName(),2050 regnum_to_deref.GetAsKind(eRegisterKindLLDB),2051 reg_to_deref_contents, address);2052 return true;2053 } else {2054 UnwindLogMsg("Tried to deref reg %s (%d) [0x%" PRIx642055 "] but memory read failed.",2056 regnum_to_deref.GetName(),2057 regnum_to_deref.GetAsKind(eRegisterKindLLDB),2058 reg_to_deref_contents);2059 }2060 }2061 }2062 break;2063 }2064 case UnwindPlan::Row::FAValue::isRegisterPlusOffset: {2065 UnwindLogMsg("CFA value via register plus offset");2066 RegisterNumber cfa_reg(m_thread, row_register_kind,2067 fa.GetRegisterNumber());2068 if (ReadGPRValue(cfa_reg, cfa_reg_contents)) {2069 if (!CallFrameAddressIsValid(abi_sp, cfa_reg_contents)) {2070 UnwindLogMsg(2071 "Got an invalid CFA register value - reg %s (%d), value 0x%" PRIx64,2072 cfa_reg.GetName(), cfa_reg.GetAsKind(eRegisterKindLLDB),2073 cfa_reg_contents);2074 return false;2075 }2076 address = cfa_reg_contents + fa.GetOffset();2077 UnwindLogMsg(2078 "CFA is 0x%" PRIx64 ": Register %s (%d) contents are 0x%" PRIx642079 ", offset is %d",2080 address, cfa_reg.GetName(), cfa_reg.GetAsKind(eRegisterKindLLDB),2081 cfa_reg_contents, fa.GetOffset());2082 return true;2083 } else2084 UnwindLogMsg("unable to read CFA register %s (%d)", cfa_reg.GetName(),2085 cfa_reg.GetAsKind(eRegisterKindLLDB));2086 break;2087 }2088 case UnwindPlan::Row::FAValue::isDWARFExpression: {2089 UnwindLogMsg("CFA value via DWARF expression");2090 ExecutionContext exe_ctx(m_thread.shared_from_this());2091 Process *process = exe_ctx.GetProcessPtr();2092 DataExtractor dwarfdata(fa.GetDWARFExpressionBytes(),2093 fa.GetDWARFExpressionLength(),2094 process->GetByteOrder(),2095 process->GetAddressByteSize());2096 ModuleSP opcode_ctx;2097 DWARFExpressionList dwarfexpr(opcode_ctx, dwarfdata, nullptr);2098 dwarfexpr.GetMutableExpressionAtAddress()->SetRegisterKind(2099 row_register_kind);2100 llvm::Expected<Value> result =2101 dwarfexpr.Evaluate(&exe_ctx, this, 0, nullptr, nullptr);2102 if (result) {2103 address = result->GetScalar().ULongLong();2104 UnwindLogMsg("CFA value set by DWARF expression is 0x%" PRIx64,2105 address);2106 return true;2107 }2108 UnwindLogMsg("Failed to set CFA value via DWARF expression: %s",2109 llvm::toString(result.takeError()).c_str());2110 break;2111 }2112 case UnwindPlan::Row::FAValue::isRaSearch: {2113 UnwindLogMsg("CFA value via heuristic search");2114 Process &process = *m_thread.GetProcess();2115 lldb::addr_t return_address_hint = GetReturnAddressHint(fa.GetOffset());2116 if (return_address_hint == LLDB_INVALID_ADDRESS)2117 return false;2118 const unsigned max_iterations = 256;2119 for (unsigned i = 0; i < max_iterations; ++i) {2120 Status st;2121 lldb::addr_t candidate_addr =2122 return_address_hint + i * process.GetAddressByteSize();2123 lldb::addr_t candidate =2124 process.ReadPointerFromMemory(candidate_addr, st);2125 if (st.Fail()) {2126 UnwindLogMsg("Cannot read memory at 0x%" PRIx64 ": %s", candidate_addr,2127 st.AsCString());2128 return false;2129 }2130 Address addr;2131 uint32_t permissions;2132 if (process.GetLoadAddressPermissions(candidate, permissions) &&2133 permissions & lldb::ePermissionsExecutable) {2134 address = candidate_addr;2135 UnwindLogMsg("Heuristically found CFA: 0x%" PRIx64, address);2136 return true;2137 }2138 }2139 UnwindLogMsg("No suitable CFA found");2140 break;2141 }2142 case UnwindPlan::Row::FAValue::isConstant: {2143 address = fa.GetConstant();2144 UnwindLogMsg("CFA value set by constant is 0x%" PRIx64, address);2145 return true;2146 }2147 default:2148 return false;2149 }2150 return false;2151}2152 2153lldb::addr_t RegisterContextUnwind::GetReturnAddressHint(int32_t plan_offset) {2154 addr_t hint;2155 if (!ReadGPRValue(eRegisterKindGeneric, LLDB_REGNUM_GENERIC_SP, hint))2156 return LLDB_INVALID_ADDRESS;2157 if (!m_sym_ctx.module_sp || !m_sym_ctx.symbol)2158 return LLDB_INVALID_ADDRESS;2159 if (ABISP abi_sp = m_thread.GetProcess()->GetABI())2160 hint = abi_sp->FixCodeAddress(hint);2161 2162 hint += plan_offset;2163 2164 if (auto next = GetNextFrame()) {2165 if (!next->m_sym_ctx.module_sp || !next->m_sym_ctx.symbol)2166 return LLDB_INVALID_ADDRESS;2167 if (auto expected_size =2168 next->m_sym_ctx.module_sp->GetSymbolFile()->GetParameterStackSize(2169 *next->m_sym_ctx.symbol))2170 hint += *expected_size;2171 else {2172 UnwindLogMsgVerbose("Could not retrieve parameter size: %s",2173 llvm::toString(expected_size.takeError()).c_str());2174 return LLDB_INVALID_ADDRESS;2175 }2176 }2177 return hint;2178}2179 2180// Retrieve a general purpose register value for THIS frame, as saved by the2181// NEXT frame, i.e. the frame that2182// this frame called. e.g.2183//2184// foo () { }2185// bar () { foo (); }2186// main () { bar (); }2187//2188// stopped in foo() so2189// frame 0 - foo2190// frame 1 - bar2191// frame 2 - main2192// and this RegisterContext is for frame 1 (bar) - if we want to get the pc2193// value for frame 1, we need to ask2194// where frame 0 (the "next" frame) saved that and retrieve the value.2195 2196bool RegisterContextUnwind::ReadGPRValue(lldb::RegisterKind register_kind,2197 uint32_t regnum, addr_t &value) {2198 if (!IsValid())2199 return false;2200 2201 uint32_t lldb_regnum;2202 if (register_kind == eRegisterKindLLDB) {2203 lldb_regnum = regnum;2204 } else if (!m_thread.GetRegisterContext()->ConvertBetweenRegisterKinds(2205 register_kind, regnum, eRegisterKindLLDB, lldb_regnum)) {2206 return false;2207 }2208 2209 const RegisterInfo *reg_info = GetRegisterInfoAtIndex(lldb_regnum);2210 assert(reg_info);2211 if (!reg_info) {2212 UnwindLogMsg(2213 "Could not find RegisterInfo definition for lldb register number %d",2214 lldb_regnum);2215 return false;2216 }2217 2218 uint32_t generic_regnum = LLDB_INVALID_REGNUM;2219 if (register_kind == eRegisterKindGeneric)2220 generic_regnum = regnum;2221 else2222 m_thread.GetRegisterContext()->ConvertBetweenRegisterKinds(2223 register_kind, regnum, eRegisterKindGeneric, generic_regnum);2224 ABISP abi_sp = m_thread.GetProcess()->GetABI();2225 2226 RegisterValue reg_value;2227 // if this is frame 0 (currently executing frame), get the requested reg2228 // contents from the actual thread registers2229 if (IsFrameZero()) {2230 if (m_thread.GetRegisterContext()->ReadRegister(reg_info, reg_value)) {2231 value = reg_value.GetAsUInt64();2232 if (abi_sp && generic_regnum != LLDB_INVALID_REGNUM) {2233 if (generic_regnum == LLDB_REGNUM_GENERIC_PC ||2234 generic_regnum == LLDB_REGNUM_GENERIC_RA)2235 value = abi_sp->FixCodeAddress(value);2236 }2237 return true;2238 }2239 return false;2240 }2241 2242 bool pc_register = false;2243 if (generic_regnum != LLDB_INVALID_REGNUM &&2244 (generic_regnum == LLDB_REGNUM_GENERIC_PC ||2245 generic_regnum == LLDB_REGNUM_GENERIC_RA))2246 pc_register = true;2247 2248 lldb_private::UnwindLLDB::ConcreteRegisterLocation regloc;2249 if (!m_parent_unwind.SearchForSavedLocationForRegister(2250 lldb_regnum, regloc, m_frame_number - 1, pc_register)) {2251 return false;2252 }2253 if (ReadRegisterValueFromRegisterLocation(regloc, reg_info, reg_value)) {2254 value = reg_value.GetAsUInt64();2255 if (pc_register) {2256 if (ABISP abi_sp = m_thread.GetProcess()->GetABI()) {2257 value = abi_sp->FixCodeAddress(value);2258 }2259 }2260 return true;2261 }2262 return false;2263}2264 2265bool RegisterContextUnwind::ReadGPRValue(const RegisterNumber ®num,2266 addr_t &value) {2267 return ReadGPRValue(regnum.GetRegisterKind(), regnum.GetRegisterNumber(),2268 value);2269}2270 2271// Find the value of a register in THIS frame2272 2273bool RegisterContextUnwind::ReadRegister(const RegisterInfo *reg_info,2274 RegisterValue &value) {2275 if (!IsValid())2276 return false;2277 2278 const uint32_t lldb_regnum = reg_info->kinds[eRegisterKindLLDB];2279 UnwindLogMsgVerbose("looking for register saved location for reg %d",2280 lldb_regnum);2281 2282 // If this is the 0th frame, hand this over to the live register context2283 if (IsFrameZero()) {2284 UnwindLogMsgVerbose("passing along to the live register context for reg %d",2285 lldb_regnum);2286 return m_thread.GetRegisterContext()->ReadRegister(reg_info, value);2287 }2288 2289 bool is_pc_regnum = false;2290 if (reg_info->kinds[eRegisterKindGeneric] == LLDB_REGNUM_GENERIC_PC ||2291 reg_info->kinds[eRegisterKindGeneric] == LLDB_REGNUM_GENERIC_RA) {2292 is_pc_regnum = true;2293 }2294 2295 lldb_private::UnwindLLDB::ConcreteRegisterLocation regloc;2296 // Find out where the NEXT frame saved THIS frame's register contents2297 if (!m_parent_unwind.SearchForSavedLocationForRegister(2298 lldb_regnum, regloc, m_frame_number - 1, is_pc_regnum))2299 return false;2300 2301 bool result = ReadRegisterValueFromRegisterLocation(regloc, reg_info, value);2302 if (result) {2303 if (is_pc_regnum && value.GetType() == RegisterValue::eTypeUInt64) {2304 addr_t reg_value = value.GetAsUInt64(LLDB_INVALID_ADDRESS);2305 if (reg_value != LLDB_INVALID_ADDRESS) {2306 if (ABISP abi_sp = m_thread.GetProcess()->GetABI())2307 value = abi_sp->FixCodeAddress(reg_value);2308 }2309 }2310 }2311 return result;2312}2313 2314bool RegisterContextUnwind::WriteRegister(const RegisterInfo *reg_info,2315 const RegisterValue &value) {2316 if (!IsValid())2317 return false;2318 2319 const uint32_t lldb_regnum = reg_info->kinds[eRegisterKindLLDB];2320 UnwindLogMsgVerbose("looking for register saved location for reg %d",2321 lldb_regnum);2322 2323 // If this is the 0th frame, hand this over to the live register context2324 if (IsFrameZero()) {2325 UnwindLogMsgVerbose("passing along to the live register context for reg %d",2326 lldb_regnum);2327 return m_thread.GetRegisterContext()->WriteRegister(reg_info, value);2328 }2329 2330 lldb_private::UnwindLLDB::ConcreteRegisterLocation regloc;2331 // Find out where the NEXT frame saved THIS frame's register contents2332 if (!m_parent_unwind.SearchForSavedLocationForRegister(2333 lldb_regnum, regloc, m_frame_number - 1, false))2334 return false;2335 2336 return WriteRegisterValueToRegisterLocation(regloc, reg_info, value);2337}2338 2339// Don't need to implement this one2340bool RegisterContextUnwind::ReadAllRegisterValues(2341 lldb::WritableDataBufferSP &data_sp) {2342 return false;2343}2344 2345// Don't need to implement this one2346bool RegisterContextUnwind::WriteAllRegisterValues(2347 const lldb::DataBufferSP &data_sp) {2348 return false;2349}2350 2351// Retrieve the pc value for THIS from2352 2353bool RegisterContextUnwind::GetCFA(addr_t &cfa) {2354 if (!IsValid()) {2355 return false;2356 }2357 if (m_cfa == LLDB_INVALID_ADDRESS) {2358 return false;2359 }2360 cfa = m_cfa;2361 return true;2362}2363 2364RegisterContextUnwind::SharedPtr RegisterContextUnwind::GetNextFrame() const {2365 RegisterContextUnwind::SharedPtr regctx;2366 if (m_frame_number == 0)2367 return regctx;2368 return m_parent_unwind.GetRegisterContextForFrameNum(m_frame_number - 1);2369}2370 2371RegisterContextUnwind::SharedPtr RegisterContextUnwind::GetPrevFrame() const {2372 RegisterContextUnwind::SharedPtr regctx;2373 return m_parent_unwind.GetRegisterContextForFrameNum(m_frame_number + 1);2374}2375 2376// Retrieve the address of the start of the function of THIS frame2377 2378bool RegisterContextUnwind::GetStartPC(addr_t &start_pc) {2379 if (!IsValid())2380 return false;2381 2382 if (!m_start_pc.IsValid()) {2383 bool read_successfully = ReadPC (start_pc);2384 if (read_successfully)2385 {2386 ProcessSP process_sp (m_thread.GetProcess());2387 if (process_sp)2388 {2389 if (ABISP abi_sp = process_sp->GetABI())2390 start_pc = abi_sp->FixCodeAddress(start_pc);2391 }2392 }2393 return read_successfully;2394 }2395 start_pc = m_start_pc.GetLoadAddress(CalculateTarget().get());2396 return true;2397}2398 2399// Retrieve the current pc value for THIS frame, as saved by the NEXT frame.2400 2401bool RegisterContextUnwind::ReadPC(addr_t &pc) {2402 if (!IsValid())2403 return false;2404 2405 bool above_trap_handler = false;2406 if (GetNextFrame().get() && GetNextFrame()->IsValid() &&2407 GetNextFrame()->IsTrapHandlerFrame())2408 above_trap_handler = true;2409 2410 if (ReadGPRValue(eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC, pc)) {2411 // A pc value of 0 or 1 is impossible in the middle of the stack -- it2412 // indicates the end of a stack walk.2413 // On the currently executing frame (or such a frame interrupted2414 // asynchronously by sigtramp et al) this may occur if code has jumped2415 // through a NULL pointer -- we want to be able to unwind past that frame2416 // to help find the bug.2417 2418 if (ABISP abi_sp = m_thread.GetProcess()->GetABI())2419 pc = abi_sp->FixCodeAddress(pc);2420 2421 return !(m_all_registers_available == false &&2422 above_trap_handler == false && (pc == 0 || pc == 1));2423 } else {2424 return false;2425 }2426}2427 2428void RegisterContextUnwind::UnwindLogMsg(const char *fmt, ...) {2429 Log *log = GetLog(LLDBLog::Unwind);2430 if (!log)2431 return;2432 2433 va_list args;2434 va_start(args, fmt);2435 2436 llvm::SmallString<0> logmsg;2437 if (VASprintf(logmsg, fmt, args)) {2438 LLDB_LOGF(log, "%*sth%d/fr%u %s",2439 m_frame_number < 100 ? m_frame_number : 100, "",2440 m_thread.GetIndexID(), m_frame_number, logmsg.c_str());2441 }2442 va_end(args);2443}2444 2445void RegisterContextUnwind::UnwindLogMsgVerbose(const char *fmt, ...) {2446 Log *log = GetLog(LLDBLog::Unwind);2447 if (!log || !log->GetVerbose())2448 return;2449 2450 va_list args;2451 va_start(args, fmt);2452 2453 llvm::SmallString<0> logmsg;2454 if (VASprintf(logmsg, fmt, args)) {2455 LLDB_LOGF(log, "%*sth%d/fr%u %s",2456 m_frame_number < 100 ? m_frame_number : 100, "",2457 m_thread.GetIndexID(), m_frame_number, logmsg.c_str());2458 }2459 va_end(args);2460}2461