diff options
Diffstat (limited to 'contrib/llvm-project/lldb/source/Plugins/UnwindAssembly')
6 files changed, 2968 insertions, 0 deletions
diff --git a/contrib/llvm-project/lldb/source/Plugins/UnwindAssembly/InstEmulation/UnwindAssemblyInstEmulation.cpp b/contrib/llvm-project/lldb/source/Plugins/UnwindAssembly/InstEmulation/UnwindAssemblyInstEmulation.cpp new file mode 100644 index 000000000000..49edd40544e3 --- /dev/null +++ b/contrib/llvm-project/lldb/source/Plugins/UnwindAssembly/InstEmulation/UnwindAssemblyInstEmulation.cpp @@ -0,0 +1,693 @@ +//===-- UnwindAssemblyInstEmulation.cpp -----------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include "UnwindAssemblyInstEmulation.h" + +#include "lldb/Core/Address.h" +#include "lldb/Core/Disassembler.h" +#include "lldb/Core/DumpDataExtractor.h" +#include "lldb/Core/DumpRegisterValue.h" +#include "lldb/Core/FormatEntity.h" +#include "lldb/Core/PluginManager.h" +#include "lldb/Target/ExecutionContext.h" +#include "lldb/Target/Process.h" +#include "lldb/Target/Target.h" +#include "lldb/Target/Thread.h" +#include "lldb/Utility/ArchSpec.h" +#include "lldb/Utility/DataBufferHeap.h" +#include "lldb/Utility/DataExtractor.h" +#include "lldb/Utility/LLDBLog.h" +#include "lldb/Utility/Log.h" +#include "lldb/Utility/Status.h" +#include "lldb/Utility/StreamString.h" + +using namespace lldb; +using namespace lldb_private; + +LLDB_PLUGIN_DEFINE(UnwindAssemblyInstEmulation) + +// UnwindAssemblyInstEmulation method definitions + +bool UnwindAssemblyInstEmulation::GetNonCallSiteUnwindPlanFromAssembly( + AddressRange &range, Thread &thread, UnwindPlan &unwind_plan) { + std::vector<uint8_t> function_text(range.GetByteSize()); + ProcessSP process_sp(thread.GetProcess()); + if (process_sp) { + Status error; + const bool force_live_memory = true; + if (process_sp->GetTarget().ReadMemory( + range.GetBaseAddress(), function_text.data(), range.GetByteSize(), + error, force_live_memory) != range.GetByteSize()) { + return false; + } + } + return GetNonCallSiteUnwindPlanFromAssembly( + range, function_text.data(), function_text.size(), unwind_plan); +} + +bool UnwindAssemblyInstEmulation::GetNonCallSiteUnwindPlanFromAssembly( + AddressRange &range, uint8_t *opcode_data, size_t opcode_size, + UnwindPlan &unwind_plan) { + if (opcode_data == nullptr || opcode_size == 0) + return false; + + if (range.GetByteSize() > 0 && range.GetBaseAddress().IsValid() && + m_inst_emulator_up.get()) { + + // The instruction emulation subclass setup the unwind plan for the first + // instruction. + m_inst_emulator_up->CreateFunctionEntryUnwind(unwind_plan); + + // CreateFunctionEntryUnwind should have created the first row. If it + // doesn't, then we are done. + if (unwind_plan.GetRowCount() == 0) + return false; + + const bool prefer_file_cache = true; + DisassemblerSP disasm_sp(Disassembler::DisassembleBytes( + m_arch, nullptr, nullptr, range.GetBaseAddress(), opcode_data, + opcode_size, 99999, prefer_file_cache)); + + Log *log = GetLog(LLDBLog::Unwind); + + if (disasm_sp) { + + m_range_ptr = ⦥ + m_unwind_plan_ptr = &unwind_plan; + + const uint32_t addr_byte_size = m_arch.GetAddressByteSize(); + const bool show_address = true; + const bool show_bytes = true; + const bool show_control_flow_kind = false; + m_cfa_reg_info = *m_inst_emulator_up->GetRegisterInfo( + unwind_plan.GetRegisterKind(), unwind_plan.GetInitialCFARegister()); + m_fp_is_cfa = false; + m_register_values.clear(); + m_pushed_regs.clear(); + + // Initialize the CFA with a known value. In the 32 bit case it will be + // 0x80000000, and in the 64 bit case 0x8000000000000000. We use the + // address byte size to be safe for any future address sizes + m_initial_sp = (1ull << ((addr_byte_size * 8) - 1)); + RegisterValue cfa_reg_value; + cfa_reg_value.SetUInt(m_initial_sp, m_cfa_reg_info.byte_size); + SetRegisterValue(m_cfa_reg_info, cfa_reg_value); + + const InstructionList &inst_list = disasm_sp->GetInstructionList(); + const size_t num_instructions = inst_list.GetSize(); + + if (num_instructions > 0) { + Instruction *inst = inst_list.GetInstructionAtIndex(0).get(); + const lldb::addr_t base_addr = inst->GetAddress().GetFileAddress(); + + // Map for storing the unwind plan row and the value of the registers + // at a given offset. When we see a forward branch we add a new entry + // to this map with the actual unwind plan row and register context for + // the target address of the branch as the current data have to be + // valid for the target address of the branch too if we are in the same + // function. + std::map<lldb::addr_t, std::pair<UnwindPlan::RowSP, RegisterValueMap>> + saved_unwind_states; + + // Make a copy of the current instruction Row and save it in m_curr_row + // so we can add updates as we process the instructions. + UnwindPlan::RowSP last_row = unwind_plan.GetLastRow(); + UnwindPlan::Row *newrow = new UnwindPlan::Row; + if (last_row.get()) + *newrow = *last_row.get(); + m_curr_row.reset(newrow); + + // Add the initial state to the save list with offset 0. + saved_unwind_states.insert({0, {last_row, m_register_values}}); + + // cache the stack pointer register number (in whatever register + // numbering this UnwindPlan uses) for quick reference during + // instruction parsing. + RegisterInfo sp_reg_info = *m_inst_emulator_up->GetRegisterInfo( + eRegisterKindGeneric, LLDB_REGNUM_GENERIC_SP); + + // The architecture dependent condition code of the last processed + // instruction. + EmulateInstruction::InstructionCondition last_condition = + EmulateInstruction::UnconditionalCondition; + lldb::addr_t condition_block_start_offset = 0; + + for (size_t idx = 0; idx < num_instructions; ++idx) { + m_curr_row_modified = false; + m_forward_branch_offset = 0; + + inst = inst_list.GetInstructionAtIndex(idx).get(); + if (inst) { + lldb::addr_t current_offset = + inst->GetAddress().GetFileAddress() - base_addr; + auto it = saved_unwind_states.upper_bound(current_offset); + assert(it != saved_unwind_states.begin() && + "Unwind row for the function entry missing"); + --it; // Move it to the row corresponding to the current offset + + // If the offset of m_curr_row don't match with the offset we see + // in saved_unwind_states then we have to update m_curr_row and + // m_register_values based on the saved values. It is happening + // after we processed an epilogue and a return to caller + // instruction. + if (it->second.first->GetOffset() != m_curr_row->GetOffset()) { + UnwindPlan::Row *newrow = new UnwindPlan::Row; + *newrow = *it->second.first; + m_curr_row.reset(newrow); + m_register_values = it->second.second; + // re-set the CFA register ivars to match the + // new m_curr_row. + if (sp_reg_info.name && + m_curr_row->GetCFAValue().IsRegisterPlusOffset()) { + uint32_t row_cfa_regnum = + m_curr_row->GetCFAValue().GetRegisterNumber(); + lldb::RegisterKind row_kind = + m_unwind_plan_ptr->GetRegisterKind(); + // set m_cfa_reg_info to the row's CFA reg. + m_cfa_reg_info = *m_inst_emulator_up->GetRegisterInfo( + row_kind, row_cfa_regnum); + // set m_fp_is_cfa. + if (sp_reg_info.kinds[row_kind] == row_cfa_regnum) + m_fp_is_cfa = false; + else + m_fp_is_cfa = true; + } + } + + m_inst_emulator_up->SetInstruction(inst->GetOpcode(), + inst->GetAddress(), nullptr); + + if (last_condition != + m_inst_emulator_up->GetInstructionCondition()) { + if (m_inst_emulator_up->GetInstructionCondition() != + EmulateInstruction::UnconditionalCondition && + saved_unwind_states.count(current_offset) == 0) { + // If we don't have a saved row for the current offset then + // save our current state because we will have to restore it + // after the conditional block. + auto new_row = + std::make_shared<UnwindPlan::Row>(*m_curr_row.get()); + saved_unwind_states.insert( + {current_offset, {new_row, m_register_values}}); + } + + // If the last instruction was conditional with a different + // condition then the then current condition then restore the + // condition. + if (last_condition != + EmulateInstruction::UnconditionalCondition) { + const auto &saved_state = + saved_unwind_states.at(condition_block_start_offset); + m_curr_row = + std::make_shared<UnwindPlan::Row>(*saved_state.first); + m_curr_row->SetOffset(current_offset); + m_register_values = saved_state.second; + // re-set the CFA register ivars to match the + // new m_curr_row. + if (sp_reg_info.name && + m_curr_row->GetCFAValue().IsRegisterPlusOffset()) { + uint32_t row_cfa_regnum = + m_curr_row->GetCFAValue().GetRegisterNumber(); + lldb::RegisterKind row_kind = + m_unwind_plan_ptr->GetRegisterKind(); + // set m_cfa_reg_info to the row's CFA reg. + m_cfa_reg_info = *m_inst_emulator_up->GetRegisterInfo( + row_kind, row_cfa_regnum); + // set m_fp_is_cfa. + if (sp_reg_info.kinds[row_kind] == row_cfa_regnum) + m_fp_is_cfa = false; + else + m_fp_is_cfa = true; + } + bool replace_existing = + true; // The last instruction might already + // created a row for this offset and + // we want to overwrite it. + unwind_plan.InsertRow( + std::make_shared<UnwindPlan::Row>(*m_curr_row), + replace_existing); + } + + // We are starting a new conditional block at the actual offset + condition_block_start_offset = current_offset; + } + + if (log && log->GetVerbose()) { + StreamString strm; + lldb_private::FormatEntity::Entry format; + FormatEntity::Parse("${frame.pc}: ", format); + inst->Dump(&strm, inst_list.GetMaxOpcocdeByteSize(), show_address, + show_bytes, show_control_flow_kind, nullptr, nullptr, + nullptr, &format, 0); + log->PutString(strm.GetString()); + } + + last_condition = m_inst_emulator_up->GetInstructionCondition(); + + m_inst_emulator_up->EvaluateInstruction( + eEmulateInstructionOptionIgnoreConditions); + + // If the current instruction is a branch forward then save the + // current CFI information for the offset where we are branching. + if (m_forward_branch_offset != 0 && + range.ContainsFileAddress(inst->GetAddress().GetFileAddress() + + m_forward_branch_offset)) { + auto newrow = + std::make_shared<UnwindPlan::Row>(*m_curr_row.get()); + newrow->SetOffset(current_offset + m_forward_branch_offset); + saved_unwind_states.insert( + {current_offset + m_forward_branch_offset, + {newrow, m_register_values}}); + unwind_plan.InsertRow(newrow); + } + + // Were there any changes to the CFI while evaluating this + // instruction? + if (m_curr_row_modified) { + // Save the modified row if we don't already have a CFI row in + // the current address + if (saved_unwind_states.count( + current_offset + inst->GetOpcode().GetByteSize()) == 0) { + m_curr_row->SetOffset(current_offset + + inst->GetOpcode().GetByteSize()); + unwind_plan.InsertRow(m_curr_row); + saved_unwind_states.insert( + {current_offset + inst->GetOpcode().GetByteSize(), + {m_curr_row, m_register_values}}); + + // Allocate a new Row for m_curr_row, copy the current state + // into it + UnwindPlan::Row *newrow = new UnwindPlan::Row; + *newrow = *m_curr_row.get(); + m_curr_row.reset(newrow); + } + } + } + } + } + } + + if (log && log->GetVerbose()) { + StreamString strm; + lldb::addr_t base_addr = range.GetBaseAddress().GetFileAddress(); + strm.Printf("Resulting unwind rows for [0x%" PRIx64 " - 0x%" PRIx64 "):", + base_addr, base_addr + range.GetByteSize()); + unwind_plan.Dump(strm, nullptr, base_addr); + log->PutString(strm.GetString()); + } + return unwind_plan.GetRowCount() > 0; + } + return false; +} + +bool UnwindAssemblyInstEmulation::AugmentUnwindPlanFromCallSite( + AddressRange &func, Thread &thread, UnwindPlan &unwind_plan) { + return false; +} + +bool UnwindAssemblyInstEmulation::GetFastUnwindPlan(AddressRange &func, + Thread &thread, + UnwindPlan &unwind_plan) { + return false; +} + +bool UnwindAssemblyInstEmulation::FirstNonPrologueInsn( + AddressRange &func, const ExecutionContext &exe_ctx, + Address &first_non_prologue_insn) { + return false; +} + +UnwindAssembly * +UnwindAssemblyInstEmulation::CreateInstance(const ArchSpec &arch) { + std::unique_ptr<EmulateInstruction> inst_emulator_up( + EmulateInstruction::FindPlugin(arch, eInstructionTypePrologueEpilogue, + nullptr)); + // Make sure that all prologue instructions are handled + if (inst_emulator_up) + return new UnwindAssemblyInstEmulation(arch, inst_emulator_up.release()); + return nullptr; +} + +void UnwindAssemblyInstEmulation::Initialize() { + PluginManager::RegisterPlugin(GetPluginNameStatic(), + GetPluginDescriptionStatic(), CreateInstance); +} + +void UnwindAssemblyInstEmulation::Terminate() { + PluginManager::UnregisterPlugin(CreateInstance); +} + +llvm::StringRef UnwindAssemblyInstEmulation::GetPluginDescriptionStatic() { + return "Instruction emulation based unwind information."; +} + +uint64_t UnwindAssemblyInstEmulation::MakeRegisterKindValuePair( + const RegisterInfo ®_info) { + lldb::RegisterKind reg_kind; + uint32_t reg_num; + if (EmulateInstruction::GetBestRegisterKindAndNumber(®_info, reg_kind, + reg_num)) + return (uint64_t)reg_kind << 24 | reg_num; + return 0ull; +} + +void UnwindAssemblyInstEmulation::SetRegisterValue( + const RegisterInfo ®_info, const RegisterValue ®_value) { + m_register_values[MakeRegisterKindValuePair(reg_info)] = reg_value; +} + +bool UnwindAssemblyInstEmulation::GetRegisterValue(const RegisterInfo ®_info, + RegisterValue ®_value) { + const uint64_t reg_id = MakeRegisterKindValuePair(reg_info); + RegisterValueMap::const_iterator pos = m_register_values.find(reg_id); + if (pos != m_register_values.end()) { + reg_value = pos->second; + return true; // We had a real value that comes from an opcode that wrote + // to it... + } + // We are making up a value that is recognizable... + reg_value.SetUInt(reg_id, reg_info.byte_size); + return false; +} + +size_t UnwindAssemblyInstEmulation::ReadMemory( + EmulateInstruction *instruction, void *baton, + const EmulateInstruction::Context &context, lldb::addr_t addr, void *dst, + size_t dst_len) { + Log *log = GetLog(LLDBLog::Unwind); + + if (log && log->GetVerbose()) { + StreamString strm; + strm.Printf( + "UnwindAssemblyInstEmulation::ReadMemory (addr = 0x%16.16" PRIx64 + ", dst = %p, dst_len = %" PRIu64 ", context = ", + addr, dst, (uint64_t)dst_len); + context.Dump(strm, instruction); + log->PutString(strm.GetString()); + } + memset(dst, 0, dst_len); + return dst_len; +} + +size_t UnwindAssemblyInstEmulation::WriteMemory( + EmulateInstruction *instruction, void *baton, + const EmulateInstruction::Context &context, lldb::addr_t addr, + const void *dst, size_t dst_len) { + if (baton && dst && dst_len) + return ((UnwindAssemblyInstEmulation *)baton) + ->WriteMemory(instruction, context, addr, dst, dst_len); + return 0; +} + +size_t UnwindAssemblyInstEmulation::WriteMemory( + EmulateInstruction *instruction, const EmulateInstruction::Context &context, + lldb::addr_t addr, const void *dst, size_t dst_len) { + DataExtractor data(dst, dst_len, + instruction->GetArchitecture().GetByteOrder(), + instruction->GetArchitecture().GetAddressByteSize()); + + Log *log = GetLog(LLDBLog::Unwind); + + if (log && log->GetVerbose()) { + StreamString strm; + + strm.PutCString("UnwindAssemblyInstEmulation::WriteMemory ("); + DumpDataExtractor(data, &strm, 0, eFormatBytes, 1, dst_len, UINT32_MAX, + addr, 0, 0); + strm.PutCString(", context = "); + context.Dump(strm, instruction); + log->PutString(strm.GetString()); + } + + switch (context.type) { + default: + case EmulateInstruction::eContextInvalid: + case EmulateInstruction::eContextReadOpcode: + case EmulateInstruction::eContextImmediate: + case EmulateInstruction::eContextAdjustBaseRegister: + case EmulateInstruction::eContextRegisterPlusOffset: + case EmulateInstruction::eContextAdjustPC: + case EmulateInstruction::eContextRegisterStore: + case EmulateInstruction::eContextRegisterLoad: + case EmulateInstruction::eContextRelativeBranchImmediate: + case EmulateInstruction::eContextAbsoluteBranchRegister: + case EmulateInstruction::eContextSupervisorCall: + case EmulateInstruction::eContextTableBranchReadMemory: + case EmulateInstruction::eContextWriteRegisterRandomBits: + case EmulateInstruction::eContextWriteMemoryRandomBits: + case EmulateInstruction::eContextArithmetic: + case EmulateInstruction::eContextAdvancePC: + case EmulateInstruction::eContextReturnFromException: + case EmulateInstruction::eContextPopRegisterOffStack: + case EmulateInstruction::eContextAdjustStackPointer: + break; + + case EmulateInstruction::eContextPushRegisterOnStack: { + uint32_t reg_num = LLDB_INVALID_REGNUM; + uint32_t generic_regnum = LLDB_INVALID_REGNUM; + assert(context.GetInfoType() == + EmulateInstruction::eInfoTypeRegisterToRegisterPlusOffset && + "unhandled case, add code to handle this!"); + const uint32_t unwind_reg_kind = m_unwind_plan_ptr->GetRegisterKind(); + reg_num = context.info.RegisterToRegisterPlusOffset.data_reg + .kinds[unwind_reg_kind]; + generic_regnum = context.info.RegisterToRegisterPlusOffset.data_reg + .kinds[eRegisterKindGeneric]; + + if (reg_num != LLDB_INVALID_REGNUM && + generic_regnum != LLDB_REGNUM_GENERIC_SP) { + if (m_pushed_regs.find(reg_num) == m_pushed_regs.end()) { + m_pushed_regs[reg_num] = addr; + const int32_t offset = addr - m_initial_sp; + m_curr_row->SetRegisterLocationToAtCFAPlusOffset(reg_num, offset, + /*can_replace=*/true); + m_curr_row_modified = true; + } + } + } break; + } + + return dst_len; +} + +bool UnwindAssemblyInstEmulation::ReadRegister(EmulateInstruction *instruction, + void *baton, + const RegisterInfo *reg_info, + RegisterValue ®_value) { + + if (baton && reg_info) + return ((UnwindAssemblyInstEmulation *)baton) + ->ReadRegister(instruction, reg_info, reg_value); + return false; +} +bool UnwindAssemblyInstEmulation::ReadRegister(EmulateInstruction *instruction, + const RegisterInfo *reg_info, + RegisterValue ®_value) { + bool synthetic = GetRegisterValue(*reg_info, reg_value); + + Log *log = GetLog(LLDBLog::Unwind); + + if (log && log->GetVerbose()) { + + StreamString strm; + strm.Printf("UnwindAssemblyInstEmulation::ReadRegister (name = \"%s\") => " + "synthetic_value = %i, value = ", + reg_info->name, synthetic); + DumpRegisterValue(reg_value, strm, *reg_info, false, false, eFormatDefault); + log->PutString(strm.GetString()); + } + return true; +} + +bool UnwindAssemblyInstEmulation::WriteRegister( + EmulateInstruction *instruction, void *baton, + const EmulateInstruction::Context &context, const RegisterInfo *reg_info, + const RegisterValue ®_value) { + if (baton && reg_info) + return ((UnwindAssemblyInstEmulation *)baton) + ->WriteRegister(instruction, context, reg_info, reg_value); + return false; +} +bool UnwindAssemblyInstEmulation::WriteRegister( + EmulateInstruction *instruction, const EmulateInstruction::Context &context, + const RegisterInfo *reg_info, const RegisterValue ®_value) { + Log *log = GetLog(LLDBLog::Unwind); + + if (log && log->GetVerbose()) { + + StreamString strm; + strm.Printf( + "UnwindAssemblyInstEmulation::WriteRegister (name = \"%s\", value = ", + reg_info->name); + DumpRegisterValue(reg_value, strm, *reg_info, false, false, eFormatDefault); + strm.PutCString(", context = "); + context.Dump(strm, instruction); + log->PutString(strm.GetString()); + } + + SetRegisterValue(*reg_info, reg_value); + + switch (context.type) { + case EmulateInstruction::eContextInvalid: + case EmulateInstruction::eContextReadOpcode: + case EmulateInstruction::eContextImmediate: + case EmulateInstruction::eContextAdjustBaseRegister: + case EmulateInstruction::eContextRegisterPlusOffset: + case EmulateInstruction::eContextAdjustPC: + case EmulateInstruction::eContextRegisterStore: + case EmulateInstruction::eContextSupervisorCall: + case EmulateInstruction::eContextTableBranchReadMemory: + case EmulateInstruction::eContextWriteRegisterRandomBits: + case EmulateInstruction::eContextWriteMemoryRandomBits: + case EmulateInstruction::eContextAdvancePC: + case EmulateInstruction::eContextReturnFromException: + case EmulateInstruction::eContextPushRegisterOnStack: + case EmulateInstruction::eContextRegisterLoad: + // { + // const uint32_t reg_num = + // reg_info->kinds[m_unwind_plan_ptr->GetRegisterKind()]; + // if (reg_num != LLDB_INVALID_REGNUM) + // { + // const bool can_replace_only_if_unspecified = true; + // + // m_curr_row.SetRegisterLocationToUndefined (reg_num, + // can_replace_only_if_unspecified, + // can_replace_only_if_unspecified); + // m_curr_row_modified = true; + // } + // } + break; + + case EmulateInstruction::eContextArithmetic: { + // If we adjusted the current frame pointer by a constant then adjust the + // CFA offset + // with the same amount. + lldb::RegisterKind kind = m_unwind_plan_ptr->GetRegisterKind(); + if (m_fp_is_cfa && reg_info->kinds[kind] == m_cfa_reg_info.kinds[kind] && + context.GetInfoType() == + EmulateInstruction::eInfoTypeRegisterPlusOffset && + context.info.RegisterPlusOffset.reg.kinds[kind] == + m_cfa_reg_info.kinds[kind]) { + const int64_t offset = context.info.RegisterPlusOffset.signed_offset; + m_curr_row->GetCFAValue().IncOffset(-1 * offset); + m_curr_row_modified = true; + } + } break; + + case EmulateInstruction::eContextAbsoluteBranchRegister: + case EmulateInstruction::eContextRelativeBranchImmediate: { + if (context.GetInfoType() == EmulateInstruction::eInfoTypeISAAndImmediate && + context.info.ISAAndImmediate.unsigned_data32 > 0) { + m_forward_branch_offset = + context.info.ISAAndImmediateSigned.signed_data32; + } else if (context.GetInfoType() == + EmulateInstruction::eInfoTypeISAAndImmediateSigned && + context.info.ISAAndImmediateSigned.signed_data32 > 0) { + m_forward_branch_offset = context.info.ISAAndImmediate.unsigned_data32; + } else if (context.GetInfoType() == + EmulateInstruction::eInfoTypeImmediate && + context.info.unsigned_immediate > 0) { + m_forward_branch_offset = context.info.unsigned_immediate; + } else if (context.GetInfoType() == + EmulateInstruction::eInfoTypeImmediateSigned && + context.info.signed_immediate > 0) { + m_forward_branch_offset = context.info.signed_immediate; + } + } break; + + case EmulateInstruction::eContextPopRegisterOffStack: { + const uint32_t reg_num = + reg_info->kinds[m_unwind_plan_ptr->GetRegisterKind()]; + const uint32_t generic_regnum = reg_info->kinds[eRegisterKindGeneric]; + if (reg_num != LLDB_INVALID_REGNUM && + generic_regnum != LLDB_REGNUM_GENERIC_SP) { + switch (context.GetInfoType()) { + case EmulateInstruction::eInfoTypeAddress: + if (m_pushed_regs.find(reg_num) != m_pushed_regs.end() && + context.info.address == m_pushed_regs[reg_num]) { + m_curr_row->SetRegisterLocationToSame(reg_num, + false /*must_replace*/); + m_curr_row_modified = true; + + // FP has been restored to its original value, we are back + // to using SP to calculate the CFA. + if (m_fp_is_cfa) { + m_fp_is_cfa = false; + lldb::RegisterKind sp_reg_kind = eRegisterKindGeneric; + uint32_t sp_reg_num = LLDB_REGNUM_GENERIC_SP; + RegisterInfo sp_reg_info = + *m_inst_emulator_up->GetRegisterInfo(sp_reg_kind, sp_reg_num); + RegisterValue sp_reg_val; + if (GetRegisterValue(sp_reg_info, sp_reg_val)) { + m_cfa_reg_info = sp_reg_info; + const uint32_t cfa_reg_num = + sp_reg_info.kinds[m_unwind_plan_ptr->GetRegisterKind()]; + assert(cfa_reg_num != LLDB_INVALID_REGNUM); + m_curr_row->GetCFAValue().SetIsRegisterPlusOffset( + cfa_reg_num, m_initial_sp - sp_reg_val.GetAsUInt64()); + } + } + } + break; + case EmulateInstruction::eInfoTypeISA: + assert( + (generic_regnum == LLDB_REGNUM_GENERIC_PC || + generic_regnum == LLDB_REGNUM_GENERIC_FLAGS) && + "eInfoTypeISA used for popping a register other the PC/FLAGS"); + if (generic_regnum != LLDB_REGNUM_GENERIC_FLAGS) { + m_curr_row->SetRegisterLocationToSame(reg_num, + false /*must_replace*/); + m_curr_row_modified = true; + } + break; + default: + assert(false && "unhandled case, add code to handle this!"); + break; + } + } + } break; + + case EmulateInstruction::eContextSetFramePointer: + if (!m_fp_is_cfa) { + m_fp_is_cfa = true; + m_cfa_reg_info = *reg_info; + const uint32_t cfa_reg_num = + reg_info->kinds[m_unwind_plan_ptr->GetRegisterKind()]; + assert(cfa_reg_num != LLDB_INVALID_REGNUM); + m_curr_row->GetCFAValue().SetIsRegisterPlusOffset( + cfa_reg_num, m_initial_sp - reg_value.GetAsUInt64()); + m_curr_row_modified = true; + } + break; + + case EmulateInstruction::eContextRestoreStackPointer: + if (m_fp_is_cfa) { + m_fp_is_cfa = false; + m_cfa_reg_info = *reg_info; + const uint32_t cfa_reg_num = + reg_info->kinds[m_unwind_plan_ptr->GetRegisterKind()]; + assert(cfa_reg_num != LLDB_INVALID_REGNUM); + m_curr_row->GetCFAValue().SetIsRegisterPlusOffset( + cfa_reg_num, m_initial_sp - reg_value.GetAsUInt64()); + m_curr_row_modified = true; + } + break; + + case EmulateInstruction::eContextAdjustStackPointer: + // If we have created a frame using the frame pointer, don't follow + // subsequent adjustments to the stack pointer. + if (!m_fp_is_cfa) { + m_curr_row->GetCFAValue().SetIsRegisterPlusOffset( + m_curr_row->GetCFAValue().GetRegisterNumber(), + m_initial_sp - reg_value.GetAsUInt64()); + m_curr_row_modified = true; + } + break; + } + return true; +} diff --git a/contrib/llvm-project/lldb/source/Plugins/UnwindAssembly/InstEmulation/UnwindAssemblyInstEmulation.h b/contrib/llvm-project/lldb/source/Plugins/UnwindAssembly/InstEmulation/UnwindAssemblyInstEmulation.h new file mode 100644 index 000000000000..d03a8ce4e924 --- /dev/null +++ b/contrib/llvm-project/lldb/source/Plugins/UnwindAssembly/InstEmulation/UnwindAssemblyInstEmulation.h @@ -0,0 +1,152 @@ +//===-- UnwindAssemblyInstEmulation.h ---------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#ifndef LLDB_SOURCE_PLUGINS_UNWINDASSEMBLY_INSTEMULATION_UNWINDASSEMBLYINSTEMULATION_H +#define LLDB_SOURCE_PLUGINS_UNWINDASSEMBLY_INSTEMULATION_UNWINDASSEMBLYINSTEMULATION_H + +#include "lldb/Core/EmulateInstruction.h" +#include "lldb/Symbol/UnwindPlan.h" +#include "lldb/Target/UnwindAssembly.h" +#include "lldb/Utility/RegisterValue.h" +#include "lldb/lldb-private.h" + +class UnwindAssemblyInstEmulation : public lldb_private::UnwindAssembly { +public: + ~UnwindAssemblyInstEmulation() override = default; + + bool GetNonCallSiteUnwindPlanFromAssembly( + lldb_private::AddressRange &func, lldb_private::Thread &thread, + lldb_private::UnwindPlan &unwind_plan) override; + + bool + GetNonCallSiteUnwindPlanFromAssembly(lldb_private::AddressRange &func, + uint8_t *opcode_data, size_t opcode_size, + lldb_private::UnwindPlan &unwind_plan); + + bool + AugmentUnwindPlanFromCallSite(lldb_private::AddressRange &func, + lldb_private::Thread &thread, + lldb_private::UnwindPlan &unwind_plan) override; + + bool GetFastUnwindPlan(lldb_private::AddressRange &func, + lldb_private::Thread &thread, + lldb_private::UnwindPlan &unwind_plan) override; + + // thread may be NULL in which case we only use the Target (e.g. if this is + // called pre-process-launch). + bool + FirstNonPrologueInsn(lldb_private::AddressRange &func, + const lldb_private::ExecutionContext &exe_ctx, + lldb_private::Address &first_non_prologue_insn) override; + + static lldb_private::UnwindAssembly * + CreateInstance(const lldb_private::ArchSpec &arch); + + // PluginInterface protocol + static void Initialize(); + + static void Terminate(); + + static llvm::StringRef GetPluginNameStatic() { return "inst-emulation"; } + + static llvm::StringRef GetPluginDescriptionStatic(); + + llvm::StringRef GetPluginName() override { return GetPluginNameStatic(); } + +private: + // Call CreateInstance to get an instance of this class + UnwindAssemblyInstEmulation(const lldb_private::ArchSpec &arch, + lldb_private::EmulateInstruction *inst_emulator) + : UnwindAssembly(arch), m_inst_emulator_up(inst_emulator), + m_range_ptr(nullptr), m_unwind_plan_ptr(nullptr), m_curr_row(), + m_initial_sp(0), m_cfa_reg_info(), m_fp_is_cfa(false), + m_register_values(), m_pushed_regs(), m_curr_row_modified(false), + m_forward_branch_offset(0) { + if (m_inst_emulator_up) { + m_inst_emulator_up->SetBaton(this); + m_inst_emulator_up->SetCallbacks(ReadMemory, WriteMemory, ReadRegister, + WriteRegister); + } + } + + static size_t + ReadMemory(lldb_private::EmulateInstruction *instruction, void *baton, + const lldb_private::EmulateInstruction::Context &context, + lldb::addr_t addr, void *dst, size_t length); + + static size_t + WriteMemory(lldb_private::EmulateInstruction *instruction, void *baton, + const lldb_private::EmulateInstruction::Context &context, + lldb::addr_t addr, const void *dst, size_t length); + + static bool ReadRegister(lldb_private::EmulateInstruction *instruction, + void *baton, + const lldb_private::RegisterInfo *reg_info, + lldb_private::RegisterValue ®_value); + + static bool + WriteRegister(lldb_private::EmulateInstruction *instruction, void *baton, + const lldb_private::EmulateInstruction::Context &context, + const lldb_private::RegisterInfo *reg_info, + const lldb_private::RegisterValue ®_value); + + // size_t + // ReadMemory (lldb_private::EmulateInstruction *instruction, + // const lldb_private::EmulateInstruction::Context &context, + // lldb::addr_t addr, + // void *dst, + // size_t length); + + size_t WriteMemory(lldb_private::EmulateInstruction *instruction, + const lldb_private::EmulateInstruction::Context &context, + lldb::addr_t addr, const void *dst, size_t length); + + bool ReadRegister(lldb_private::EmulateInstruction *instruction, + const lldb_private::RegisterInfo *reg_info, + lldb_private::RegisterValue ®_value); + + bool WriteRegister(lldb_private::EmulateInstruction *instruction, + const lldb_private::EmulateInstruction::Context &context, + const lldb_private::RegisterInfo *reg_info, + const lldb_private::RegisterValue ®_value); + + static uint64_t + MakeRegisterKindValuePair(const lldb_private::RegisterInfo ®_info); + + void SetRegisterValue(const lldb_private::RegisterInfo ®_info, + const lldb_private::RegisterValue ®_value); + + bool GetRegisterValue(const lldb_private::RegisterInfo ®_info, + lldb_private::RegisterValue ®_value); + + std::unique_ptr<lldb_private::EmulateInstruction> m_inst_emulator_up; + lldb_private::AddressRange *m_range_ptr; + lldb_private::UnwindPlan *m_unwind_plan_ptr; + lldb_private::UnwindPlan::RowSP m_curr_row; + typedef std::map<uint64_t, uint64_t> PushedRegisterToAddrMap; + uint64_t m_initial_sp; + lldb_private::RegisterInfo m_cfa_reg_info; + bool m_fp_is_cfa; + typedef std::map<uint64_t, lldb_private::RegisterValue> RegisterValueMap; + RegisterValueMap m_register_values; + PushedRegisterToAddrMap m_pushed_regs; + + // While processing the instruction stream, we need to communicate some state + // change + // information up to the higher level loop that makes decisions about how to + // push + // the unwind instructions for the UnwindPlan we're constructing. + + // The instruction we're processing updated the UnwindPlan::Row contents + bool m_curr_row_modified; + // The instruction is branching forward with the given offset. 0 value means + // no branching. + uint32_t m_forward_branch_offset; +}; + +#endif // LLDB_SOURCE_PLUGINS_UNWINDASSEMBLY_INSTEMULATION_UNWINDASSEMBLYINSTEMULATION_H diff --git a/contrib/llvm-project/lldb/source/Plugins/UnwindAssembly/x86/UnwindAssembly-x86.cpp b/contrib/llvm-project/lldb/source/Plugins/UnwindAssembly/x86/UnwindAssembly-x86.cpp new file mode 100644 index 000000000000..eca78a9b3a04 --- /dev/null +++ b/contrib/llvm-project/lldb/source/Plugins/UnwindAssembly/x86/UnwindAssembly-x86.cpp @@ -0,0 +1,253 @@ +//===-- UnwindAssembly-x86.cpp --------------------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include "UnwindAssembly-x86.h" +#include "x86AssemblyInspectionEngine.h" + +#include "llvm-c/Disassembler.h" +#include "llvm/ADT/STLExtras.h" +#include "llvm/Support/TargetSelect.h" + +#include "lldb/Core/Address.h" +#include "lldb/Core/PluginManager.h" +#include "lldb/Symbol/UnwindPlan.h" +#include "lldb/Target/ABI.h" +#include "lldb/Target/ExecutionContext.h" +#include "lldb/Target/Process.h" +#include "lldb/Target/RegisterContext.h" +#include "lldb/Target/RegisterNumber.h" +#include "lldb/Target/Target.h" +#include "lldb/Target/Thread.h" +#include "lldb/Target/UnwindAssembly.h" +#include "lldb/Utility/ArchSpec.h" +#include "lldb/Utility/Status.h" + +using namespace lldb; +using namespace lldb_private; + +LLDB_PLUGIN_DEFINE_ADV(UnwindAssembly_x86, UnwindAssemblyX86) + +// UnwindAssemblyParser_x86 method definitions + +UnwindAssembly_x86::UnwindAssembly_x86(const ArchSpec &arch) + : lldb_private::UnwindAssembly(arch), + m_assembly_inspection_engine(new x86AssemblyInspectionEngine(arch)) {} + +UnwindAssembly_x86::~UnwindAssembly_x86() { + delete m_assembly_inspection_engine; +} + +bool UnwindAssembly_x86::GetNonCallSiteUnwindPlanFromAssembly( + AddressRange &func, Thread &thread, UnwindPlan &unwind_plan) { + if (!func.GetBaseAddress().IsValid() || func.GetByteSize() == 0) + return false; + if (m_assembly_inspection_engine == nullptr) + return false; + ProcessSP process_sp(thread.GetProcess()); + if (process_sp.get() == nullptr) + return false; + std::vector<uint8_t> function_text(func.GetByteSize()); + Status error; + if (process_sp->GetTarget().ReadMemory( + func.GetBaseAddress(), function_text.data(), func.GetByteSize(), + error) == func.GetByteSize()) { + RegisterContextSP reg_ctx(thread.GetRegisterContext()); + m_assembly_inspection_engine->Initialize(reg_ctx); + return m_assembly_inspection_engine->GetNonCallSiteUnwindPlanFromAssembly( + function_text.data(), func.GetByteSize(), func, unwind_plan); + } + return false; +} + +bool UnwindAssembly_x86::AugmentUnwindPlanFromCallSite( + AddressRange &func, Thread &thread, UnwindPlan &unwind_plan) { + bool do_augment_unwindplan = true; + + UnwindPlan::RowSP first_row = unwind_plan.GetRowForFunctionOffset(0); + UnwindPlan::RowSP last_row = unwind_plan.GetRowForFunctionOffset(-1); + + int wordsize = 8; + ProcessSP process_sp(thread.GetProcess()); + if (process_sp.get() == nullptr) + return false; + + wordsize = process_sp->GetTarget().GetArchitecture().GetAddressByteSize(); + + RegisterNumber sp_regnum(thread, eRegisterKindGeneric, + LLDB_REGNUM_GENERIC_SP); + RegisterNumber pc_regnum(thread, eRegisterKindGeneric, + LLDB_REGNUM_GENERIC_PC); + + // Does this UnwindPlan describe the prologue? I want to see that the CFA is + // set in terms of the stack pointer plus an offset, and I want to see that + // rip is retrieved at the CFA-wordsize. If there is no description of the + // prologue, don't try to augment this eh_frame unwinder code, fall back to + // assembly parsing instead. + + if (first_row->GetCFAValue().GetValueType() != + UnwindPlan::Row::FAValue::isRegisterPlusOffset || + RegisterNumber(thread, unwind_plan.GetRegisterKind(), + first_row->GetCFAValue().GetRegisterNumber()) != + sp_regnum || + first_row->GetCFAValue().GetOffset() != wordsize) { + return false; + } + UnwindPlan::Row::RegisterLocation first_row_pc_loc; + if (!first_row->GetRegisterInfo( + pc_regnum.GetAsKind(unwind_plan.GetRegisterKind()), + first_row_pc_loc) || + !first_row_pc_loc.IsAtCFAPlusOffset() || + first_row_pc_loc.GetOffset() != -wordsize) { + return false; + } + + // It looks like the prologue is described. Is the epilogue described? If it + // is, no need to do any augmentation. + + if (first_row != last_row && + first_row->GetOffset() != last_row->GetOffset()) { + // The first & last row have the same CFA register and the same CFA offset + // value and the CFA register is esp/rsp (the stack pointer). + + // We're checking that both of them have an unwind rule like "CFA=esp+4" or + // CFA+rsp+8". + + if (first_row->GetCFAValue().GetValueType() == + last_row->GetCFAValue().GetValueType() && + first_row->GetCFAValue().GetRegisterNumber() == + last_row->GetCFAValue().GetRegisterNumber() && + first_row->GetCFAValue().GetOffset() == + last_row->GetCFAValue().GetOffset()) { + // Get the register locations for eip/rip from the first & last rows. Are + // they both CFA plus an offset? Is it the same offset? + + UnwindPlan::Row::RegisterLocation last_row_pc_loc; + if (last_row->GetRegisterInfo( + pc_regnum.GetAsKind(unwind_plan.GetRegisterKind()), + last_row_pc_loc)) { + if (last_row_pc_loc.IsAtCFAPlusOffset() && + first_row_pc_loc.GetOffset() == last_row_pc_loc.GetOffset()) { + + // One last sanity check: Is the unwind rule for getting the caller + // pc value "deref the CFA-4" or "deref the CFA-8"? + + // If so, we have an UnwindPlan that already describes the epilogue + // and we don't need to modify it at all. + + if (first_row_pc_loc.GetOffset() == -wordsize) { + return true; + } + } + } + } + } + + if (do_augment_unwindplan) { + if (!func.GetBaseAddress().IsValid() || func.GetByteSize() == 0) + return false; + if (m_assembly_inspection_engine == nullptr) + return false; + std::vector<uint8_t> function_text(func.GetByteSize()); + Status error; + if (process_sp->GetTarget().ReadMemory( + func.GetBaseAddress(), function_text.data(), func.GetByteSize(), + error) == func.GetByteSize()) { + RegisterContextSP reg_ctx(thread.GetRegisterContext()); + m_assembly_inspection_engine->Initialize(reg_ctx); + return m_assembly_inspection_engine->AugmentUnwindPlanFromCallSite( + function_text.data(), func.GetByteSize(), func, unwind_plan, reg_ctx); + } + } + + return false; +} + +bool UnwindAssembly_x86::GetFastUnwindPlan(AddressRange &func, Thread &thread, + UnwindPlan &unwind_plan) { + // if prologue is + // 55 pushl %ebp + // 89 e5 movl %esp, %ebp + // or + // 55 pushq %rbp + // 48 89 e5 movq %rsp, %rbp + + // We should pull in the ABI architecture default unwind plan and return that + + llvm::SmallVector<uint8_t, 4> opcode_data; + + ProcessSP process_sp = thread.GetProcess(); + if (process_sp) { + Target &target(process_sp->GetTarget()); + Status error; + if (target.ReadMemory(func.GetBaseAddress(), opcode_data.data(), 4, + error) == 4) { + uint8_t i386_push_mov[] = {0x55, 0x89, 0xe5}; + uint8_t x86_64_push_mov[] = {0x55, 0x48, 0x89, 0xe5}; + + if (memcmp(opcode_data.data(), i386_push_mov, sizeof(i386_push_mov)) == + 0 || + memcmp(opcode_data.data(), x86_64_push_mov, + sizeof(x86_64_push_mov)) == 0) { + ABISP abi_sp = process_sp->GetABI(); + if (abi_sp) { + return abi_sp->CreateDefaultUnwindPlan(unwind_plan); + } + } + } + } + return false; +} + +bool UnwindAssembly_x86::FirstNonPrologueInsn( + AddressRange &func, const ExecutionContext &exe_ctx, + Address &first_non_prologue_insn) { + + if (!func.GetBaseAddress().IsValid()) + return false; + + Target *target = exe_ctx.GetTargetPtr(); + if (target == nullptr) + return false; + + if (m_assembly_inspection_engine == nullptr) + return false; + + std::vector<uint8_t> function_text(func.GetByteSize()); + Status error; + if (target->ReadMemory(func.GetBaseAddress(), function_text.data(), + func.GetByteSize(), error) == func.GetByteSize()) { + size_t offset; + if (m_assembly_inspection_engine->FindFirstNonPrologueInstruction( + function_text.data(), func.GetByteSize(), offset)) { + first_non_prologue_insn = func.GetBaseAddress(); + first_non_prologue_insn.Slide(offset); + } + return true; + } + return false; +} + +UnwindAssembly *UnwindAssembly_x86::CreateInstance(const ArchSpec &arch) { + const llvm::Triple::ArchType cpu = arch.GetMachine(); + if (cpu == llvm::Triple::x86 || cpu == llvm::Triple::x86_64) + return new UnwindAssembly_x86(arch); + return nullptr; +} + +void UnwindAssembly_x86::Initialize() { + PluginManager::RegisterPlugin(GetPluginNameStatic(), + GetPluginDescriptionStatic(), CreateInstance); +} + +void UnwindAssembly_x86::Terminate() { + PluginManager::UnregisterPlugin(CreateInstance); +} + +llvm::StringRef UnwindAssembly_x86::GetPluginDescriptionStatic() { + return "i386 and x86_64 assembly language profiler plugin."; +} diff --git a/contrib/llvm-project/lldb/source/Plugins/UnwindAssembly/x86/UnwindAssembly-x86.h b/contrib/llvm-project/lldb/source/Plugins/UnwindAssembly/x86/UnwindAssembly-x86.h new file mode 100644 index 000000000000..3857c8776b02 --- /dev/null +++ b/contrib/llvm-project/lldb/source/Plugins/UnwindAssembly/x86/UnwindAssembly-x86.h @@ -0,0 +1,63 @@ +//===-- UnwindAssembly-x86.h ------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#ifndef LLDB_SOURCE_PLUGINS_UNWINDASSEMBLY_X86_UNWINDASSEMBLY_X86_H +#define LLDB_SOURCE_PLUGINS_UNWINDASSEMBLY_X86_UNWINDASSEMBLY_X86_H + +#include "x86AssemblyInspectionEngine.h" + +#include "lldb/Target/UnwindAssembly.h" +#include "lldb/lldb-private.h" + +class UnwindAssembly_x86 : public lldb_private::UnwindAssembly { +public: + ~UnwindAssembly_x86() override; + + bool GetNonCallSiteUnwindPlanFromAssembly( + lldb_private::AddressRange &func, lldb_private::Thread &thread, + lldb_private::UnwindPlan &unwind_plan) override; + + bool + AugmentUnwindPlanFromCallSite(lldb_private::AddressRange &func, + lldb_private::Thread &thread, + lldb_private::UnwindPlan &unwind_plan) override; + + bool GetFastUnwindPlan(lldb_private::AddressRange &func, + lldb_private::Thread &thread, + lldb_private::UnwindPlan &unwind_plan) override; + + // thread may be NULL in which case we only use the Target (e.g. if this is + // called pre-process-launch). + bool + FirstNonPrologueInsn(lldb_private::AddressRange &func, + const lldb_private::ExecutionContext &exe_ctx, + lldb_private::Address &first_non_prologue_insn) override; + + static lldb_private::UnwindAssembly * + CreateInstance(const lldb_private::ArchSpec &arch); + + // PluginInterface protocol + static void Initialize(); + + static void Terminate(); + + static llvm::StringRef GetPluginNameStatic() { return "x86"; } + + static llvm::StringRef GetPluginDescriptionStatic(); + + llvm::StringRef GetPluginName() override { return GetPluginNameStatic(); } + +private: + UnwindAssembly_x86(const lldb_private::ArchSpec &arch); + + lldb_private::ArchSpec m_arch; + + lldb_private::x86AssemblyInspectionEngine *m_assembly_inspection_engine; +}; + +#endif // LLDB_SOURCE_PLUGINS_UNWINDASSEMBLY_X86_UNWINDASSEMBLY_X86_H diff --git a/contrib/llvm-project/lldb/source/Plugins/UnwindAssembly/x86/x86AssemblyInspectionEngine.cpp b/contrib/llvm-project/lldb/source/Plugins/UnwindAssembly/x86/x86AssemblyInspectionEngine.cpp new file mode 100644 index 000000000000..6bfaa54135a9 --- /dev/null +++ b/contrib/llvm-project/lldb/source/Plugins/UnwindAssembly/x86/x86AssemblyInspectionEngine.cpp @@ -0,0 +1,1606 @@ +//===-- x86AssemblyInspectionEngine.cpp -----------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include "x86AssemblyInspectionEngine.h" + +#include <memory> + +#include "llvm-c/Disassembler.h" + +#include "lldb/Core/Address.h" +#include "lldb/Symbol/UnwindPlan.h" +#include "lldb/Target/RegisterContext.h" +#include "lldb/Target/UnwindAssembly.h" + +using namespace lldb_private; +using namespace lldb; + +x86AssemblyInspectionEngine::x86AssemblyInspectionEngine(const ArchSpec &arch) + : m_cur_insn(nullptr), m_machine_ip_regnum(LLDB_INVALID_REGNUM), + m_machine_sp_regnum(LLDB_INVALID_REGNUM), + m_machine_fp_regnum(LLDB_INVALID_REGNUM), + m_machine_alt_fp_regnum(LLDB_INVALID_REGNUM), + m_lldb_ip_regnum(LLDB_INVALID_REGNUM), + m_lldb_sp_regnum(LLDB_INVALID_REGNUM), + m_lldb_fp_regnum(LLDB_INVALID_REGNUM), + m_lldb_alt_fp_regnum(LLDB_INVALID_REGNUM), m_reg_map(), m_arch(arch), + m_cpu(k_cpu_unspecified), m_wordsize(-1), + m_register_map_initialized(false), m_disasm_context() { + m_disasm_context = + ::LLVMCreateDisasm(arch.GetTriple().getTriple().c_str(), nullptr, + /*TagType=*/1, nullptr, nullptr); +} + +x86AssemblyInspectionEngine::~x86AssemblyInspectionEngine() { + ::LLVMDisasmDispose(m_disasm_context); +} + +void x86AssemblyInspectionEngine::Initialize(RegisterContextSP ®_ctx) { + m_cpu = k_cpu_unspecified; + m_wordsize = -1; + m_register_map_initialized = false; + + const llvm::Triple::ArchType cpu = m_arch.GetMachine(); + if (cpu == llvm::Triple::x86) + m_cpu = k_i386; + else if (cpu == llvm::Triple::x86_64) + m_cpu = k_x86_64; + + if (m_cpu == k_cpu_unspecified) + return; + + if (reg_ctx.get() == nullptr) + return; + + if (m_cpu == k_i386) { + m_machine_ip_regnum = k_machine_eip; + m_machine_sp_regnum = k_machine_esp; + m_machine_fp_regnum = k_machine_ebp; + m_machine_alt_fp_regnum = k_machine_ebx; + m_wordsize = 4; + + struct lldb_reg_info reginfo; + reginfo.name = "eax"; + m_reg_map[k_machine_eax] = reginfo; + reginfo.name = "edx"; + m_reg_map[k_machine_edx] = reginfo; + reginfo.name = "esp"; + m_reg_map[k_machine_esp] = reginfo; + reginfo.name = "esi"; + m_reg_map[k_machine_esi] = reginfo; + reginfo.name = "eip"; + m_reg_map[k_machine_eip] = reginfo; + reginfo.name = "ecx"; + m_reg_map[k_machine_ecx] = reginfo; + reginfo.name = "ebx"; + m_reg_map[k_machine_ebx] = reginfo; + reginfo.name = "ebp"; + m_reg_map[k_machine_ebp] = reginfo; + reginfo.name = "edi"; + m_reg_map[k_machine_edi] = reginfo; + } else { + m_machine_ip_regnum = k_machine_rip; + m_machine_sp_regnum = k_machine_rsp; + m_machine_fp_regnum = k_machine_rbp; + m_machine_alt_fp_regnum = k_machine_rbx; + m_wordsize = 8; + + struct lldb_reg_info reginfo; + reginfo.name = "rax"; + m_reg_map[k_machine_rax] = reginfo; + reginfo.name = "rdx"; + m_reg_map[k_machine_rdx] = reginfo; + reginfo.name = "rsp"; + m_reg_map[k_machine_rsp] = reginfo; + reginfo.name = "rsi"; + m_reg_map[k_machine_rsi] = reginfo; + reginfo.name = "r8"; + m_reg_map[k_machine_r8] = reginfo; + reginfo.name = "r10"; + m_reg_map[k_machine_r10] = reginfo; + reginfo.name = "r12"; + m_reg_map[k_machine_r12] = reginfo; + reginfo.name = "r14"; + m_reg_map[k_machine_r14] = reginfo; + reginfo.name = "rip"; + m_reg_map[k_machine_rip] = reginfo; + reginfo.name = "rcx"; + m_reg_map[k_machine_rcx] = reginfo; + reginfo.name = "rbx"; + m_reg_map[k_machine_rbx] = reginfo; + reginfo.name = "rbp"; + m_reg_map[k_machine_rbp] = reginfo; + reginfo.name = "rdi"; + m_reg_map[k_machine_rdi] = reginfo; + reginfo.name = "r9"; + m_reg_map[k_machine_r9] = reginfo; + reginfo.name = "r11"; + m_reg_map[k_machine_r11] = reginfo; + reginfo.name = "r13"; + m_reg_map[k_machine_r13] = reginfo; + reginfo.name = "r15"; + m_reg_map[k_machine_r15] = reginfo; + } + + for (MachineRegnumToNameAndLLDBRegnum::iterator it = m_reg_map.begin(); + it != m_reg_map.end(); ++it) { + const RegisterInfo *ri = reg_ctx->GetRegisterInfoByName(it->second.name); + if (ri) + it->second.lldb_regnum = ri->kinds[eRegisterKindLLDB]; + } + + uint32_t lldb_regno; + if (machine_regno_to_lldb_regno(m_machine_sp_regnum, lldb_regno)) + m_lldb_sp_regnum = lldb_regno; + if (machine_regno_to_lldb_regno(m_machine_fp_regnum, lldb_regno)) + m_lldb_fp_regnum = lldb_regno; + if (machine_regno_to_lldb_regno(m_machine_alt_fp_regnum, lldb_regno)) + m_lldb_alt_fp_regnum = lldb_regno; + if (machine_regno_to_lldb_regno(m_machine_ip_regnum, lldb_regno)) + m_lldb_ip_regnum = lldb_regno; + + m_register_map_initialized = true; +} + +void x86AssemblyInspectionEngine::Initialize( + std::vector<lldb_reg_info> ®_info) { + m_cpu = k_cpu_unspecified; + m_wordsize = -1; + m_register_map_initialized = false; + + const llvm::Triple::ArchType cpu = m_arch.GetMachine(); + if (cpu == llvm::Triple::x86) + m_cpu = k_i386; + else if (cpu == llvm::Triple::x86_64) + m_cpu = k_x86_64; + + if (m_cpu == k_cpu_unspecified) + return; + + if (m_cpu == k_i386) { + m_machine_ip_regnum = k_machine_eip; + m_machine_sp_regnum = k_machine_esp; + m_machine_fp_regnum = k_machine_ebp; + m_machine_alt_fp_regnum = k_machine_ebx; + m_wordsize = 4; + + struct lldb_reg_info reginfo; + reginfo.name = "eax"; + m_reg_map[k_machine_eax] = reginfo; + reginfo.name = "edx"; + m_reg_map[k_machine_edx] = reginfo; + reginfo.name = "esp"; + m_reg_map[k_machine_esp] = reginfo; + reginfo.name = "esi"; + m_reg_map[k_machine_esi] = reginfo; + reginfo.name = "eip"; + m_reg_map[k_machine_eip] = reginfo; + reginfo.name = "ecx"; + m_reg_map[k_machine_ecx] = reginfo; + reginfo.name = "ebx"; + m_reg_map[k_machine_ebx] = reginfo; + reginfo.name = "ebp"; + m_reg_map[k_machine_ebp] = reginfo; + reginfo.name = "edi"; + m_reg_map[k_machine_edi] = reginfo; + } else { + m_machine_ip_regnum = k_machine_rip; + m_machine_sp_regnum = k_machine_rsp; + m_machine_fp_regnum = k_machine_rbp; + m_machine_alt_fp_regnum = k_machine_rbx; + m_wordsize = 8; + + struct lldb_reg_info reginfo; + reginfo.name = "rax"; + m_reg_map[k_machine_rax] = reginfo; + reginfo.name = "rdx"; + m_reg_map[k_machine_rdx] = reginfo; + reginfo.name = "rsp"; + m_reg_map[k_machine_rsp] = reginfo; + reginfo.name = "rsi"; + m_reg_map[k_machine_rsi] = reginfo; + reginfo.name = "r8"; + m_reg_map[k_machine_r8] = reginfo; + reginfo.name = "r10"; + m_reg_map[k_machine_r10] = reginfo; + reginfo.name = "r12"; + m_reg_map[k_machine_r12] = reginfo; + reginfo.name = "r14"; + m_reg_map[k_machine_r14] = reginfo; + reginfo.name = "rip"; + m_reg_map[k_machine_rip] = reginfo; + reginfo.name = "rcx"; + m_reg_map[k_machine_rcx] = reginfo; + reginfo.name = "rbx"; + m_reg_map[k_machine_rbx] = reginfo; + reginfo.name = "rbp"; + m_reg_map[k_machine_rbp] = reginfo; + reginfo.name = "rdi"; + m_reg_map[k_machine_rdi] = reginfo; + reginfo.name = "r9"; + m_reg_map[k_machine_r9] = reginfo; + reginfo.name = "r11"; + m_reg_map[k_machine_r11] = reginfo; + reginfo.name = "r13"; + m_reg_map[k_machine_r13] = reginfo; + reginfo.name = "r15"; + m_reg_map[k_machine_r15] = reginfo; + } + + for (MachineRegnumToNameAndLLDBRegnum::iterator it = m_reg_map.begin(); + it != m_reg_map.end(); ++it) { + for (size_t i = 0; i < reg_info.size(); ++i) { + if (::strcmp(reg_info[i].name, it->second.name) == 0) { + it->second.lldb_regnum = reg_info[i].lldb_regnum; + break; + } + } + } + + uint32_t lldb_regno; + if (machine_regno_to_lldb_regno(m_machine_sp_regnum, lldb_regno)) + m_lldb_sp_regnum = lldb_regno; + if (machine_regno_to_lldb_regno(m_machine_fp_regnum, lldb_regno)) + m_lldb_fp_regnum = lldb_regno; + if (machine_regno_to_lldb_regno(m_machine_alt_fp_regnum, lldb_regno)) + m_lldb_alt_fp_regnum = lldb_regno; + if (machine_regno_to_lldb_regno(m_machine_ip_regnum, lldb_regno)) + m_lldb_ip_regnum = lldb_regno; + + m_register_map_initialized = true; +} + +// This function expects an x86 native register number (i.e. the bits stripped +// out of the actual instruction), not an lldb register number. +// +// FIXME: This is ABI dependent, it shouldn't be hardcoded here. + +bool x86AssemblyInspectionEngine::nonvolatile_reg_p(int machine_regno) { + if (m_cpu == k_i386) { + switch (machine_regno) { + case k_machine_ebx: + case k_machine_ebp: // not actually a nonvolatile but often treated as such + // by convention + case k_machine_esi: + case k_machine_edi: + case k_machine_esp: + return true; + default: + return false; + } + } + if (m_cpu == k_x86_64) { + switch (machine_regno) { + case k_machine_rbx: + case k_machine_rsp: + case k_machine_rbp: // not actually a nonvolatile but often treated as such + // by convention + case k_machine_r12: + case k_machine_r13: + case k_machine_r14: + case k_machine_r15: + return true; + default: + return false; + } + } + return false; +} + +// Macro to detect if this is a REX mode prefix byte. +#define REX_W_PREFIX_P(opcode) (((opcode) & (~0x5)) == 0x48) + +// The high bit which should be added to the source register number (the "R" +// bit) +#define REX_W_SRCREG(opcode) (((opcode)&0x4) >> 2) + +// The high bit which should be added to the destination register number (the +// "B" bit) +#define REX_W_DSTREG(opcode) ((opcode)&0x1) + +// pushq %rbp [0x55] +bool x86AssemblyInspectionEngine::push_rbp_pattern_p() { + uint8_t *p = m_cur_insn; + return *p == 0x55; +} + +// pushq $0 ; the first instruction in start() [0x6a 0x00] +bool x86AssemblyInspectionEngine::push_0_pattern_p() { + uint8_t *p = m_cur_insn; + return *p == 0x6a && *(p + 1) == 0x0; +} + +// pushq $0 +// pushl $0 +bool x86AssemblyInspectionEngine::push_imm_pattern_p() { + uint8_t *p = m_cur_insn; + return *p == 0x68 || *p == 0x6a; +} + +// pushl imm8(%esp) +// +// e.g. 0xff 0x74 0x24 0x20 - 'pushl 0x20(%esp)' (same byte pattern for 'pushq +// 0x20(%rsp)' in an x86_64 program) +// +// 0xff (with opcode bits '6' in next byte, PUSH r/m32) 0x74 (ModR/M byte with +// three bits used to specify the opcode) +// mod == b01, opcode == b110, R/M == b100 +// "+disp8" +// 0x24 (SIB byte - scaled index = 0, r32 == esp) 0x20 imm8 value + +bool x86AssemblyInspectionEngine::push_extended_pattern_p() { + if (*m_cur_insn == 0xff) { + // Get the 3 opcode bits from the ModR/M byte + uint8_t opcode = (*(m_cur_insn + 1) >> 3) & 7; + if (opcode == 6) { + // I'm only looking for 0xff /6 here - I + // don't really care what value is being pushed, just that we're pushing + // a 32/64 bit value on to the stack is enough. + return true; + } + } + return false; +} + +// instructions only valid in 32-bit mode: +// 0x0e - push cs +// 0x16 - push ss +// 0x1e - push ds +// 0x06 - push es +bool x86AssemblyInspectionEngine::push_misc_reg_p() { + uint8_t p = *m_cur_insn; + if (m_wordsize == 4) { + if (p == 0x0e || p == 0x16 || p == 0x1e || p == 0x06) + return true; + } + return false; +} + +// pushq %rbx +// pushl %ebx +bool x86AssemblyInspectionEngine::push_reg_p(int ®no) { + uint8_t *p = m_cur_insn; + int regno_prefix_bit = 0; + // If we have a rex prefix byte, check to see if a B bit is set + if (m_wordsize == 8 && (*p & 0xfe) == 0x40) { + regno_prefix_bit = (*p & 1) << 3; + p++; + } + if (*p >= 0x50 && *p <= 0x57) { + regno = (*p - 0x50) | regno_prefix_bit; + return true; + } + return false; +} + +// movq %rsp, %rbp [0x48 0x8b 0xec] or [0x48 0x89 0xe5] movl %esp, %ebp [0x8b +// 0xec] or [0x89 0xe5] +bool x86AssemblyInspectionEngine::mov_rsp_rbp_pattern_p() { + uint8_t *p = m_cur_insn; + if (m_wordsize == 8 && *p == 0x48) + p++; + if (*(p) == 0x8b && *(p + 1) == 0xec) + return true; + if (*(p) == 0x89 && *(p + 1) == 0xe5) + return true; + return false; +} + +// movq %rsp, %rbx [0x48 0x8b 0xdc] or [0x48 0x89 0xe3] +// movl %esp, %ebx [0x8b 0xdc] or [0x89 0xe3] +bool x86AssemblyInspectionEngine::mov_rsp_rbx_pattern_p() { + uint8_t *p = m_cur_insn; + if (m_wordsize == 8 && *p == 0x48) + p++; + if (*(p) == 0x8b && *(p + 1) == 0xdc) + return true; + if (*(p) == 0x89 && *(p + 1) == 0xe3) + return true; + return false; +} + +// movq %rbp, %rsp [0x48 0x8b 0xe5] or [0x48 0x89 0xec] +// movl %ebp, %esp [0x8b 0xe5] or [0x89 0xec] +bool x86AssemblyInspectionEngine::mov_rbp_rsp_pattern_p() { + uint8_t *p = m_cur_insn; + if (m_wordsize == 8 && *p == 0x48) + p++; + if (*(p) == 0x8b && *(p + 1) == 0xe5) + return true; + if (*(p) == 0x89 && *(p + 1) == 0xec) + return true; + return false; +} + +// movq %rbx, %rsp [0x48 0x8b 0xe3] or [0x48 0x89 0xdc] +// movl %ebx, %esp [0x8b 0xe3] or [0x89 0xdc] +bool x86AssemblyInspectionEngine::mov_rbx_rsp_pattern_p() { + uint8_t *p = m_cur_insn; + if (m_wordsize == 8 && *p == 0x48) + p++; + if (*(p) == 0x8b && *(p + 1) == 0xe3) + return true; + if (*(p) == 0x89 && *(p + 1) == 0xdc) + return true; + return false; +} + +// subq $0x20, %rsp +bool x86AssemblyInspectionEngine::sub_rsp_pattern_p(int &amount) { + uint8_t *p = m_cur_insn; + if (m_wordsize == 8 && *p == 0x48) + p++; + // 8-bit immediate operand + if (*p == 0x83 && *(p + 1) == 0xec) { + amount = (int8_t) * (p + 2); + return true; + } + // 32-bit immediate operand + if (*p == 0x81 && *(p + 1) == 0xec) { + amount = (int32_t)extract_4(p + 2); + return true; + } + return false; +} + +// addq $0x20, %rsp +bool x86AssemblyInspectionEngine::add_rsp_pattern_p(int &amount) { + uint8_t *p = m_cur_insn; + if (m_wordsize == 8 && *p == 0x48) + p++; + // 8-bit immediate operand + if (*p == 0x83 && *(p + 1) == 0xc4) { + amount = (int8_t) * (p + 2); + return true; + } + // 32-bit immediate operand + if (*p == 0x81 && *(p + 1) == 0xc4) { + amount = (int32_t)extract_4(p + 2); + return true; + } + return false; +} + +// lea esp, [esp - 0x28] +// lea esp, [esp + 0x28] +bool x86AssemblyInspectionEngine::lea_rsp_pattern_p(int &amount) { + uint8_t *p = m_cur_insn; + if (m_wordsize == 8 && *p == 0x48) + p++; + + // Check opcode + if (*p != 0x8d) + return false; + + // 8 bit displacement + if (*(p + 1) == 0x64 && (*(p + 2) & 0x3f) == 0x24) { + amount = (int8_t) * (p + 3); + return true; + } + + // 32 bit displacement + if (*(p + 1) == 0xa4 && (*(p + 2) & 0x3f) == 0x24) { + amount = (int32_t)extract_4(p + 3); + return true; + } + + return false; +} + +// lea -0x28(%ebp), %esp +// (32-bit and 64-bit variants, 8-bit and 32-bit displacement) +bool x86AssemblyInspectionEngine::lea_rbp_rsp_pattern_p(int &amount) { + uint8_t *p = m_cur_insn; + if (m_wordsize == 8 && *p == 0x48) + p++; + + // Check opcode + if (*p != 0x8d) + return false; + ++p; + + // 8 bit displacement + if (*p == 0x65) { + amount = (int8_t)p[1]; + return true; + } + + // 32 bit displacement + if (*p == 0xa5) { + amount = (int32_t)extract_4(p + 1); + return true; + } + + return false; +} + +// lea -0x28(%ebx), %esp +// (32-bit and 64-bit variants, 8-bit and 32-bit displacement) +bool x86AssemblyInspectionEngine::lea_rbx_rsp_pattern_p(int &amount) { + uint8_t *p = m_cur_insn; + if (m_wordsize == 8 && *p == 0x48) + p++; + + // Check opcode + if (*p != 0x8d) + return false; + ++p; + + // 8 bit displacement + if (*p == 0x63) { + amount = (int8_t)p[1]; + return true; + } + + // 32 bit displacement + if (*p == 0xa3) { + amount = (int32_t)extract_4(p + 1); + return true; + } + + return false; +} + +// and -0xfffffff0, %esp +// (32-bit and 64-bit variants, 8-bit and 32-bit displacement) +bool x86AssemblyInspectionEngine::and_rsp_pattern_p() { + uint8_t *p = m_cur_insn; + if (m_wordsize == 8 && *p == 0x48) + p++; + + if (*p != 0x81 && *p != 0x83) + return false; + + return *++p == 0xe4; +} + +// popq %rbx +// popl %ebx +bool x86AssemblyInspectionEngine::pop_reg_p(int ®no) { + uint8_t *p = m_cur_insn; + int regno_prefix_bit = 0; + // If we have a rex prefix byte, check to see if a B bit is set + if (m_wordsize == 8 && (*p & 0xfe) == 0x40) { + regno_prefix_bit = (*p & 1) << 3; + p++; + } + if (*p >= 0x58 && *p <= 0x5f) { + regno = (*p - 0x58) | regno_prefix_bit; + return true; + } + return false; +} + +// popq %rbp [0x5d] +// popl %ebp [0x5d] +bool x86AssemblyInspectionEngine::pop_rbp_pattern_p() { + uint8_t *p = m_cur_insn; + return (*p == 0x5d); +} + +// instructions valid only in 32-bit mode: +// 0x1f - pop ds +// 0x07 - pop es +// 0x17 - pop ss +bool x86AssemblyInspectionEngine::pop_misc_reg_p() { + uint8_t p = *m_cur_insn; + if (m_wordsize == 4) { + if (p == 0x1f || p == 0x07 || p == 0x17) + return true; + } + return false; +} + +// leave [0xc9] +bool x86AssemblyInspectionEngine::leave_pattern_p() { + uint8_t *p = m_cur_insn; + return (*p == 0xc9); +} + +// call $0 [0xe8 0x0 0x0 0x0 0x0] +bool x86AssemblyInspectionEngine::call_next_insn_pattern_p() { + uint8_t *p = m_cur_insn; + return (*p == 0xe8) && (*(p + 1) == 0x0) && (*(p + 2) == 0x0) && + (*(p + 3) == 0x0) && (*(p + 4) == 0x0); +} + +// Look for an instruction sequence storing a nonvolatile register on to the +// stack frame. + +// movq %rax, -0x10(%rbp) [0x48 0x89 0x45 0xf0] +// movl %eax, -0xc(%ebp) [0x89 0x45 0xf4] + +// The offset value returned in rbp_offset will be positive -- but it must be +// subtraced from the frame base register to get the actual location. The +// positive value returned for the offset is a convention used elsewhere for +// CFA offsets et al. + +bool x86AssemblyInspectionEngine::mov_reg_to_local_stack_frame_p( + int ®no, int &rbp_offset) { + uint8_t *p = m_cur_insn; + int src_reg_prefix_bit = 0; + int target_reg_prefix_bit = 0; + + if (m_wordsize == 8 && REX_W_PREFIX_P(*p)) { + src_reg_prefix_bit = REX_W_SRCREG(*p) << 3; + target_reg_prefix_bit = REX_W_DSTREG(*p) << 3; + if (target_reg_prefix_bit == 1) { + // rbp/ebp don't need a prefix bit - we know this isn't the reg we care + // about. + return false; + } + p++; + } + + if (*p == 0x89) { + /* Mask off the 3-5 bits which indicate the destination register + if this is a ModR/M byte. */ + int opcode_destreg_masked_out = *(p + 1) & (~0x38); + + /* Is this a ModR/M byte with Mod bits 01 and R/M bits 101 + and three bits between them, e.g. 01nnn101 + We're looking for a destination of ebp-disp8 or ebp-disp32. */ + int immsize; + if (opcode_destreg_masked_out == 0x45) + immsize = 2; + else if (opcode_destreg_masked_out == 0x85) + immsize = 4; + else + return false; + + int offset = 0; + if (immsize == 2) + offset = (int8_t) * (p + 2); + if (immsize == 4) + offset = (uint32_t)extract_4(p + 2); + if (offset > 0) + return false; + + regno = ((*(p + 1) >> 3) & 0x7) | src_reg_prefix_bit; + rbp_offset = offset > 0 ? offset : -offset; + return true; + } + return false; +} + +// Returns true if this is a jmp instruction where we can't +// know the destination address statically. +// +// ff e0 jmpq *%rax +// ff e1 jmpq *%rcx +// ff 60 28 jmpq *0x28(%rax) +// ff 60 60 jmpq *0x60(%rax) +bool x86AssemblyInspectionEngine::jmp_to_reg_p() { + if (*m_cur_insn != 0xff) + return false; + + // The second byte is a ModR/M /4 byte, strip off the registers + uint8_t second_byte_sans_reg = *(m_cur_insn + 1) & ~7; + + // [reg] + if (second_byte_sans_reg == 0x20) + return true; + + // [reg]+disp8 + if (second_byte_sans_reg == 0x60) + return true; + + // [reg]+disp32 + if (second_byte_sans_reg == 0xa0) + return true; + + // reg + if (second_byte_sans_reg == 0xe0) + return true; + + return false; +} + +// Detect branches to fixed pc-relative offsets. +// Returns the offset from the address of the next instruction +// that may be branch/jumped to. +// +// Cannot determine the offset of a JMP that jumps to the address in +// a register ("jmpq *%rax") or offset from a register value +// ("jmpq *0x28(%rax)"), this method will return false on those +// instructions. +// +// These instructions all end in either a relative 8/16/32 bit value +// depending on the instruction and the current execution mode of the +// inferior process. Once we know the size of the opcode instruction, +// we can use the total instruction length to determine the size of +// the relative offset without having to compute it correctly. + +bool x86AssemblyInspectionEngine::pc_rel_branch_or_jump_p ( + const int instruction_length, int &offset) +{ + int opcode_size = 0; + + uint8_t b1 = m_cur_insn[0]; + + switch (b1) { + case 0x77: // JA/JNBE rel8 + case 0x73: // JAE/JNB/JNC rel8 + case 0x72: // JB/JC/JNAE rel8 + case 0x76: // JBE/JNA rel8 + case 0xe3: // JCXZ/JECXZ/JRCXZ rel8 + case 0x74: // JE/JZ rel8 + case 0x7f: // JG/JNLE rel8 + case 0x7d: // JGE/JNL rel8 + case 0x7c: // JL/JNGE rel8 + case 0x7e: // JNG/JLE rel8 + case 0x71: // JNO rel8 + case 0x7b: // JNP/JPO rel8 + case 0x79: // JNS rel8 + case 0x75: // JNE/JNZ rel8 + case 0x70: // JO rel8 + case 0x7a: // JP/JPE rel8 + case 0x78: // JS rel8 + case 0xeb: // JMP rel8 + case 0xe9: // JMP rel16/rel32 + opcode_size = 1; + break; + default: + break; + } + if (b1 == 0x0f && opcode_size == 0) { + uint8_t b2 = m_cur_insn[1]; + switch (b2) { + case 0x87: // JA/JNBE rel16/rel32 + case 0x86: // JBE/JNA rel16/rel32 + case 0x84: // JE/JZ rel16/rel32 + case 0x8f: // JG/JNLE rel16/rel32 + case 0x8d: // JNL/JGE rel16/rel32 + case 0x8e: // JLE rel16/rel32 + case 0x82: // JB/JC/JNAE rel16/rel32 + case 0x83: // JAE/JNB/JNC rel16/rel32 + case 0x85: // JNE/JNZ rel16/rel32 + case 0x8c: // JL/JNGE rel16/rel32 + case 0x81: // JNO rel16/rel32 + case 0x8b: // JNP/JPO rel16/rel32 + case 0x89: // JNS rel16/rel32 + case 0x80: // JO rel16/rel32 + case 0x8a: // JP rel16/rel32 + case 0x88: // JS rel16/rel32 + opcode_size = 2; + break; + default: + break; + } + } + + if (opcode_size == 0) + return false; + + offset = 0; + if (instruction_length - opcode_size == 1) { + int8_t rel8 = (int8_t) *(m_cur_insn + opcode_size); + offset = rel8; + } else if (instruction_length - opcode_size == 2) { + int16_t rel16 = extract_2_signed (m_cur_insn + opcode_size); + offset = rel16; + } else if (instruction_length - opcode_size == 4) { + int32_t rel32 = extract_4_signed (m_cur_insn + opcode_size); + offset = rel32; + } else { + return false; + } + return true; +} + +// Returns true if this instruction is a intra-function branch or jump - +// a branch/jump within the bounds of this same function. +// Cannot predict where a jump through a register value ("jmpq *%rax") +// will go, so it will return false on that instruction. +bool x86AssemblyInspectionEngine::local_branch_p ( + const addr_t current_func_text_offset, + const AddressRange &func_range, + const int instruction_length, + addr_t &target_insn_offset) { + int offset; + if (pc_rel_branch_or_jump_p (instruction_length, offset) && offset != 0) { + addr_t next_pc_value = current_func_text_offset + instruction_length; + if (offset < 0 && addr_t(-offset) > current_func_text_offset) { + // Branch target is before the start of this function + return false; + } + if (offset + next_pc_value > func_range.GetByteSize()) { + // Branch targets outside this function's bounds + return false; + } + // This instruction branches to target_insn_offset (byte offset into the function) + target_insn_offset = next_pc_value + offset; + return true; + } + return false; +} + +// Returns true if this instruction is a inter-function branch or jump - a +// branch/jump to another function. +// Cannot predict where a jump through a register value ("jmpq *%rax") +// will go, so it will return false on that instruction. +bool x86AssemblyInspectionEngine::non_local_branch_p ( + const addr_t current_func_text_offset, + const AddressRange &func_range, + const int instruction_length) { + int offset; + addr_t target_insn_offset; + if (pc_rel_branch_or_jump_p (instruction_length, offset)) { + return !local_branch_p(current_func_text_offset,func_range,instruction_length,target_insn_offset); + } + return false; +} + +// ret [0xc3] or [0xcb] or [0xc2 imm16] or [0xca imm16] +bool x86AssemblyInspectionEngine::ret_pattern_p() { + uint8_t *p = m_cur_insn; + return *p == 0xc3 || *p == 0xc2 || *p == 0xca || *p == 0xcb; +} + +uint16_t x86AssemblyInspectionEngine::extract_2(uint8_t *b) { + uint16_t v = 0; + for (int i = 1; i >= 0; i--) + v = (v << 8) | b[i]; + return v; +} + +int16_t x86AssemblyInspectionEngine::extract_2_signed(uint8_t *b) { + int16_t v = 0; + for (int i = 1; i >= 0; i--) + v = (v << 8) | b[i]; + return v; +} + +uint32_t x86AssemblyInspectionEngine::extract_4(uint8_t *b) { + uint32_t v = 0; + for (int i = 3; i >= 0; i--) + v = (v << 8) | b[i]; + return v; +} + +int32_t x86AssemblyInspectionEngine::extract_4_signed(uint8_t *b) { + int32_t v = 0; + for (int i = 3; i >= 0; i--) + v = (v << 8) | b[i]; + return v; +} + + +bool x86AssemblyInspectionEngine::instruction_length(uint8_t *insn_p, + int &length, + uint32_t buffer_remaining_bytes) { + + uint32_t max_op_byte_size = std::min(buffer_remaining_bytes, m_arch.GetMaximumOpcodeByteSize()); + llvm::SmallVector<uint8_t, 32> opcode_data; + opcode_data.resize(max_op_byte_size); + + char out_string[512]; + const size_t inst_size = + ::LLVMDisasmInstruction(m_disasm_context, insn_p, max_op_byte_size, 0, + out_string, sizeof(out_string)); + + length = inst_size; + return true; +} + +bool x86AssemblyInspectionEngine::machine_regno_to_lldb_regno( + int machine_regno, uint32_t &lldb_regno) { + MachineRegnumToNameAndLLDBRegnum::iterator it = m_reg_map.find(machine_regno); + if (it != m_reg_map.end()) { + lldb_regno = it->second.lldb_regnum; + return true; + } + return false; +} + +bool x86AssemblyInspectionEngine::GetNonCallSiteUnwindPlanFromAssembly( + uint8_t *data, size_t size, AddressRange &func_range, + UnwindPlan &unwind_plan) { + unwind_plan.Clear(); + + if (data == nullptr || size == 0) + return false; + + if (!m_register_map_initialized) + return false; + + if (m_disasm_context == nullptr) + return false; + + addr_t current_func_text_offset = 0; + int current_sp_bytes_offset_from_fa = 0; + bool is_aligned = false; + UnwindPlan::Row::RegisterLocation initial_regloc; + UnwindPlan::RowSP row(new UnwindPlan::Row); + + unwind_plan.SetPlanValidAddressRange(func_range); + unwind_plan.SetRegisterKind(eRegisterKindLLDB); + + // At the start of the function, find the CFA by adding wordsize to the SP + // register + row->SetOffset(current_func_text_offset); + row->GetCFAValue().SetIsRegisterPlusOffset(m_lldb_sp_regnum, m_wordsize); + + // caller's stack pointer value before the call insn is the CFA address + initial_regloc.SetIsCFAPlusOffset(0); + row->SetRegisterInfo(m_lldb_sp_regnum, initial_regloc); + + // saved instruction pointer can be found at CFA - wordsize. + current_sp_bytes_offset_from_fa = m_wordsize; + initial_regloc.SetAtCFAPlusOffset(-current_sp_bytes_offset_from_fa); + row->SetRegisterInfo(m_lldb_ip_regnum, initial_regloc); + + unwind_plan.AppendRow(row); + + // Allocate a new Row, populate it with the existing Row contents. + UnwindPlan::Row *newrow = new UnwindPlan::Row; + *newrow = *row.get(); + row.reset(newrow); + + // Track which registers have been saved so far in the prologue. If we see + // another push of that register, it's not part of the prologue. The register + // numbers used here are the machine register #'s (i386_register_numbers, + // x86_64_register_numbers). + std::vector<bool> saved_registers(32, false); + + // Once the prologue has completed we'll save a copy of the unwind + // instructions If there is an epilogue in the middle of the function, after + // that epilogue we'll reinstate the unwind setup -- we assume that some code + // path jumps over the mid-function epilogue + + UnwindPlan::RowSP prologue_completed_row; // copy of prologue row of CFI + int prologue_completed_sp_bytes_offset_from_cfa = 0; // The sp value before the + // epilogue started executed + bool prologue_completed_is_aligned = false; + std::vector<bool> prologue_completed_saved_registers; + + while (current_func_text_offset < size) { + int stack_offset, insn_len; + int machine_regno; // register numbers masked directly out of instructions + uint32_t lldb_regno; // register numbers in lldb's eRegisterKindLLDB + // numbering scheme + + bool in_epilogue = false; // we're in the middle of an epilogue sequence + bool row_updated = false; // The UnwindPlan::Row 'row' has been updated + + m_cur_insn = data + current_func_text_offset; + if (!instruction_length(m_cur_insn, insn_len, size - current_func_text_offset) + || insn_len == 0 + || insn_len > kMaxInstructionByteSize) { + // An unrecognized/junk instruction + break; + } + + auto &cfa_value = row->GetCFAValue(); + auto &afa_value = row->GetAFAValue(); + auto fa_value_ptr = is_aligned ? &afa_value : &cfa_value; + + if (mov_rsp_rbp_pattern_p()) { + if (fa_value_ptr->GetRegisterNumber() == m_lldb_sp_regnum) { + fa_value_ptr->SetIsRegisterPlusOffset( + m_lldb_fp_regnum, fa_value_ptr->GetOffset()); + row_updated = true; + } + } + + else if (mov_rsp_rbx_pattern_p()) { + if (fa_value_ptr->GetRegisterNumber() == m_lldb_sp_regnum) { + fa_value_ptr->SetIsRegisterPlusOffset( + m_lldb_alt_fp_regnum, fa_value_ptr->GetOffset()); + row_updated = true; + } + } + + else if (and_rsp_pattern_p()) { + current_sp_bytes_offset_from_fa = 0; + afa_value.SetIsRegisterPlusOffset( + m_lldb_sp_regnum, current_sp_bytes_offset_from_fa); + fa_value_ptr = &afa_value; + is_aligned = true; + row_updated = true; + } + + else if (mov_rbp_rsp_pattern_p()) { + if (is_aligned && cfa_value.GetRegisterNumber() == m_lldb_fp_regnum) + { + is_aligned = false; + fa_value_ptr = &cfa_value; + afa_value.SetUnspecified(); + row_updated = true; + } + if (fa_value_ptr->GetRegisterNumber() == m_lldb_fp_regnum) + current_sp_bytes_offset_from_fa = fa_value_ptr->GetOffset(); + } + + else if (mov_rbx_rsp_pattern_p()) { + if (is_aligned && cfa_value.GetRegisterNumber() == m_lldb_alt_fp_regnum) + { + is_aligned = false; + fa_value_ptr = &cfa_value; + afa_value.SetUnspecified(); + row_updated = true; + } + if (fa_value_ptr->GetRegisterNumber() == m_lldb_alt_fp_regnum) + current_sp_bytes_offset_from_fa = fa_value_ptr->GetOffset(); + } + + // This is the start() function (or a pthread equivalent), it starts with a + // pushl $0x0 which puts the saved pc value of 0 on the stack. In this + // case we want to pretend we didn't see a stack movement at all -- + // normally the saved pc value is already on the stack by the time the + // function starts executing. + else if (push_0_pattern_p()) { + } + + else if (push_reg_p(machine_regno)) { + current_sp_bytes_offset_from_fa += m_wordsize; + // the PUSH instruction has moved the stack pointer - if the FA is set + // in terms of the stack pointer, we need to add a new row of + // instructions. + if (fa_value_ptr->GetRegisterNumber() == m_lldb_sp_regnum) { + fa_value_ptr->SetOffset(current_sp_bytes_offset_from_fa); + row_updated = true; + } + // record where non-volatile (callee-saved, spilled) registers are saved + // on the stack + if (nonvolatile_reg_p(machine_regno) && + machine_regno_to_lldb_regno(machine_regno, lldb_regno) && + !saved_registers[machine_regno]) { + UnwindPlan::Row::RegisterLocation regloc; + if (is_aligned) + regloc.SetAtAFAPlusOffset(-current_sp_bytes_offset_from_fa); + else + regloc.SetAtCFAPlusOffset(-current_sp_bytes_offset_from_fa); + row->SetRegisterInfo(lldb_regno, regloc); + saved_registers[machine_regno] = true; + row_updated = true; + } + } + + else if (pop_reg_p(machine_regno)) { + current_sp_bytes_offset_from_fa -= m_wordsize; + + if (nonvolatile_reg_p(machine_regno) && + machine_regno_to_lldb_regno(machine_regno, lldb_regno) && + saved_registers[machine_regno]) { + saved_registers[machine_regno] = false; + row->RemoveRegisterInfo(lldb_regno); + + if (lldb_regno == fa_value_ptr->GetRegisterNumber()) { + fa_value_ptr->SetIsRegisterPlusOffset( + m_lldb_sp_regnum, fa_value_ptr->GetOffset()); + } + + in_epilogue = true; + row_updated = true; + } + + // the POP instruction has moved the stack pointer - if the FA is set in + // terms of the stack pointer, we need to add a new row of instructions. + if (fa_value_ptr->GetRegisterNumber() == m_lldb_sp_regnum) { + fa_value_ptr->SetIsRegisterPlusOffset( + m_lldb_sp_regnum, current_sp_bytes_offset_from_fa); + row_updated = true; + } + } + + else if (pop_misc_reg_p()) { + current_sp_bytes_offset_from_fa -= m_wordsize; + if (fa_value_ptr->GetRegisterNumber() == m_lldb_sp_regnum) { + fa_value_ptr->SetIsRegisterPlusOffset( + m_lldb_sp_regnum, current_sp_bytes_offset_from_fa); + row_updated = true; + } + } + + // The LEAVE instruction moves the value from rbp into rsp and pops a value + // off the stack into rbp (restoring the caller's rbp value). It is the + // opposite of ENTER, or 'push rbp, mov rsp rbp'. + else if (leave_pattern_p()) { + if (saved_registers[m_machine_fp_regnum]) { + saved_registers[m_machine_fp_regnum] = false; + row->RemoveRegisterInfo(m_lldb_fp_regnum); + + row_updated = true; + } + + if (is_aligned && cfa_value.GetRegisterNumber() == m_lldb_fp_regnum) + { + is_aligned = false; + fa_value_ptr = &cfa_value; + afa_value.SetUnspecified(); + row_updated = true; + } + + if (fa_value_ptr->GetRegisterNumber() == m_lldb_fp_regnum) + { + fa_value_ptr->SetIsRegisterPlusOffset( + m_lldb_sp_regnum, fa_value_ptr->GetOffset()); + + current_sp_bytes_offset_from_fa = fa_value_ptr->GetOffset(); + } + + current_sp_bytes_offset_from_fa -= m_wordsize; + + if (fa_value_ptr->GetRegisterNumber() == m_lldb_sp_regnum) { + fa_value_ptr->SetIsRegisterPlusOffset( + m_lldb_sp_regnum, current_sp_bytes_offset_from_fa); + row_updated = true; + } + + in_epilogue = true; + } + + else if (mov_reg_to_local_stack_frame_p(machine_regno, stack_offset) && + nonvolatile_reg_p(machine_regno) && + machine_regno_to_lldb_regno(machine_regno, lldb_regno) && + !saved_registers[machine_regno]) { + saved_registers[machine_regno] = true; + + UnwindPlan::Row::RegisterLocation regloc; + + // stack_offset for 'movq %r15, -80(%rbp)' will be 80. In the Row, we + // want to express this as the offset from the FA. If the frame base is + // rbp (like the above instruction), the FA offset for rbp is probably + // 16. So we want to say that the value is stored at the FA address - + // 96. + if (is_aligned) + regloc.SetAtAFAPlusOffset(-(stack_offset + fa_value_ptr->GetOffset())); + else + regloc.SetAtCFAPlusOffset(-(stack_offset + fa_value_ptr->GetOffset())); + + row->SetRegisterInfo(lldb_regno, regloc); + + row_updated = true; + } + + else if (sub_rsp_pattern_p(stack_offset)) { + current_sp_bytes_offset_from_fa += stack_offset; + if (fa_value_ptr->GetRegisterNumber() == m_lldb_sp_regnum) { + fa_value_ptr->SetOffset(current_sp_bytes_offset_from_fa); + row_updated = true; + } + } + + else if (add_rsp_pattern_p(stack_offset)) { + current_sp_bytes_offset_from_fa -= stack_offset; + if (fa_value_ptr->GetRegisterNumber() == m_lldb_sp_regnum) { + fa_value_ptr->SetOffset(current_sp_bytes_offset_from_fa); + row_updated = true; + } + in_epilogue = true; + } + + else if (push_extended_pattern_p() || push_imm_pattern_p() || + push_misc_reg_p()) { + current_sp_bytes_offset_from_fa += m_wordsize; + if (fa_value_ptr->GetRegisterNumber() == m_lldb_sp_regnum) { + fa_value_ptr->SetOffset(current_sp_bytes_offset_from_fa); + row_updated = true; + } + } + + else if (lea_rsp_pattern_p(stack_offset)) { + current_sp_bytes_offset_from_fa -= stack_offset; + if (fa_value_ptr->GetRegisterNumber() == m_lldb_sp_regnum) { + fa_value_ptr->SetOffset(current_sp_bytes_offset_from_fa); + row_updated = true; + } + if (stack_offset > 0) + in_epilogue = true; + } + + else if (lea_rbp_rsp_pattern_p(stack_offset)) { + if (is_aligned && + cfa_value.GetRegisterNumber() == m_lldb_fp_regnum) { + is_aligned = false; + fa_value_ptr = &cfa_value; + afa_value.SetUnspecified(); + row_updated = true; + } + if (fa_value_ptr->GetRegisterNumber() == m_lldb_fp_regnum) { + current_sp_bytes_offset_from_fa = + fa_value_ptr->GetOffset() - stack_offset; + } + } + + else if (lea_rbx_rsp_pattern_p(stack_offset)) { + if (is_aligned && + cfa_value.GetRegisterNumber() == m_lldb_alt_fp_regnum) { + is_aligned = false; + fa_value_ptr = &cfa_value; + afa_value.SetUnspecified(); + row_updated = true; + } + if (fa_value_ptr->GetRegisterNumber() == m_lldb_alt_fp_regnum) { + current_sp_bytes_offset_from_fa = fa_value_ptr->GetOffset() - stack_offset; + } + } + + else if (prologue_completed_row.get() && + (ret_pattern_p() || + non_local_branch_p (current_func_text_offset, func_range, insn_len) || + jmp_to_reg_p())) { + // Check if the current instruction is the end of an epilogue sequence, + // and if so, re-instate the prologue-completed unwind state. + + // The current instruction is a branch/jump outside this function, + // a ret, or a jump through a register value which we cannot + // determine the effcts of. Verify that the stack frame state + // has been unwound to the same as it was at function entry to avoid + // mis-identifying a JMP instruction as an epilogue. + UnwindPlan::Row::RegisterLocation sp, pc; + if (row->GetRegisterInfo(m_lldb_sp_regnum, sp) && + row->GetRegisterInfo(m_lldb_ip_regnum, pc)) { + // Any ret instruction variant is definitely indicative of an + // epilogue; for other insn patterns verify that we're back to + // the original unwind state. + if (ret_pattern_p() || + (sp.IsCFAPlusOffset() && sp.GetOffset() == 0 && + pc.IsAtCFAPlusOffset() && pc.GetOffset() == -m_wordsize)) { + // Reinstate the saved prologue setup for any instructions that come + // after the epilogue + + UnwindPlan::Row *newrow = new UnwindPlan::Row; + *newrow = *prologue_completed_row.get(); + row.reset(newrow); + current_sp_bytes_offset_from_fa = + prologue_completed_sp_bytes_offset_from_cfa; + is_aligned = prologue_completed_is_aligned; + + saved_registers.clear(); + saved_registers.resize(prologue_completed_saved_registers.size(), false); + for (size_t i = 0; i < prologue_completed_saved_registers.size(); ++i) { + saved_registers[i] = prologue_completed_saved_registers[i]; + } + + in_epilogue = true; + row_updated = true; + } + } + } + + // call next instruction + // call 0 + // => pop %ebx + // This is used in i386 programs to get the PIC base address for finding + // global data + else if (call_next_insn_pattern_p()) { + current_sp_bytes_offset_from_fa += m_wordsize; + if (fa_value_ptr->GetRegisterNumber() == m_lldb_sp_regnum) { + fa_value_ptr->SetOffset(current_sp_bytes_offset_from_fa); + row_updated = true; + } + } + + if (row_updated) { + if (current_func_text_offset + insn_len < size) { + row->SetOffset(current_func_text_offset + insn_len); + unwind_plan.AppendRow(row); + // Allocate a new Row, populate it with the existing Row contents. + newrow = new UnwindPlan::Row; + *newrow = *row.get(); + row.reset(newrow); + } + } + + if (!in_epilogue && row_updated) { + // If we're not in an epilogue sequence, save the updated Row + UnwindPlan::Row *newrow = new UnwindPlan::Row; + *newrow = *row.get(); + prologue_completed_row.reset(newrow); + + prologue_completed_saved_registers.clear(); + prologue_completed_saved_registers.resize(saved_registers.size(), false); + for (size_t i = 0; i < saved_registers.size(); ++i) { + prologue_completed_saved_registers[i] = saved_registers[i]; + } + } + + // We may change the sp value without adding a new Row necessarily -- keep + // track of it either way. + if (!in_epilogue) { + prologue_completed_sp_bytes_offset_from_cfa = + current_sp_bytes_offset_from_fa; + prologue_completed_is_aligned = is_aligned; + } + + m_cur_insn = m_cur_insn + insn_len; + current_func_text_offset += insn_len; + } + + unwind_plan.SetSourceName("assembly insn profiling"); + unwind_plan.SetSourcedFromCompiler(eLazyBoolNo); + unwind_plan.SetUnwindPlanValidAtAllInstructions(eLazyBoolYes); + unwind_plan.SetUnwindPlanForSignalTrap(eLazyBoolNo); + + return true; +} + +bool x86AssemblyInspectionEngine::AugmentUnwindPlanFromCallSite( + uint8_t *data, size_t size, AddressRange &func_range, + UnwindPlan &unwind_plan, RegisterContextSP ®_ctx) { + Address addr_start = func_range.GetBaseAddress(); + if (!addr_start.IsValid()) + return false; + + // We either need a live RegisterContext, or we need the UnwindPlan to + // already be in the lldb register numbering scheme. + if (reg_ctx.get() == nullptr && + unwind_plan.GetRegisterKind() != eRegisterKindLLDB) + return false; + + // Is original unwind_plan valid? + // unwind_plan should have at least one row which is ABI-default (CFA + // register is sp), and another row in mid-function. + if (unwind_plan.GetRowCount() < 2) + return false; + + UnwindPlan::RowSP first_row = unwind_plan.GetRowAtIndex(0); + if (first_row->GetOffset() != 0) + return false; + uint32_t cfa_reg = first_row->GetCFAValue().GetRegisterNumber(); + if (unwind_plan.GetRegisterKind() != eRegisterKindLLDB) { + cfa_reg = reg_ctx->ConvertRegisterKindToRegisterNumber( + unwind_plan.GetRegisterKind(), + first_row->GetCFAValue().GetRegisterNumber()); + } + if (cfa_reg != m_lldb_sp_regnum || + first_row->GetCFAValue().GetOffset() != m_wordsize) + return false; + + UnwindPlan::RowSP original_last_row = unwind_plan.GetRowForFunctionOffset(-1); + + size_t offset = 0; + int row_id = 1; + bool unwind_plan_updated = false; + UnwindPlan::RowSP row(new UnwindPlan::Row(*first_row)); + + // After a mid-function epilogue we will need to re-insert the original + // unwind rules so unwinds work for the remainder of the function. These + // aren't common with clang/gcc on x86 but it is possible. + bool reinstate_unwind_state = false; + + while (offset < size) { + m_cur_insn = data + offset; + int insn_len; + if (!instruction_length(m_cur_insn, insn_len, size - offset) || + insn_len == 0 || insn_len > kMaxInstructionByteSize) { + // An unrecognized/junk instruction. + break; + } + + // Advance offsets. + offset += insn_len; + + // offset is pointing beyond the bounds of the function; stop looping. + if (offset >= size) + continue; + + if (reinstate_unwind_state) { + UnwindPlan::RowSP new_row(new UnwindPlan::Row()); + *new_row = *original_last_row; + new_row->SetOffset(offset); + unwind_plan.AppendRow(new_row); + row = std::make_shared<UnwindPlan::Row>(); + *row = *new_row; + reinstate_unwind_state = false; + unwind_plan_updated = true; + continue; + } + + // If we already have one row for this instruction, we can continue. + while (row_id < unwind_plan.GetRowCount() && + unwind_plan.GetRowAtIndex(row_id)->GetOffset() <= offset) { + row_id++; + } + UnwindPlan::RowSP original_row = unwind_plan.GetRowAtIndex(row_id - 1); + if (original_row->GetOffset() == offset) { + *row = *original_row; + continue; + } + + if (row_id == 0) { + // If we are here, compiler didn't generate CFI for prologue. This won't + // happen to GCC or clang. In this case, bail out directly. + return false; + } + + // Inspect the instruction to check if we need a new row for it. + cfa_reg = row->GetCFAValue().GetRegisterNumber(); + if (unwind_plan.GetRegisterKind() != eRegisterKindLLDB) { + cfa_reg = reg_ctx->ConvertRegisterKindToRegisterNumber( + unwind_plan.GetRegisterKind(), + row->GetCFAValue().GetRegisterNumber()); + } + if (cfa_reg == m_lldb_sp_regnum) { + // CFA register is sp. + + // call next instruction + // call 0 + // => pop %ebx + if (call_next_insn_pattern_p()) { + row->SetOffset(offset); + row->GetCFAValue().IncOffset(m_wordsize); + + UnwindPlan::RowSP new_row(new UnwindPlan::Row(*row)); + unwind_plan.InsertRow(new_row); + unwind_plan_updated = true; + continue; + } + + // push/pop register + int regno; + if (push_reg_p(regno)) { + row->SetOffset(offset); + row->GetCFAValue().IncOffset(m_wordsize); + + UnwindPlan::RowSP new_row(new UnwindPlan::Row(*row)); + unwind_plan.InsertRow(new_row); + unwind_plan_updated = true; + continue; + } + if (pop_reg_p(regno)) { + // Technically, this might be a nonvolatile register recover in + // epilogue. We should reset RegisterInfo for the register. But in + // practice, previous rule for the register is still valid... So we + // ignore this case. + + row->SetOffset(offset); + row->GetCFAValue().IncOffset(-m_wordsize); + + UnwindPlan::RowSP new_row(new UnwindPlan::Row(*row)); + unwind_plan.InsertRow(new_row); + unwind_plan_updated = true; + continue; + } + + if (pop_misc_reg_p()) { + row->SetOffset(offset); + row->GetCFAValue().IncOffset(-m_wordsize); + + UnwindPlan::RowSP new_row(new UnwindPlan::Row(*row)); + unwind_plan.InsertRow(new_row); + unwind_plan_updated = true; + continue; + } + + // push imm + if (push_imm_pattern_p()) { + row->SetOffset(offset); + row->GetCFAValue().IncOffset(m_wordsize); + UnwindPlan::RowSP new_row(new UnwindPlan::Row(*row)); + unwind_plan.InsertRow(new_row); + unwind_plan_updated = true; + continue; + } + + // push extended + if (push_extended_pattern_p() || push_misc_reg_p()) { + row->SetOffset(offset); + row->GetCFAValue().IncOffset(m_wordsize); + UnwindPlan::RowSP new_row(new UnwindPlan::Row(*row)); + unwind_plan.InsertRow(new_row); + unwind_plan_updated = true; + continue; + } + + // add/sub %rsp/%esp + int amount; + if (add_rsp_pattern_p(amount)) { + row->SetOffset(offset); + row->GetCFAValue().IncOffset(-amount); + + UnwindPlan::RowSP new_row(new UnwindPlan::Row(*row)); + unwind_plan.InsertRow(new_row); + unwind_plan_updated = true; + continue; + } + if (sub_rsp_pattern_p(amount)) { + row->SetOffset(offset); + row->GetCFAValue().IncOffset(amount); + + UnwindPlan::RowSP new_row(new UnwindPlan::Row(*row)); + unwind_plan.InsertRow(new_row); + unwind_plan_updated = true; + continue; + } + + // lea %rsp, [%rsp + $offset] + if (lea_rsp_pattern_p(amount)) { + row->SetOffset(offset); + row->GetCFAValue().IncOffset(-amount); + + UnwindPlan::RowSP new_row(new UnwindPlan::Row(*row)); + unwind_plan.InsertRow(new_row); + unwind_plan_updated = true; + continue; + } + + if (ret_pattern_p()) { + reinstate_unwind_state = true; + continue; + } + } else if (cfa_reg == m_lldb_fp_regnum) { + // CFA register is fp. + + // The only case we care about is epilogue: + // [0x5d] pop %rbp/%ebp + // => [0xc3] ret + if (pop_rbp_pattern_p() || leave_pattern_p()) { + m_cur_insn++; + if (ret_pattern_p()) { + row->SetOffset(offset); + row->GetCFAValue().SetIsRegisterPlusOffset( + first_row->GetCFAValue().GetRegisterNumber(), m_wordsize); + + UnwindPlan::RowSP new_row(new UnwindPlan::Row(*row)); + unwind_plan.InsertRow(new_row); + unwind_plan_updated = true; + reinstate_unwind_state = true; + continue; + } + } + } else { + // CFA register is not sp or fp. + + // This must be hand-written assembly. + // Just trust eh_frame and assume we have finished. + break; + } + } + + unwind_plan.SetPlanValidAddressRange(func_range); + if (unwind_plan_updated) { + std::string unwind_plan_source(unwind_plan.GetSourceName().AsCString()); + unwind_plan_source += " plus augmentation from assembly parsing"; + unwind_plan.SetSourceName(unwind_plan_source.c_str()); + unwind_plan.SetSourcedFromCompiler(eLazyBoolNo); + unwind_plan.SetUnwindPlanValidAtAllInstructions(eLazyBoolYes); + } + return true; +} + +bool x86AssemblyInspectionEngine::FindFirstNonPrologueInstruction( + uint8_t *data, size_t size, size_t &offset) { + offset = 0; + + if (!m_register_map_initialized) + return false; + + if (m_disasm_context == nullptr) + return false; + + while (offset < size) { + int regno; + int insn_len; + int scratch; + + m_cur_insn = data + offset; + if (!instruction_length(m_cur_insn, insn_len, size - offset) + || insn_len > kMaxInstructionByteSize + || insn_len == 0) { + // An error parsing the instruction, i.e. probably data/garbage - stop + // scanning + break; + } + + if (push_rbp_pattern_p() || mov_rsp_rbp_pattern_p() || + sub_rsp_pattern_p(scratch) || push_reg_p(regno) || + mov_reg_to_local_stack_frame_p(regno, scratch) || + (lea_rsp_pattern_p(scratch) && offset == 0)) { + offset += insn_len; + continue; + } + // + // Unknown non-prologue instruction - stop scanning + break; + } + + return true; +} diff --git a/contrib/llvm-project/lldb/source/Plugins/UnwindAssembly/x86/x86AssemblyInspectionEngine.h b/contrib/llvm-project/lldb/source/Plugins/UnwindAssembly/x86/x86AssemblyInspectionEngine.h new file mode 100644 index 000000000000..487748812968 --- /dev/null +++ b/contrib/llvm-project/lldb/source/Plugins/UnwindAssembly/x86/x86AssemblyInspectionEngine.h @@ -0,0 +1,201 @@ +//===-- x86AssemblyInspectionEngine.h ---------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#ifndef LLDB_SOURCE_PLUGINS_UNWINDASSEMBLY_X86_X86ASSEMBLYINSPECTIONENGINE_H +#define LLDB_SOURCE_PLUGINS_UNWINDASSEMBLY_X86_X86ASSEMBLYINSPECTIONENGINE_H + +#include "llvm-c/Disassembler.h" + +#include "lldb/Utility/ArchSpec.h" +#include "lldb/Utility/ConstString.h" +#include "lldb/lldb-enumerations.h" +#include "lldb/lldb-forward.h" +#include "lldb/lldb-private.h" + +#include <map> +#include <vector> + +namespace lldb_private { + +// x86AssemblyInspectionEngine - a class which will take a buffer of bytes +// of i386/x86_64 instructions and create an UnwindPlan based on those +// assembly instructions. +class x86AssemblyInspectionEngine { + +public: + /// default ctor + x86AssemblyInspectionEngine(const lldb_private::ArchSpec &arch); + + /// default dtor + ~x86AssemblyInspectionEngine(); + + /// One of the two initialize methods that can be called on this object; + /// they must be called before any of the assembly inspection methods + /// are called. This one should be used if the caller has access to a + /// valid RegisterContext. + void Initialize(lldb::RegisterContextSP ®_ctx); + + /// One of the two initialize methods that can be called on this object; + /// they must be called before any of the assembly inspection methods + /// are called. This one takes a vector of register name and lldb + /// register numbers. + struct lldb_reg_info { + const char *name = nullptr; + uint32_t lldb_regnum = LLDB_INVALID_REGNUM; + lldb_reg_info() = default; + }; + void Initialize(std::vector<lldb_reg_info> ®_info); + + /// Create an UnwindPlan for a "non-call site" stack frame situation. + /// This is usually when this function/method is currently executing, and may + /// be at + /// a location where exception-handling style unwind information (eh_frame, + /// compact unwind info, arm unwind info) + /// are not valid. + /// \p data is a pointer to the instructions for the function + /// \p size is the size of the instruction buffer above + /// \p func_range is the start Address and size of the function, to be + /// included in the UnwindPlan + /// \p unwind_plan is the unwind plan that this method creates + /// \returns true if it was able to create an UnwindPlan; false if not. + bool + GetNonCallSiteUnwindPlanFromAssembly(uint8_t *data, size_t size, + lldb_private::AddressRange &func_range, + lldb_private::UnwindPlan &unwind_plan); + + /// Take an existing UnwindPlan, probably from eh_frame which may be missing + /// description + /// of the epilogue instructions, and add the epilogue description to it based + /// on the + /// instructions in the function. + /// + /// The \p unwind_plan 's register numbers must be converted into the lldb + /// register numbering + /// scheme OR a RegisterContext must be provided in \p reg_ctx. If the \p + /// unwind_plan + /// register numbers are already in lldb register numbering, \p reg_ctx may be + /// null. + /// \returns true if the \p unwind_plan was updated, false if it was not. + bool AugmentUnwindPlanFromCallSite(uint8_t *data, size_t size, + lldb_private::AddressRange &func_range, + lldb_private::UnwindPlan &unwind_plan, + lldb::RegisterContextSP ®_ctx); + + bool FindFirstNonPrologueInstruction(uint8_t *data, size_t size, + size_t &offset); + +private: + bool nonvolatile_reg_p(int machine_regno); + bool push_rbp_pattern_p(); + bool push_0_pattern_p(); + bool push_imm_pattern_p(); + bool push_extended_pattern_p(); + bool push_misc_reg_p(); + bool mov_rsp_rbp_pattern_p(); + bool mov_rsp_rbx_pattern_p(); + bool mov_rbp_rsp_pattern_p(); + bool mov_rbx_rsp_pattern_p(); + bool sub_rsp_pattern_p(int &amount); + bool add_rsp_pattern_p(int &amount); + bool lea_rsp_pattern_p(int &amount); + bool lea_rbp_rsp_pattern_p(int &amount); + bool lea_rbx_rsp_pattern_p(int &amount); + bool and_rsp_pattern_p(); + bool push_reg_p(int ®no); + bool pop_reg_p(int ®no); + bool pop_rbp_pattern_p(); + bool pop_misc_reg_p(); + bool leave_pattern_p(); + bool call_next_insn_pattern_p(); + bool mov_reg_to_local_stack_frame_p(int ®no, int &rbp_offset); + bool ret_pattern_p(); + bool jmp_to_reg_p(); + bool pc_rel_branch_or_jump_p (const int instruction_length, int &offset); + bool non_local_branch_p (const lldb::addr_t current_func_text_offset, + const lldb_private::AddressRange &func_range, + const int instruction_length); + bool local_branch_p (const lldb::addr_t current_func_text_offset, + const lldb_private::AddressRange &func_range, + const int instruction_length, + lldb::addr_t &target_insn_offset); + uint16_t extract_2(uint8_t *b); + int16_t extract_2_signed(uint8_t *b); + uint32_t extract_4(uint8_t *b); + int32_t extract_4_signed(uint8_t *b); + + bool instruction_length(uint8_t *insn, int &length, uint32_t buffer_remaining_bytes); + + bool machine_regno_to_lldb_regno(int machine_regno, uint32_t &lldb_regno); + + enum CPU { k_i386, k_x86_64, k_cpu_unspecified }; + + enum i386_register_numbers { + k_machine_eax = 0, + k_machine_ecx = 1, + k_machine_edx = 2, + k_machine_ebx = 3, + k_machine_esp = 4, + k_machine_ebp = 5, + k_machine_esi = 6, + k_machine_edi = 7, + k_machine_eip = 8 + }; + + enum x86_64_register_numbers { + k_machine_rax = 0, + k_machine_rcx = 1, + k_machine_rdx = 2, + k_machine_rbx = 3, + k_machine_rsp = 4, + k_machine_rbp = 5, + k_machine_rsi = 6, + k_machine_rdi = 7, + k_machine_r8 = 8, + k_machine_r9 = 9, + k_machine_r10 = 10, + k_machine_r11 = 11, + k_machine_r12 = 12, + k_machine_r13 = 13, + k_machine_r14 = 14, + k_machine_r15 = 15, + k_machine_rip = 16 + }; + + enum { kMaxInstructionByteSize = 32 }; + + uint8_t *m_cur_insn; + + uint32_t m_machine_ip_regnum; + uint32_t m_machine_sp_regnum; + uint32_t m_machine_fp_regnum; + uint32_t m_machine_alt_fp_regnum; + uint32_t m_lldb_ip_regnum; + uint32_t m_lldb_sp_regnum; + uint32_t m_lldb_fp_regnum; + uint32_t m_lldb_alt_fp_regnum; + + typedef std::map<uint32_t, lldb_reg_info> MachineRegnumToNameAndLLDBRegnum; + + MachineRegnumToNameAndLLDBRegnum m_reg_map; + + lldb_private::ArchSpec m_arch; + CPU m_cpu; + int m_wordsize; + + bool m_register_map_initialized; + + ::LLVMDisasmContextRef m_disasm_context; + + x86AssemblyInspectionEngine(const x86AssemblyInspectionEngine &) = delete; + const x86AssemblyInspectionEngine & + operator=(const x86AssemblyInspectionEngine &) = delete; +}; + +} // namespace lldb_private + +#endif // LLDB_SOURCE_PLUGINS_UNWINDASSEMBLY_X86_X86ASSEMBLYINSPECTIONENGINE_H |