brintos

brintos / llvm-project-archived public Read only

0
0
Text · 89.9 KiB · f4d1070 Raw
2358 lines · cpp
1//===-- DWARFExpression.cpp -----------------------------------------------===//2//3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.4// See https://llvm.org/LICENSE.txt for license information.5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception6//7//===----------------------------------------------------------------------===//8 9#include "lldb/Expression/DWARFExpression.h"10 11#include <cinttypes>12 13#include <optional>14#include <vector>15 16#include "lldb/Core/Module.h"17#include "lldb/Core/Value.h"18#include "lldb/Utility/DataEncoder.h"19#include "lldb/Utility/LLDBLog.h"20#include "lldb/Utility/Log.h"21#include "lldb/Utility/RegisterValue.h"22#include "lldb/Utility/Scalar.h"23#include "lldb/Utility/StreamString.h"24#include "lldb/Utility/VMRange.h"25 26#include "lldb/Host/Host.h"27#include "lldb/Utility/Endian.h"28 29#include "lldb/Symbol/Function.h"30 31#include "lldb/Target/ABI.h"32#include "lldb/Target/ExecutionContext.h"33#include "lldb/Target/Process.h"34#include "lldb/Target/RegisterContext.h"35#include "lldb/Target/StackFrame.h"36#include "lldb/Target/StackID.h"37#include "lldb/Target/Target.h"38#include "lldb/Target/Thread.h"39#include "llvm/DebugInfo/DWARF/DWARFExpressionPrinter.h"40#include "llvm/DebugInfo/DWARF/LowLevel/DWARFExpression.h"41 42using namespace lldb;43using namespace lldb_private;44using namespace lldb_private::plugin::dwarf;45using namespace llvm::dwarf;46 47// DWARFExpression constructor48DWARFExpression::DWARFExpression() : m_data() {}49 50DWARFExpression::DWARFExpression(const DataExtractor &data) : m_data(data) {}51 52// Destructor53DWARFExpression::~DWARFExpression() = default;54 55bool DWARFExpression::IsValid() const { return m_data.GetByteSize() > 0; }56 57void DWARFExpression::UpdateValue(uint64_t const_value,58                                  lldb::offset_t const_value_byte_size,59                                  uint8_t addr_byte_size) {60  if (!const_value_byte_size)61    return;62 63  m_data.SetData(64      DataBufferSP(new DataBufferHeap(&const_value, const_value_byte_size)));65  m_data.SetByteOrder(endian::InlHostByteOrder());66  m_data.SetAddressByteSize(addr_byte_size);67}68 69void DWARFExpression::DumpLocation(Stream *s, lldb::DescriptionLevel level,70                                   ABI *abi,71                                   llvm::DIDumpOptions options) const {72  auto *MCRegInfo = abi ? &abi->GetMCRegisterInfo() : nullptr;73  auto GetRegName = [&MCRegInfo](uint64_t DwarfRegNum,74                                 bool IsEH) -> llvm::StringRef {75    if (!MCRegInfo)76      return {};77    if (std::optional<unsigned> LLVMRegNum =78            MCRegInfo->getLLVMRegNum(DwarfRegNum, IsEH))79      if (const char *RegName = MCRegInfo->getName(*LLVMRegNum))80        return llvm::StringRef(RegName);81    return {};82  };83  options.GetNameForDWARFReg = GetRegName;84  llvm::DWARFExpression E(m_data.GetAsLLVM(), m_data.GetAddressByteSize());85  llvm::printDwarfExpression(&E, s->AsRawOstream(), options, nullptr);86}87 88RegisterKind DWARFExpression::GetRegisterKind() const { return m_reg_kind; }89 90void DWARFExpression::SetRegisterKind(RegisterKind reg_kind) {91  m_reg_kind = reg_kind;92}93 94llvm::Error95DWARFExpression::ReadRegisterValueAsScalar(RegisterContext *reg_ctx,96                                           lldb::RegisterKind reg_kind,97                                           uint32_t reg_num, Value &value) {98  if (reg_ctx == nullptr)99    return llvm::createStringError("no register context in frame");100 101  const uint32_t native_reg =102      reg_ctx->ConvertRegisterKindToRegisterNumber(reg_kind, reg_num);103  if (native_reg == LLDB_INVALID_REGNUM)104    return llvm::createStringError(105        "unable to convert register kind=%u reg_num=%u to a native "106        "register number",107        reg_kind, reg_num);108 109  const RegisterInfo *reg_info = reg_ctx->GetRegisterInfoAtIndex(native_reg);110  RegisterValue reg_value;111  if (reg_ctx->ReadRegister(reg_info, reg_value)) {112    if (reg_value.GetScalarValue(value.GetScalar())) {113      value.SetValueType(Value::ValueType::Scalar);114      value.SetContext(Value::ContextType::RegisterInfo,115                       const_cast<RegisterInfo *>(reg_info));116      return llvm::Error::success();117    }118 119    // If we get this error, then we need to implement a value buffer in120    // the dwarf expression evaluation function...121    return llvm::createStringError(122        "register %s can't be converted to a scalar value", reg_info->name);123  }124 125  return llvm::createStringError("register %s is not available",126                                 reg_info->name);127}128 129/// Return the length in bytes of the set of operands for \p op. No guarantees130/// are made on the state of \p data after this call.131static lldb::offset_t132GetOpcodeDataSize(const DataExtractor &data, const lldb::offset_t data_offset,133                  const LocationAtom op,134                  const DWARFExpression::Delegate *dwarf_cu) {135  lldb::offset_t offset = data_offset;136  switch (op) {137  // Only used in LLVM metadata.138  case DW_OP_LLVM_fragment:139  case DW_OP_LLVM_convert:140  case DW_OP_LLVM_tag_offset:141  case DW_OP_LLVM_entry_value:142  case DW_OP_LLVM_implicit_pointer:143  case DW_OP_LLVM_arg:144  case DW_OP_LLVM_extract_bits_sext:145  case DW_OP_LLVM_extract_bits_zext:146    break;147  // Vendor extensions:148  case DW_OP_HP_is_value:149  case DW_OP_HP_fltconst4:150  case DW_OP_HP_fltconst8:151  case DW_OP_HP_mod_range:152  case DW_OP_HP_unmod_range:153  case DW_OP_HP_tls:154  case DW_OP_INTEL_bit_piece:155  case DW_OP_WASM_location:156  case DW_OP_WASM_location_int:157  case DW_OP_APPLE_uninit:158  case DW_OP_PGI_omp_thread_num:159  case DW_OP_hi_user:160  case DW_OP_GNU_implicit_pointer:161    break;162 163  case DW_OP_addr:164  case DW_OP_call_ref: // 0x9a 1 address sized offset of DIE (DWARF3)165    return data.GetAddressByteSize();166 167  // Opcodes with no arguments168  case DW_OP_deref:                // 0x06169  case DW_OP_dup:                  // 0x12170  case DW_OP_drop:                 // 0x13171  case DW_OP_over:                 // 0x14172  case DW_OP_swap:                 // 0x16173  case DW_OP_rot:                  // 0x17174  case DW_OP_xderef:               // 0x18175  case DW_OP_abs:                  // 0x19176  case DW_OP_and:                  // 0x1a177  case DW_OP_div:                  // 0x1b178  case DW_OP_minus:                // 0x1c179  case DW_OP_mod:                  // 0x1d180  case DW_OP_mul:                  // 0x1e181  case DW_OP_neg:                  // 0x1f182  case DW_OP_not:                  // 0x20183  case DW_OP_or:                   // 0x21184  case DW_OP_plus:                 // 0x22185  case DW_OP_shl:                  // 0x24186  case DW_OP_shr:                  // 0x25187  case DW_OP_shra:                 // 0x26188  case DW_OP_xor:                  // 0x27189  case DW_OP_eq:                   // 0x29190  case DW_OP_ge:                   // 0x2a191  case DW_OP_gt:                   // 0x2b192  case DW_OP_le:                   // 0x2c193  case DW_OP_lt:                   // 0x2d194  case DW_OP_ne:                   // 0x2e195  case DW_OP_lit0:                 // 0x30196  case DW_OP_lit1:                 // 0x31197  case DW_OP_lit2:                 // 0x32198  case DW_OP_lit3:                 // 0x33199  case DW_OP_lit4:                 // 0x34200  case DW_OP_lit5:                 // 0x35201  case DW_OP_lit6:                 // 0x36202  case DW_OP_lit7:                 // 0x37203  case DW_OP_lit8:                 // 0x38204  case DW_OP_lit9:                 // 0x39205  case DW_OP_lit10:                // 0x3A206  case DW_OP_lit11:                // 0x3B207  case DW_OP_lit12:                // 0x3C208  case DW_OP_lit13:                // 0x3D209  case DW_OP_lit14:                // 0x3E210  case DW_OP_lit15:                // 0x3F211  case DW_OP_lit16:                // 0x40212  case DW_OP_lit17:                // 0x41213  case DW_OP_lit18:                // 0x42214  case DW_OP_lit19:                // 0x43215  case DW_OP_lit20:                // 0x44216  case DW_OP_lit21:                // 0x45217  case DW_OP_lit22:                // 0x46218  case DW_OP_lit23:                // 0x47219  case DW_OP_lit24:                // 0x48220  case DW_OP_lit25:                // 0x49221  case DW_OP_lit26:                // 0x4A222  case DW_OP_lit27:                // 0x4B223  case DW_OP_lit28:                // 0x4C224  case DW_OP_lit29:                // 0x4D225  case DW_OP_lit30:                // 0x4E226  case DW_OP_lit31:                // 0x4f227  case DW_OP_reg0:                 // 0x50228  case DW_OP_reg1:                 // 0x51229  case DW_OP_reg2:                 // 0x52230  case DW_OP_reg3:                 // 0x53231  case DW_OP_reg4:                 // 0x54232  case DW_OP_reg5:                 // 0x55233  case DW_OP_reg6:                 // 0x56234  case DW_OP_reg7:                 // 0x57235  case DW_OP_reg8:                 // 0x58236  case DW_OP_reg9:                 // 0x59237  case DW_OP_reg10:                // 0x5A238  case DW_OP_reg11:                // 0x5B239  case DW_OP_reg12:                // 0x5C240  case DW_OP_reg13:                // 0x5D241  case DW_OP_reg14:                // 0x5E242  case DW_OP_reg15:                // 0x5F243  case DW_OP_reg16:                // 0x60244  case DW_OP_reg17:                // 0x61245  case DW_OP_reg18:                // 0x62246  case DW_OP_reg19:                // 0x63247  case DW_OP_reg20:                // 0x64248  case DW_OP_reg21:                // 0x65249  case DW_OP_reg22:                // 0x66250  case DW_OP_reg23:                // 0x67251  case DW_OP_reg24:                // 0x68252  case DW_OP_reg25:                // 0x69253  case DW_OP_reg26:                // 0x6A254  case DW_OP_reg27:                // 0x6B255  case DW_OP_reg28:                // 0x6C256  case DW_OP_reg29:                // 0x6D257  case DW_OP_reg30:                // 0x6E258  case DW_OP_reg31:                // 0x6F259  case DW_OP_nop:                  // 0x96260  case DW_OP_push_object_address:  // 0x97 DWARF3261  case DW_OP_form_tls_address:     // 0x9b DWARF3262  case DW_OP_call_frame_cfa:       // 0x9c DWARF3263  case DW_OP_stack_value:          // 0x9f DWARF4264  case DW_OP_GNU_push_tls_address: // 0xe0 GNU extension265    return 0;266 267  // Opcodes with a single 1 byte arguments268  case DW_OP_const1u:     // 0x08 1 1-byte constant269  case DW_OP_const1s:     // 0x09 1 1-byte constant270  case DW_OP_pick:        // 0x15 1 1-byte stack index271  case DW_OP_deref_size:  // 0x94 1 1-byte size of data retrieved272  case DW_OP_xderef_size: // 0x95 1 1-byte size of data retrieved273  case DW_OP_deref_type:  // 0xa6 1 1-byte constant274    return 1;275 276  // Opcodes with a single 2 byte arguments277  case DW_OP_const2u: // 0x0a 1 2-byte constant278  case DW_OP_const2s: // 0x0b 1 2-byte constant279  case DW_OP_skip:    // 0x2f 1 signed 2-byte constant280  case DW_OP_bra:     // 0x28 1 signed 2-byte constant281  case DW_OP_call2:   // 0x98 1 2-byte offset of DIE (DWARF3)282    return 2;283 284  // Opcodes with a single 4 byte arguments285  case DW_OP_const4u: // 0x0c 1 4-byte constant286  case DW_OP_const4s: // 0x0d 1 4-byte constant287  case DW_OP_call4:   // 0x99 1 4-byte offset of DIE (DWARF3)288    return 4;289 290  // Opcodes with a single 8 byte arguments291  case DW_OP_const8u: // 0x0e 1 8-byte constant292  case DW_OP_const8s: // 0x0f 1 8-byte constant293    return 8;294 295  // All opcodes that have a single ULEB (signed or unsigned) argument296  case DW_OP_constu:          // 0x10 1 ULEB128 constant297  case DW_OP_consts:          // 0x11 1 SLEB128 constant298  case DW_OP_plus_uconst:     // 0x23 1 ULEB128 addend299  case DW_OP_breg0:           // 0x70 1 ULEB128 register300  case DW_OP_breg1:           // 0x71 1 ULEB128 register301  case DW_OP_breg2:           // 0x72 1 ULEB128 register302  case DW_OP_breg3:           // 0x73 1 ULEB128 register303  case DW_OP_breg4:           // 0x74 1 ULEB128 register304  case DW_OP_breg5:           // 0x75 1 ULEB128 register305  case DW_OP_breg6:           // 0x76 1 ULEB128 register306  case DW_OP_breg7:           // 0x77 1 ULEB128 register307  case DW_OP_breg8:           // 0x78 1 ULEB128 register308  case DW_OP_breg9:           // 0x79 1 ULEB128 register309  case DW_OP_breg10:          // 0x7a 1 ULEB128 register310  case DW_OP_breg11:          // 0x7b 1 ULEB128 register311  case DW_OP_breg12:          // 0x7c 1 ULEB128 register312  case DW_OP_breg13:          // 0x7d 1 ULEB128 register313  case DW_OP_breg14:          // 0x7e 1 ULEB128 register314  case DW_OP_breg15:          // 0x7f 1 ULEB128 register315  case DW_OP_breg16:          // 0x80 1 ULEB128 register316  case DW_OP_breg17:          // 0x81 1 ULEB128 register317  case DW_OP_breg18:          // 0x82 1 ULEB128 register318  case DW_OP_breg19:          // 0x83 1 ULEB128 register319  case DW_OP_breg20:          // 0x84 1 ULEB128 register320  case DW_OP_breg21:          // 0x85 1 ULEB128 register321  case DW_OP_breg22:          // 0x86 1 ULEB128 register322  case DW_OP_breg23:          // 0x87 1 ULEB128 register323  case DW_OP_breg24:          // 0x88 1 ULEB128 register324  case DW_OP_breg25:          // 0x89 1 ULEB128 register325  case DW_OP_breg26:          // 0x8a 1 ULEB128 register326  case DW_OP_breg27:          // 0x8b 1 ULEB128 register327  case DW_OP_breg28:          // 0x8c 1 ULEB128 register328  case DW_OP_breg29:          // 0x8d 1 ULEB128 register329  case DW_OP_breg30:          // 0x8e 1 ULEB128 register330  case DW_OP_breg31:          // 0x8f 1 ULEB128 register331  case DW_OP_regx:            // 0x90 1 ULEB128 register332  case DW_OP_fbreg:           // 0x91 1 SLEB128 offset333  case DW_OP_piece:           // 0x93 1 ULEB128 size of piece addressed334  case DW_OP_convert:         // 0xa8 1 ULEB128 offset335  case DW_OP_reinterpret:     // 0xa9 1 ULEB128 offset336  case DW_OP_addrx:           // 0xa1 1 ULEB128 index337  case DW_OP_constx:          // 0xa2 1 ULEB128 index338  case DW_OP_xderef_type:     // 0xa7 1 ULEB128 index339  case DW_OP_GNU_addr_index:  // 0xfb 1 ULEB128 index340  case DW_OP_GNU_const_index: // 0xfc 1 ULEB128 index341    data.Skip_LEB128(&offset);342    return offset - data_offset;343 344  // All opcodes that have a 2 ULEB (signed or unsigned) arguments345  case DW_OP_bregx:       // 0x92 2 ULEB128 register followed by SLEB128 offset346  case DW_OP_bit_piece:   // 0x9d ULEB128 bit size, ULEB128 bit offset (DWARF3);347  case DW_OP_regval_type: // 0xa5 ULEB128 + ULEB128348    data.Skip_LEB128(&offset);349    data.Skip_LEB128(&offset);350    return offset - data_offset;351 352  case DW_OP_implicit_value: // 0x9e ULEB128 size followed by block of that size353                             // (DWARF4)354  {355    uint64_t block_len = data.Skip_LEB128(&offset);356    offset += block_len;357    return offset - data_offset;358  }359 360  case DW_OP_implicit_pointer: // 0xa0 4-byte (or 8-byte for DWARF 64) constant361                               // + LEB128362  {363    data.Skip_LEB128(&offset);364    return (dwarf_cu ? dwarf_cu->GetAddressByteSize() : 4) + offset -365           data_offset;366  }367 368  case DW_OP_GNU_entry_value:369  case DW_OP_entry_value: // 0xa3 ULEB128 size + variable-length block370  {371    uint64_t subexpr_len = data.GetULEB128(&offset);372    return (offset - data_offset) + subexpr_len;373  }374 375  case DW_OP_const_type: // 0xa4 ULEB128 + size + variable-length block376  {377    data.Skip_LEB128(&offset);378    uint8_t length = data.GetU8(&offset);379    return (offset - data_offset) + length;380  }381 382  case DW_OP_LLVM_user: // 0xe9: ULEB128 + variable length constant383  {384    uint64_t constants = data.GetULEB128(&offset);385    return (offset - data_offset) + constants;386  }387  }388 389  if (dwarf_cu)390    return dwarf_cu->GetVendorDWARFOpcodeSize(data, data_offset, op);391 392  return LLDB_INVALID_OFFSET;393}394 395static const char *DW_OP_value_to_name(uint32_t val) {396  static char invalid[100];397  llvm::StringRef llvmstr = llvm::dwarf::OperationEncodingString(val);398  if (llvmstr.empty()) {399    snprintf(invalid, sizeof(invalid), "Unknown DW_OP constant: 0x%x", val);400    return invalid;401  }402  return llvmstr.data();403}404 405llvm::Expected<lldb::addr_t> DWARFExpression::GetLocation_DW_OP_addr(406    const DWARFExpression::Delegate *dwarf_cu) const {407  lldb::offset_t offset = 0;408  while (m_data.ValidOffset(offset)) {409    const LocationAtom op = static_cast<LocationAtom>(m_data.GetU8(&offset));410 411    if (op == DW_OP_addr)412      return m_data.GetAddress(&offset);413 414    if (op == DW_OP_GNU_addr_index || op == DW_OP_addrx) {415      const uint64_t index = m_data.GetULEB128(&offset);416      if (dwarf_cu)417        return dwarf_cu->ReadAddressFromDebugAddrSection(index);418      return llvm::createStringError("cannot evaluate %s without a DWARF unit",419                                     DW_OP_value_to_name(op));420    }421 422    const lldb::offset_t op_arg_size =423        GetOpcodeDataSize(m_data, offset, op, dwarf_cu);424    if (op_arg_size == LLDB_INVALID_OFFSET)425      return llvm::createStringError("cannot get opcode data size for %s",426                                     DW_OP_value_to_name(op));427 428    offset += op_arg_size;429  }430 431  return LLDB_INVALID_ADDRESS;432}433 434bool DWARFExpression::Update_DW_OP_addr(435    const DWARFExpression::Delegate *dwarf_cu, lldb::addr_t file_addr) {436  lldb::offset_t offset = 0;437  while (m_data.ValidOffset(offset)) {438    const LocationAtom op = static_cast<LocationAtom>(m_data.GetU8(&offset));439 440    if (op == DW_OP_addr) {441      const uint32_t addr_byte_size = m_data.GetAddressByteSize();442      // We have to make a copy of the data as we don't know if this data is443      // from a read only memory mapped buffer, so we duplicate all of the data444      // first, then modify it, and if all goes well, we then replace the data445      // for this expression446 447      // Make en encoder that contains a copy of the location expression data448      // so we can write the address into the buffer using the correct byte449      // order.450      DataEncoder encoder(m_data.GetDataStart(), m_data.GetByteSize(),451                          m_data.GetByteOrder(), addr_byte_size);452 453      // Replace the address in the new buffer454      if (encoder.PutAddress(offset, file_addr) == UINT32_MAX)455        return false;456 457      // All went well, so now we can reset the data using a shared pointer to458      // the heap data so "m_data" will now correctly manage the heap data.459      m_data.SetData(encoder.GetDataBuffer());460      return true;461    }462    if (op == DW_OP_addrx) {463      // Replace DW_OP_addrx with DW_OP_addr, since we can't modify the464      // read-only debug_addr table.465      // Subtract one to account for the opcode.466      llvm::ArrayRef data_before_op = m_data.GetData().take_front(offset - 1);467 468      // Read the addrx index to determine how many bytes it needs.469      const lldb::offset_t old_offset = offset;470      m_data.GetULEB128(&offset);471      if (old_offset == offset)472        return false;473      llvm::ArrayRef data_after_op = m_data.GetData().drop_front(offset);474 475      DataEncoder encoder(m_data.GetByteOrder(), m_data.GetAddressByteSize());476      encoder.AppendData(data_before_op);477      encoder.AppendU8(DW_OP_addr);478      encoder.AppendAddress(file_addr);479      encoder.AppendData(data_after_op);480      m_data.SetData(encoder.GetDataBuffer());481      return true;482    }483    const lldb::offset_t op_arg_size =484        GetOpcodeDataSize(m_data, offset, op, dwarf_cu);485    if (op_arg_size == LLDB_INVALID_OFFSET)486      break;487    offset += op_arg_size;488  }489  return false;490}491 492bool DWARFExpression::ContainsThreadLocalStorage(493    const DWARFExpression::Delegate *dwarf_cu) const {494  lldb::offset_t offset = 0;495  while (m_data.ValidOffset(offset)) {496    const LocationAtom op = static_cast<LocationAtom>(m_data.GetU8(&offset));497 498    if (op == DW_OP_form_tls_address || op == DW_OP_GNU_push_tls_address)499      return true;500    const lldb::offset_t op_arg_size =501        GetOpcodeDataSize(m_data, offset, op, dwarf_cu);502    if (op_arg_size == LLDB_INVALID_OFFSET)503      return false;504    offset += op_arg_size;505  }506  return false;507}508bool DWARFExpression::LinkThreadLocalStorage(509    const DWARFExpression::Delegate *dwarf_cu,510    std::function<lldb::addr_t(lldb::addr_t file_addr)> const511        &link_address_callback) {512  const uint32_t addr_byte_size = m_data.GetAddressByteSize();513  // We have to make a copy of the data as we don't know if this data is from a514  // read only memory mapped buffer, so we duplicate all of the data first,515  // then modify it, and if all goes well, we then replace the data for this516  // expression.517  // Make en encoder that contains a copy of the location expression data so we518  // can write the address into the buffer using the correct byte order.519  DataEncoder encoder(m_data.GetDataStart(), m_data.GetByteSize(),520                      m_data.GetByteOrder(), addr_byte_size);521 522  lldb::offset_t offset = 0;523  lldb::offset_t const_offset = 0;524  lldb::addr_t const_value = 0;525  size_t const_byte_size = 0;526  while (m_data.ValidOffset(offset)) {527    const LocationAtom op = static_cast<LocationAtom>(m_data.GetU8(&offset));528 529    bool decoded_data = false;530    switch (op) {531    case DW_OP_const4u:532      // Remember the const offset in case we later have a533      // DW_OP_form_tls_address or DW_OP_GNU_push_tls_address534      const_offset = offset;535      const_value = m_data.GetU32(&offset);536      decoded_data = true;537      const_byte_size = 4;538      break;539 540    case DW_OP_const8u:541      // Remember the const offset in case we later have a542      // DW_OP_form_tls_address or DW_OP_GNU_push_tls_address543      const_offset = offset;544      const_value = m_data.GetU64(&offset);545      decoded_data = true;546      const_byte_size = 8;547      break;548 549    case DW_OP_form_tls_address:550    case DW_OP_GNU_push_tls_address:551      // DW_OP_form_tls_address and DW_OP_GNU_push_tls_address must be preceded552      // by a file address on the stack. We assume that DW_OP_const4u or553      // DW_OP_const8u is used for these values, and we check that the last554      // opcode we got before either of these was DW_OP_const4u or555      // DW_OP_const8u. If so, then we can link the value accordingly. For556      // Darwin, the value in the DW_OP_const4u or DW_OP_const8u is the file557      // address of a structure that contains a function pointer, the pthread558      // key and the offset into the data pointed to by the pthread key. So we559      // must link this address and also set the module of this expression to560      // the new_module_sp so we can resolve the file address correctly561      if (const_byte_size > 0) {562        lldb::addr_t linked_file_addr = link_address_callback(const_value);563        if (linked_file_addr == LLDB_INVALID_ADDRESS)564          return false;565        // Replace the address in the new buffer566        if (encoder.PutUnsigned(const_offset, const_byte_size,567                                linked_file_addr) == UINT32_MAX)568          return false;569      }570      break;571 572    default:573      const_offset = 0;574      const_value = 0;575      const_byte_size = 0;576      break;577    }578 579    if (!decoded_data) {580      const lldb::offset_t op_arg_size =581          GetOpcodeDataSize(m_data, offset, op, dwarf_cu);582      if (op_arg_size == LLDB_INVALID_OFFSET)583        return false;584      else585        offset += op_arg_size;586    }587  }588 589  m_data.SetData(encoder.GetDataBuffer());590  return true;591}592 593static llvm::Error Evaluate_DW_OP_entry_value(DWARFExpression::Stack &stack,594                                              ExecutionContext *exe_ctx,595                                              RegisterContext *reg_ctx,596                                              const DataExtractor &opcodes,597                                              lldb::offset_t &opcode_offset,598                                              Log *log) {599  // DW_OP_entry_value(sub-expr) describes the location a variable had upon600  // function entry: this variable location is presumed to be optimized out at601  // the current PC value.  The caller of the function may have call site602  // information that describes an alternate location for the variable (e.g. a603  // constant literal, or a spilled stack value) in the parent frame.604  //605  // Example (this is pseudo-code & pseudo-DWARF, but hopefully illustrative):606  //607  //     void child(int &sink, int x) {608  //       ...609  //       /* "x" gets optimized out. */610  //611  //       /* The location of "x" here is: DW_OP_entry_value($reg2). */612  //       ++sink;613  //     }614  //615  //     void parent() {616  //       int sink;617  //618  //       /*619  //        * The callsite information emitted here is:620  //        *621  //        * DW_TAG_call_site622  //        *   DW_AT_return_pc ... (for "child(sink, 123);")623  //        *   DW_TAG_call_site_parameter (for "sink")624  //        *     DW_AT_location   ($reg1)625  //        *     DW_AT_call_value ($SP - 8)626  //        *   DW_TAG_call_site_parameter (for "x")627  //        *     DW_AT_location   ($reg2)628  //        *     DW_AT_call_value ($literal 123)629  //        *630  //        * DW_TAG_call_site631  //        *   DW_AT_return_pc ... (for "child(sink, 456);")632  //        *   ...633  //        */634  //       child(sink, 123);635  //       child(sink, 456);636  //     }637  //638  // When the program stops at "++sink" within `child`, the debugger determines639  // the call site by analyzing the return address. Once the call site is found,640  // the debugger determines which parameter is referenced by DW_OP_entry_value641  // and evaluates the corresponding location for that parameter in `parent`.642 643  // 1. Find the function which pushed the current frame onto the stack.644  if ((!exe_ctx || !exe_ctx->HasTargetScope()) || !reg_ctx) {645    return llvm::createStringError("no exe/reg context");646  }647 648  StackFrame *current_frame = exe_ctx->GetFramePtr();649  Thread *thread = exe_ctx->GetThreadPtr();650  if (!current_frame || !thread)651    return llvm::createStringError("no current frame/thread");652 653  Target &target = exe_ctx->GetTargetRef();654  StackFrameSP parent_frame = nullptr;655  addr_t return_pc = LLDB_INVALID_ADDRESS;656  uint32_t current_frame_idx = current_frame->GetFrameIndex();657 658  for (uint32_t parent_frame_idx = current_frame_idx + 1;; parent_frame_idx++) {659    parent_frame = thread->GetStackFrameAtIndex(parent_frame_idx);660    // If this is null, we're at the end of the stack.661    if (!parent_frame)662      break;663 664    // Record the first valid return address, even if this is an inlined frame,665    // in order to look up the associated call edge in the first non-inlined666    // parent frame.667    if (return_pc == LLDB_INVALID_ADDRESS) {668      return_pc = parent_frame->GetFrameCodeAddress().GetLoadAddress(&target);669      LLDB_LOG(log, "immediate ancestor with pc = {0:x}", return_pc);670    }671 672    // If we've found an inlined frame, skip it (these have no call site673    // parameters).674    if (parent_frame->IsInlined())675      continue;676 677    // We've found the first non-inlined parent frame.678    break;679  }680  if (!parent_frame || !parent_frame->GetRegisterContext()) {681    return llvm::createStringError("no parent frame with reg ctx");682  }683 684  Function *parent_func =685      parent_frame->GetSymbolContext(eSymbolContextFunction).function;686  if (!parent_func)687    return llvm::createStringError("no parent function");688 689  // 2. Find the call edge in the parent function responsible for creating the690  //    current activation.691  Function *current_func =692      current_frame->GetSymbolContext(eSymbolContextFunction).function;693  if (!current_func)694    return llvm::createStringError("no current function");695 696  CallEdge *call_edge = nullptr;697  ModuleList &modlist = target.GetImages();698  ExecutionContext parent_exe_ctx = *exe_ctx;699  parent_exe_ctx.SetFrameSP(parent_frame);700  if (!parent_frame->IsArtificial()) {701    // If the parent frame is not artificial, the current activation may be702    // produced by an ambiguous tail call. In this case, refuse to proceed.703    call_edge = parent_func->GetCallEdgeForReturnAddress(return_pc, target);704    if (!call_edge) {705      return llvm::createStringError(706          llvm::formatv("no call edge for retn-pc = {0:x} in parent frame {1}",707                        return_pc, parent_func->GetName()));708    }709    Function *callee_func = call_edge->GetCallee(modlist, parent_exe_ctx);710    if (callee_func != current_func) {711      return llvm::createStringError(712          "ambiguous call sequence, can't find real parent frame");713    }714  } else {715    // The StackFrameList solver machinery has deduced that an unambiguous tail716    // call sequence that produced the current activation.  The first edge in717    // the parent that points to the current function must be valid.718    for (auto &edge : parent_func->GetTailCallingEdges()) {719      if (edge->GetCallee(modlist, parent_exe_ctx) == current_func) {720        call_edge = edge.get();721        break;722      }723    }724  }725  if (!call_edge)726    return llvm::createStringError("no unambiguous edge from parent "727                                   "to current function");728 729  // 3. Attempt to locate the DW_OP_entry_value expression in the set of730  //    available call site parameters. If found, evaluate the corresponding731  //    parameter in the context of the parent frame.732  const uint32_t subexpr_len = opcodes.GetULEB128(&opcode_offset);733  const void *subexpr_data = opcodes.GetData(&opcode_offset, subexpr_len);734  if (!subexpr_data)735    return llvm::createStringError("subexpr could not be read");736 737  const CallSiteParameter *matched_param = nullptr;738  for (const CallSiteParameter &param : call_edge->GetCallSiteParameters()) {739    DataExtractor param_subexpr_extractor;740    if (!param.LocationInCallee.GetExpressionData(param_subexpr_extractor))741      continue;742    lldb::offset_t param_subexpr_offset = 0;743    const void *param_subexpr_data =744        param_subexpr_extractor.GetData(&param_subexpr_offset, subexpr_len);745    if (!param_subexpr_data ||746        param_subexpr_extractor.BytesLeft(param_subexpr_offset) != 0)747      continue;748 749    // At this point, the DW_OP_entry_value sub-expression and the callee-side750    // expression in the call site parameter are known to have the same length.751    // Check whether they are equal.752    //753    // Note that an equality check is sufficient: the contents of the754    // DW_OP_entry_value subexpression are only used to identify the right call755    // site parameter in the parent, and do not require any special handling.756    if (memcmp(subexpr_data, param_subexpr_data, subexpr_len) == 0) {757      matched_param = &param;758      break;759    }760  }761  if (!matched_param)762    return llvm::createStringError("no matching call site param found");763 764  // TODO: Add support for DW_OP_push_object_address within a DW_OP_entry_value765  // subexpresion whenever llvm does.766  const DWARFExpressionList &param_expr = matched_param->LocationInCaller;767 768  llvm::Expected<Value> maybe_result = param_expr.Evaluate(769      &parent_exe_ctx, parent_frame->GetRegisterContext().get(),770      LLDB_INVALID_ADDRESS,771      /*initial_value_ptr=*/nullptr,772      /*object_address_ptr=*/nullptr);773  if (!maybe_result) {774    LLDB_LOG(log,775             "Evaluate_DW_OP_entry_value: call site param evaluation failed");776    return maybe_result.takeError();777  }778 779  stack.push_back(*maybe_result);780  return llvm::Error::success();781}782 783namespace {784/// The location description kinds described by the DWARF v5785/// specification.  Composite locations are handled out-of-band and786/// thus aren't part of the enum.787enum LocationDescriptionKind {788  Empty,789  Memory,790  Register,791  Implicit792  /* Composite*/793};794/// Adjust value's ValueType according to the kind of location description.795void UpdateValueTypeFromLocationDescription(796    Log *log, const DWARFExpression::Delegate *dwarf_cu,797    LocationDescriptionKind kind, Value *value = nullptr) {798  // Note that this function is conflating DWARF expressions with799  // DWARF location descriptions. Perhaps it would be better to define800  // a wrapper for DWARFExpression::Eval() that deals with DWARF801  // location descriptions (which consist of one or more DWARF802  // expressions). But doing this would mean we'd also need factor the803  // handling of DW_OP_(bit_)piece out of this function.804  if (dwarf_cu && dwarf_cu->GetVersion() >= 4) {805    const char *log_msg = "DWARF location description kind: %s";806    switch (kind) {807    case Empty:808      LLDB_LOGF(log, log_msg, "Empty");809      break;810    case Memory:811      LLDB_LOGF(log, log_msg, "Memory");812      if (value->GetValueType() == Value::ValueType::Scalar)813        value->SetValueType(Value::ValueType::LoadAddress);814      break;815    case Register:816      LLDB_LOGF(log, log_msg, "Register");817      value->SetValueType(Value::ValueType::Scalar);818      break;819    case Implicit:820      LLDB_LOGF(log, log_msg, "Implicit");821      if (value->GetValueType() == Value::ValueType::LoadAddress)822        value->SetValueType(Value::ValueType::Scalar);823      break;824    }825  }826}827} // namespace828 829/// Helper function to move common code used to resolve a file address and turn830/// into a load address.831///832/// \param exe_ctx Pointer to the execution context833/// \param module_sp shared_ptr contains the module if we have one834/// \param dw_op_type C-style string used to vary the error output835/// \param file_addr the file address we are trying to resolve and turn into a836///                  load address837/// \param so_addr out parameter, will be set to load address or section offset838/// \param check_sectionoffset bool which determines if having a section offset839///                            but not a load address is considerd a success840/// \returns std::optional containing the load address if resolving and getting841///          the load address succeed or an empty Optinal otherwise. If842///          check_sectionoffset is true we consider LLDB_INVALID_ADDRESS a843///          success if so_addr.IsSectionOffset() is true.844static llvm::Expected<lldb::addr_t>845ResolveLoadAddress(ExecutionContext *exe_ctx, lldb::ModuleSP &module_sp,846                   const char *dw_op_type, lldb::addr_t file_addr,847                   Address &so_addr, bool check_sectionoffset = false) {848  if (!module_sp)849    return llvm::createStringError("need module to resolve file address for %s",850                                   dw_op_type);851 852  if (!module_sp->ResolveFileAddress(file_addr, so_addr))853    return llvm::createStringError("failed to resolve file address in module");854 855  const addr_t load_addr = so_addr.GetLoadAddress(exe_ctx->GetTargetPtr());856 857  if (load_addr == LLDB_INVALID_ADDRESS &&858      (check_sectionoffset && !so_addr.IsSectionOffset()))859    return llvm::createStringError("failed to resolve load address");860 861  return load_addr;862}863 864/// @brief Helper function to load sized data from a uint8_t buffer.865///866/// @param addr_bytes The buffer containing raw data.867/// @param size_addr_bytes How large is the underlying raw data.868/// @param byte_order What is the byte order of the underlying data.869/// @param size How much of the underlying data we want to use.870/// @return The underlying data converted into a Scalar.871static Scalar DerefSizeExtractDataHelper(uint8_t *addr_bytes,872                                         size_t size_addr_bytes,873                                         ByteOrder byte_order, size_t size) {874  DataExtractor addr_data(addr_bytes, size_addr_bytes, byte_order, size);875 876  lldb::offset_t addr_data_offset = 0;877  if (size <= 8)878    return addr_data.GetMaxU64(&addr_data_offset, size);879  return addr_data.GetAddress(&addr_data_offset);880}881 882static llvm::Error Evaluate_DW_OP_deref_size(DWARFExpression::Stack &stack,883                                             ExecutionContext *exe_ctx,884                                             lldb::ModuleSP module_sp,885                                             Process *process, Target *target,886                                             uint8_t size) {887  if (stack.empty())888    return llvm::createStringError(889        "expression stack empty for DW_OP_deref_size");890 891  if (size > 8)892    return llvm::createStringError(893        "Invalid address size for DW_OP_deref_size: %d\n", size);894 895  Value::ValueType value_type = stack.back().GetValueType();896  switch (value_type) {897  case Value::ValueType::HostAddress: {898    void *src = (void *)stack.back().GetScalar().ULongLong();899    intptr_t ptr;900    ::memcpy(&ptr, src, sizeof(void *));901    // I can't decide whether the size operand should apply to the bytes in902    // their lldb-host endianness or the target endianness.. I doubt this'll903    // ever come up but I'll opt for assuming big endian regardless.904    switch (size) {905    case 1:906      ptr = ptr & 0xff;907      break;908    case 2:909      ptr = ptr & 0xffff;910      break;911    case 3:912      ptr = ptr & 0xffffff;913      break;914    case 4:915      ptr = ptr & 0xffffffff;916      break;917    // The casts are added to work around the case where intptr_t is a 32-bit918    // quantity. Presumably we won't hit the 5..7 cases if (void*) is 32-bits in919    // this program.920    case 5:921      ptr = (intptr_t)ptr & 0xffffffffffULL;922      break;923    case 6:924      ptr = (intptr_t)ptr & 0xffffffffffffULL;925      break;926    case 7:927      ptr = (intptr_t)ptr & 0xffffffffffffffULL;928      break;929    default:930      break;931    }932    stack.back().GetScalar() = ptr;933    stack.back().ClearContext();934  } break;935  case Value::ValueType::FileAddress: {936    auto file_addr = stack.back().GetScalar().ULongLong(LLDB_INVALID_ADDRESS);937    Address so_addr;938    auto maybe_load_addr = ResolveLoadAddress(939        exe_ctx, module_sp, "DW_OP_deref_size", file_addr, so_addr,940        /*check_sectionoffset=*/true);941 942    if (!maybe_load_addr)943      return maybe_load_addr.takeError();944 945    addr_t load_addr = *maybe_load_addr;946 947    if (load_addr == LLDB_INVALID_ADDRESS && so_addr.IsSectionOffset()) {948      uint8_t addr_bytes[8];949      Status error;950 951      if (!target || target->ReadMemory(so_addr, &addr_bytes, size, error,952                                        /*force_live_memory=*/false) != size)953        return llvm::createStringError(954            "failed to dereference pointer for DW_OP_deref_size: "955            "%s\n",956            error.AsCString());957 958      ObjectFile *objfile = module_sp->GetObjectFile();959 960      stack.back().GetScalar() = DerefSizeExtractDataHelper(961          addr_bytes, size, objfile->GetByteOrder(), size);962      stack.back().ClearContext();963      break;964    }965    stack.back().GetScalar() = load_addr;966    // Fall through to load address promotion code below.967  }968 969    [[fallthrough]];970  case Value::ValueType::Scalar:971    // Promote Scalar to LoadAddress and fall through.972    stack.back().SetValueType(Value::ValueType::LoadAddress);973    [[fallthrough]];974  case Value::ValueType::LoadAddress: {975    if (!exe_ctx)976      return llvm::createStringError(977          "no execution context for DW_OP_deref_size");978    if (!process)979      return llvm::createStringError("no process for DW_OP_deref_size");980 981    lldb::addr_t pointer_addr =982        stack.back().GetScalar().ULongLong(LLDB_INVALID_ADDRESS);983    uint8_t addr_bytes[sizeof(lldb::addr_t)];984    Status error;985 986    if (process->ReadMemory(pointer_addr, &addr_bytes, size, error) != size)987      return llvm::createStringError(988          "failed to dereference pointer from 0x%" PRIx64989          " for DW_OP_deref_size: %s\n",990          pointer_addr, error.AsCString());991 992    stack.back().GetScalar() = DerefSizeExtractDataHelper(993        addr_bytes, sizeof(addr_bytes), process->GetByteOrder(), size);994    stack.back().ClearContext();995  } break;996 997  case Value::ValueType::Invalid:998    return llvm::createStringError("invalid value for DW_OP_deref_size");999  }1000 1001  return llvm::Error::success();1002}1003 1004llvm::Expected<Value> DWARFExpression::Evaluate(1005    ExecutionContext *exe_ctx, RegisterContext *reg_ctx,1006    lldb::ModuleSP module_sp, const DataExtractor &opcodes,1007    const DWARFExpression::Delegate *dwarf_cu,1008    const lldb::RegisterKind reg_kind, const Value *initial_value_ptr,1009    const Value *object_address_ptr) {1010 1011  if (opcodes.GetByteSize() == 0)1012    return llvm::createStringError(1013        "no location, value may have been optimized out");1014 1015  Stack stack;1016 1017  Process *process = nullptr;1018  StackFrame *frame = nullptr;1019  Target *target = nullptr;1020 1021  if (exe_ctx) {1022    process = exe_ctx->GetProcessPtr();1023    frame = exe_ctx->GetFramePtr();1024    target = exe_ctx->GetTargetPtr();1025  }1026  if (reg_ctx == nullptr && frame)1027    reg_ctx = frame->GetRegisterContext().get();1028 1029  if (initial_value_ptr)1030    stack.push_back(*initial_value_ptr);1031 1032  lldb::offset_t offset = 0;1033  Value tmp;1034  uint32_t reg_num;1035 1036  /// Insertion point for evaluating multi-piece expression.1037  uint64_t op_piece_offset = 0;1038  Value pieces; // Used for DW_OP_piece1039 1040  Log *log = GetLog(LLDBLog::Expressions);1041  // A generic type is "an integral type that has the size of an address and an1042  // unspecified signedness". For now, just use the signedness of the operand.1043  // TODO: Implement a real typed stack, and store the genericness of the value1044  // there.1045  auto to_generic = [&](auto v) {1046    // TODO: Avoid implicit trunc?1047    // See https://github.com/llvm/llvm-project/issues/112510.1048    bool is_signed = std::is_signed<decltype(v)>::value;1049    return Scalar(llvm::APSInt(llvm::APInt(8 * opcodes.GetAddressByteSize(), v,1050                                           is_signed, /*implicitTrunc=*/true),1051                               !is_signed));1052  };1053 1054  // The default kind is a memory location. This is updated by any1055  // operation that changes this, such as DW_OP_stack_value, and reset1056  // by composition operations like DW_OP_piece.1057  LocationDescriptionKind dwarf4_location_description_kind = Memory;1058 1059  while (opcodes.ValidOffset(offset)) {1060    const lldb::offset_t op_offset = offset;1061    const uint8_t op = opcodes.GetU8(&offset);1062 1063    if (log && log->GetVerbose()) {1064      size_t count = stack.size();1065      LLDB_LOGF(log, "Stack before operation has %" PRIu64 " values:",1066                (uint64_t)count);1067      for (size_t i = 0; i < count; ++i) {1068        StreamString new_value;1069        new_value.Printf("[%" PRIu64 "]", (uint64_t)i);1070        stack[i].Dump(&new_value);1071        LLDB_LOGF(log, "  %s", new_value.GetData());1072      }1073      LLDB_LOGF(log, "0x%8.8" PRIx64 ": %s", op_offset,1074                DW_OP_value_to_name(op));1075    }1076 1077    if (std::optional<unsigned> arity =1078            llvm::dwarf::OperationArity(static_cast<LocationAtom>(op))) {1079      if (stack.size() < *arity)1080        return llvm::createStringError(1081            "%s needs at least %d stack entries (stack has %d entries)",1082            DW_OP_value_to_name(op), *arity, stack.size());1083    }1084 1085    switch (op) {1086    // The DW_OP_addr operation has a single operand that encodes a machine1087    // address and whose size is the size of an address on the target machine.1088    case DW_OP_addr:1089      stack.push_back(Scalar(opcodes.GetAddress(&offset)));1090      if (target &&1091          target->GetArchitecture().GetCore() == ArchSpec::eCore_wasm32) {1092        // wasm file sections aren't mapped into memory, therefore addresses can1093        // never point into a file section and are always LoadAddresses.1094        stack.back().SetValueType(Value::ValueType::LoadAddress);1095      } else {1096        stack.back().SetValueType(Value::ValueType::FileAddress);1097      }1098      break;1099 1100    // The DW_OP_addr_sect_offset4 is used for any location expressions in1101    // shared libraries that have a location like:1102    //  DW_OP_addr(0x1000)1103    // If this address resides in a shared library, then this virtual address1104    // won't make sense when it is evaluated in the context of a running1105    // process where shared libraries have been slid. To account for this, this1106    // new address type where we can store the section pointer and a 4 byte1107    // offset.1108    //      case DW_OP_addr_sect_offset4:1109    //          {1110    //              result_type = eResultTypeFileAddress;1111    //              lldb::Section *sect = (lldb::Section1112    //              *)opcodes.GetMaxU64(&offset, sizeof(void *));1113    //              lldb::addr_t sect_offset = opcodes.GetU32(&offset);1114    //1115    //              Address so_addr (sect, sect_offset);1116    //              lldb::addr_t load_addr = so_addr.GetLoadAddress();1117    //              if (load_addr != LLDB_INVALID_ADDRESS)1118    //              {1119    //                  // We successfully resolve a file address to a load1120    //                  // address.1121    //                  stack.push_back(load_addr);1122    //                  break;1123    //              }1124    //              else1125    //              {1126    //                  // We were able1127    //                  if (error_ptr)1128    //                      error_ptr->SetErrorStringWithFormat ("Section %s in1129    //                      %s is not currently loaded.\n",1130    //                      sect->GetName().AsCString(),1131    //                      sect->GetModule()->GetFileSpec().GetFilename().AsCString());1132    //                  return false;1133    //              }1134    //          }1135    //          break;1136 1137    // OPCODE: DW_OP_deref1138    // OPERANDS: none1139    // DESCRIPTION: Pops the top stack entry and treats it as an address.1140    // The value retrieved from that address is pushed. The size of the data1141    // retrieved from the dereferenced address is the size of an address on the1142    // target machine.1143    case DW_OP_deref: {1144      size_t size = opcodes.GetAddressByteSize();1145      if (llvm::Error err = Evaluate_DW_OP_deref_size(stack, exe_ctx, module_sp,1146                                                      process, target, size))1147        return err;1148    } break;1149 1150    // OPCODE: DW_OP_deref_size1151    // OPERANDS: 11152    //  1 - uint8_t that specifies the size of the data to dereference.1153    // DESCRIPTION: Behaves like the DW_OP_deref operation: it pops the top1154    // stack entry and treats it as an address. The value retrieved from that1155    // address is pushed. In the DW_OP_deref_size operation, however, the size1156    // in bytes of the data retrieved from the dereferenced address is1157    // specified by the single operand. This operand is a 1-byte unsigned1158    // integral constant whose value may not be larger than the size of an1159    // address on the target machine. The data retrieved is zero extended to1160    // the size of an address on the target machine before being pushed on the1161    // expression stack.1162    case DW_OP_deref_size: {1163      size_t size = opcodes.GetU8(&offset);1164      if (llvm::Error err = Evaluate_DW_OP_deref_size(stack, exe_ctx, module_sp,1165                                                      process, target, size))1166        return err;1167    } break;1168 1169    // OPCODE: DW_OP_xderef_size1170    // OPERANDS: 11171    //  1 - uint8_t that specifies the size of the data to dereference.1172    // DESCRIPTION: Behaves like the DW_OP_xderef operation: the entry at1173    // the top of the stack is treated as an address. The second stack entry is1174    // treated as an "address space identifier" for those architectures that1175    // support multiple address spaces. The top two stack elements are popped,1176    // a data item is retrieved through an implementation-defined address1177    // calculation and pushed as the new stack top. In the DW_OP_xderef_size1178    // operation, however, the size in bytes of the data retrieved from the1179    // dereferenced address is specified by the single operand. This operand is1180    // a 1-byte unsigned integral constant whose value may not be larger than1181    // the size of an address on the target machine. The data retrieved is zero1182    // extended to the size of an address on the target machine before being1183    // pushed on the expression stack.1184    case DW_OP_xderef_size:1185      return llvm::createStringError("unimplemented opcode: DW_OP_xderef_size");1186    // OPCODE: DW_OP_xderef1187    // OPERANDS: none1188    // DESCRIPTION: Provides an extended dereference mechanism. The entry at1189    // the top of the stack is treated as an address. The second stack entry is1190    // treated as an "address space identifier" for those architectures that1191    // support multiple address spaces. The top two stack elements are popped,1192    // a data item is retrieved through an implementation-defined address1193    // calculation and pushed as the new stack top. The size of the data1194    // retrieved from the dereferenced address is the size of an address on the1195    // target machine.1196    case DW_OP_xderef:1197      return llvm::createStringError("unimplemented opcode: DW_OP_xderef");1198 1199    // All DW_OP_constXXX opcodes have a single operand as noted below:1200    //1201    // Opcode           Operand 11202    // DW_OP_const1u    1-byte unsigned integer constant1203    // DW_OP_const1s    1-byte signed integer constant1204    // DW_OP_const2u    2-byte unsigned integer constant1205    // DW_OP_const2s    2-byte signed integer constant1206    // DW_OP_const4u    4-byte unsigned integer constant1207    // DW_OP_const4s    4-byte signed integer constant1208    // DW_OP_const8u    8-byte unsigned integer constant1209    // DW_OP_const8s    8-byte signed integer constant1210    // DW_OP_constu     unsigned LEB128 integer constant1211    // DW_OP_consts     signed LEB128 integer constant1212    case DW_OP_const1u:1213      stack.push_back(to_generic(opcodes.GetU8(&offset)));1214      break;1215    case DW_OP_const1s:1216      stack.push_back(to_generic((int8_t)opcodes.GetU8(&offset)));1217      break;1218    case DW_OP_const2u:1219      stack.push_back(to_generic(opcodes.GetU16(&offset)));1220      break;1221    case DW_OP_const2s:1222      stack.push_back(to_generic((int16_t)opcodes.GetU16(&offset)));1223      break;1224    case DW_OP_const4u:1225      stack.push_back(to_generic(opcodes.GetU32(&offset)));1226      break;1227    case DW_OP_const4s:1228      stack.push_back(to_generic((int32_t)opcodes.GetU32(&offset)));1229      break;1230    case DW_OP_const8u:1231      stack.push_back(to_generic(opcodes.GetU64(&offset)));1232      break;1233    case DW_OP_const8s:1234      stack.push_back(to_generic((int64_t)opcodes.GetU64(&offset)));1235      break;1236    // These should also use to_generic, but we can't do that due to a1237    // producer-side bug in llvm. See llvm.org/pr48087.1238    case DW_OP_constu:1239      stack.push_back(Scalar(opcodes.GetULEB128(&offset)));1240      break;1241    case DW_OP_consts:1242      stack.push_back(Scalar(opcodes.GetSLEB128(&offset)));1243      break;1244 1245    // OPCODE: DW_OP_dup1246    // OPERANDS: none1247    // DESCRIPTION: duplicates the value at the top of the stack1248    case DW_OP_dup:1249      if (stack.empty()) {1250        return llvm::createStringError("expression stack empty for DW_OP_dup");1251      } else1252        stack.push_back(stack.back());1253      break;1254 1255    // OPCODE: DW_OP_drop1256    // OPERANDS: none1257    // DESCRIPTION: pops the value at the top of the stack1258    case DW_OP_drop:1259      if (stack.empty()) {1260        return llvm::createStringError("expression stack empty for DW_OP_drop");1261      } else1262        stack.pop_back();1263      break;1264 1265    // OPCODE: DW_OP_over1266    // OPERANDS: none1267    // DESCRIPTION: Duplicates the entry currently second in the stack at1268    // the top of the stack.1269    case DW_OP_over:1270      stack.push_back(stack[stack.size() - 2]);1271      break;1272 1273    // OPCODE: DW_OP_pick1274    // OPERANDS: uint8_t index into the current stack1275    // DESCRIPTION: The stack entry with the specified index (0 through 255,1276    // inclusive) is pushed on the stack1277    case DW_OP_pick: {1278      uint8_t pick_idx = opcodes.GetU8(&offset);1279      if (pick_idx < stack.size())1280        stack.push_back(stack[stack.size() - 1 - pick_idx]);1281      else {1282        return llvm::createStringError(1283            "Index %u out of range for DW_OP_pick.\n", pick_idx);1284      }1285    } break;1286 1287    // OPCODE: DW_OP_swap1288    // OPERANDS: none1289    // DESCRIPTION: swaps the top two stack entries. The entry at the top1290    // of the stack becomes the second stack entry, and the second entry1291    // becomes the top of the stack1292    case DW_OP_swap:1293      tmp = stack.back();1294      stack.back() = stack[stack.size() - 2];1295      stack[stack.size() - 2] = tmp;1296      break;1297 1298    // OPCODE: DW_OP_rot1299    // OPERANDS: none1300    // DESCRIPTION: Rotates the first three stack entries. The entry at1301    // the top of the stack becomes the third stack entry, the second entry1302    // becomes the top of the stack, and the third entry becomes the second1303    // entry.1304    case DW_OP_rot: {1305      size_t last_idx = stack.size() - 1;1306      Value old_top = stack[last_idx];1307      stack[last_idx] = stack[last_idx - 1];1308      stack[last_idx - 1] = stack[last_idx - 2];1309      stack[last_idx - 2] = old_top;1310    } break;1311 1312    // OPCODE: DW_OP_abs1313    // OPERANDS: none1314    // DESCRIPTION: pops the top stack entry, interprets it as a signed1315    // value and pushes its absolute value. If the absolute value can not be1316    // represented, the result is undefined.1317    case DW_OP_abs:1318      if (!stack.back().ResolveValue(exe_ctx).AbsoluteValue()) {1319        return llvm::createStringError(1320            "failed to take the absolute value of the first stack item");1321      }1322      break;1323 1324    // OPCODE: DW_OP_and1325    // OPERANDS: none1326    // DESCRIPTION: pops the top two stack values, performs a bitwise and1327    // operation on the two, and pushes the result.1328    case DW_OP_and:1329      tmp = stack.back();1330      stack.pop_back();1331      stack.back().ResolveValue(exe_ctx) =1332          stack.back().ResolveValue(exe_ctx) & tmp.ResolveValue(exe_ctx);1333      break;1334 1335    // OPCODE: DW_OP_div1336    // OPERANDS: none1337    // DESCRIPTION: pops the top two stack values, divides the former second1338    // entry by the former top of the stack using signed division, and pushes1339    // the result.1340    case DW_OP_div: {1341      tmp = stack.back();1342      if (tmp.ResolveValue(exe_ctx).IsZero())1343        return llvm::createStringError("divide by zero");1344 1345      stack.pop_back();1346      Scalar divisor, dividend;1347      divisor = tmp.ResolveValue(exe_ctx);1348      dividend = stack.back().ResolveValue(exe_ctx);1349      divisor.MakeSigned();1350      dividend.MakeSigned();1351      stack.back() = dividend / divisor;1352 1353      if (!stack.back().ResolveValue(exe_ctx).IsValid())1354        return llvm::createStringError("divide failed");1355    } break;1356 1357    // OPCODE: DW_OP_minus1358    // OPERANDS: none1359    // DESCRIPTION: pops the top two stack values, subtracts the former top1360    // of the stack from the former second entry, and pushes the result.1361    case DW_OP_minus:1362      tmp = stack.back();1363      stack.pop_back();1364      stack.back().ResolveValue(exe_ctx) =1365          stack.back().ResolveValue(exe_ctx) - tmp.ResolveValue(exe_ctx);1366      break;1367 1368    // OPCODE: DW_OP_mod1369    // OPERANDS: none1370    // DESCRIPTION: pops the top two stack values and pushes the result of1371    // the calculation: former second stack entry modulo the former top of the1372    // stack.1373    case DW_OP_mod:1374      tmp = stack.back();1375      stack.pop_back();1376      stack.back().ResolveValue(exe_ctx) =1377          stack.back().ResolveValue(exe_ctx) % tmp.ResolveValue(exe_ctx);1378      break;1379 1380    // OPCODE: DW_OP_mul1381    // OPERANDS: none1382    // DESCRIPTION: pops the top two stack entries, multiplies them1383    // together, and pushes the result.1384    case DW_OP_mul:1385      tmp = stack.back();1386      stack.pop_back();1387      stack.back().ResolveValue(exe_ctx) =1388          stack.back().ResolveValue(exe_ctx) * tmp.ResolveValue(exe_ctx);1389      break;1390 1391    // OPCODE: DW_OP_neg1392    // OPERANDS: none1393    // DESCRIPTION: pops the top stack entry, and pushes its negation.1394    case DW_OP_neg:1395      if (!stack.back().ResolveValue(exe_ctx).UnaryNegate())1396        return llvm::createStringError("unary negate failed");1397      break;1398 1399    // OPCODE: DW_OP_not1400    // OPERANDS: none1401    // DESCRIPTION: pops the top stack entry, and pushes its bitwise1402    // complement1403    case DW_OP_not:1404      if (!stack.back().ResolveValue(exe_ctx).OnesComplement())1405        return llvm::createStringError("logical NOT failed");1406      break;1407 1408    // OPCODE: DW_OP_or1409    // OPERANDS: none1410    // DESCRIPTION: pops the top two stack entries, performs a bitwise or1411    // operation on the two, and pushes the result.1412    case DW_OP_or:1413      tmp = stack.back();1414      stack.pop_back();1415      stack.back().ResolveValue(exe_ctx) =1416          stack.back().ResolveValue(exe_ctx) | tmp.ResolveValue(exe_ctx);1417      break;1418 1419    // OPCODE: DW_OP_plus1420    // OPERANDS: none1421    // DESCRIPTION: pops the top two stack entries, adds them together, and1422    // pushes the result.1423    case DW_OP_plus:1424      tmp = stack.back();1425      stack.pop_back();1426      stack.back().GetScalar() += tmp.GetScalar();1427      break;1428 1429    // OPCODE: DW_OP_plus_uconst1430    // OPERANDS: none1431    // DESCRIPTION: pops the top stack entry, adds it to the unsigned LEB1281432    // constant operand and pushes the result.1433    case DW_OP_plus_uconst: {1434      const uint64_t uconst_value = opcodes.GetULEB128(&offset);1435      // Implicit conversion from a UINT to a Scalar...1436      stack.back().GetScalar() += uconst_value;1437      if (!stack.back().GetScalar().IsValid())1438        return llvm::createStringError("DW_OP_plus_uconst failed");1439    } break;1440 1441    // OPCODE: DW_OP_shl1442    // OPERANDS: none1443    // DESCRIPTION:  pops the top two stack entries, shifts the former1444    // second entry left by the number of bits specified by the former top of1445    // the stack, and pushes the result.1446    case DW_OP_shl:1447      tmp = stack.back();1448      stack.pop_back();1449      stack.back().ResolveValue(exe_ctx) <<= tmp.ResolveValue(exe_ctx);1450      break;1451 1452    // OPCODE: DW_OP_shr1453    // OPERANDS: none1454    // DESCRIPTION: pops the top two stack entries, shifts the former second1455    // entry right logically (filling with zero bits) by the number of bits1456    // specified by the former top of the stack, and pushes the result.1457    case DW_OP_shr:1458      tmp = stack.back();1459      stack.pop_back();1460      if (!stack.back().ResolveValue(exe_ctx).ShiftRightLogical(1461              tmp.ResolveValue(exe_ctx)))1462        return llvm::createStringError("DW_OP_shr failed");1463      break;1464 1465    // OPCODE: DW_OP_shra1466    // OPERANDS: none1467    // DESCRIPTION: pops the top two stack entries, shifts the former second1468    // entry right arithmetically (divide the magnitude by 2, keep the same1469    // sign for the result) by the number of bits specified by the former top1470    // of the stack, and pushes the result.1471    case DW_OP_shra:1472      tmp = stack.back();1473      stack.pop_back();1474      stack.back().ResolveValue(exe_ctx) >>= tmp.ResolveValue(exe_ctx);1475      break;1476 1477    // OPCODE: DW_OP_xor1478    // OPERANDS: none1479    // DESCRIPTION: pops the top two stack entries, performs the bitwise1480    // exclusive-or operation on the two, and pushes the result.1481    case DW_OP_xor:1482      tmp = stack.back();1483      stack.pop_back();1484      stack.back().ResolveValue(exe_ctx) =1485          stack.back().ResolveValue(exe_ctx) ^ tmp.ResolveValue(exe_ctx);1486      break;1487 1488    // OPCODE: DW_OP_skip1489    // OPERANDS: int16_t1490    // DESCRIPTION:  An unconditional branch. Its single operand is a 2-byte1491    // signed integer constant. The 2-byte constant is the number of bytes of1492    // the DWARF expression to skip forward or backward from the current1493    // operation, beginning after the 2-byte constant.1494    case DW_OP_skip: {1495      int16_t skip_offset = (int16_t)opcodes.GetU16(&offset);1496      lldb::offset_t new_offset = offset + skip_offset;1497      // New offset can point at the end of the data, in this case we should1498      // terminate the DWARF expression evaluation (will happen in the loop1499      // condition).1500      if (new_offset <= opcodes.GetByteSize())1501        offset = new_offset;1502      else {1503        return llvm::createStringError(llvm::formatv(1504            "Invalid opcode offset in DW_OP_skip: {0}+({1}) > {2}", offset,1505            skip_offset, opcodes.GetByteSize()));1506      }1507    } break;1508 1509    // OPCODE: DW_OP_bra1510    // OPERANDS: int16_t1511    // DESCRIPTION: A conditional branch. Its single operand is a 2-byte1512    // signed integer constant. This operation pops the top of stack. If the1513    // value popped is not the constant 0, the 2-byte constant operand is the1514    // number of bytes of the DWARF expression to skip forward or backward from1515    // the current operation, beginning after the 2-byte constant.1516    case DW_OP_bra: {1517      tmp = stack.back();1518      stack.pop_back();1519      int16_t bra_offset = (int16_t)opcodes.GetU16(&offset);1520      Scalar zero(0);1521      if (tmp.ResolveValue(exe_ctx) != zero) {1522        lldb::offset_t new_offset = offset + bra_offset;1523        // New offset can point at the end of the data, in this case we should1524        // terminate the DWARF expression evaluation (will happen in the loop1525        // condition).1526        if (new_offset <= opcodes.GetByteSize())1527          offset = new_offset;1528        else {1529          return llvm::createStringError(llvm::formatv(1530              "Invalid opcode offset in DW_OP_bra: {0}+({1}) > {2}", offset,1531              bra_offset, opcodes.GetByteSize()));1532        }1533      }1534    } break;1535 1536    // OPCODE: DW_OP_eq1537    // OPERANDS: none1538    // DESCRIPTION: pops the top two stack values, compares using the1539    // equals (==) operator.1540    // STACK RESULT: push the constant value 1 onto the stack if the result1541    // of the operation is true or the constant value 0 if the result of the1542    // operation is false.1543    case DW_OP_eq:1544      tmp = stack.back();1545      stack.pop_back();1546      stack.back().ResolveValue(exe_ctx) =1547          stack.back().ResolveValue(exe_ctx) == tmp.ResolveValue(exe_ctx);1548      break;1549 1550    // OPCODE: DW_OP_ge1551    // OPERANDS: none1552    // DESCRIPTION: pops the top two stack values, compares using the1553    // greater than or equal to (>=) operator.1554    // STACK RESULT: push the constant value 1 onto the stack if the result1555    // of the operation is true or the constant value 0 if the result of the1556    // operation is false.1557    case DW_OP_ge:1558      tmp = stack.back();1559      stack.pop_back();1560      stack.back().ResolveValue(exe_ctx) =1561          stack.back().ResolveValue(exe_ctx) >= tmp.ResolveValue(exe_ctx);1562      break;1563 1564    // OPCODE: DW_OP_gt1565    // OPERANDS: none1566    // DESCRIPTION: pops the top two stack values, compares using the1567    // greater than (>) operator.1568    // STACK RESULT: push the constant value 1 onto the stack if the result1569    // of the operation is true or the constant value 0 if the result of the1570    // operation is false.1571    case DW_OP_gt:1572      tmp = stack.back();1573      stack.pop_back();1574      stack.back().ResolveValue(exe_ctx) =1575          stack.back().ResolveValue(exe_ctx) > tmp.ResolveValue(exe_ctx);1576      break;1577 1578    // OPCODE: DW_OP_le1579    // OPERANDS: none1580    // DESCRIPTION: pops the top two stack values, compares using the1581    // less than or equal to (<=) operator.1582    // STACK RESULT: push the constant value 1 onto the stack if the result1583    // of the operation is true or the constant value 0 if the result of the1584    // operation is false.1585    case DW_OP_le:1586      tmp = stack.back();1587      stack.pop_back();1588      stack.back().ResolveValue(exe_ctx) =1589          stack.back().ResolveValue(exe_ctx) <= tmp.ResolveValue(exe_ctx);1590      break;1591 1592    // OPCODE: DW_OP_lt1593    // OPERANDS: none1594    // DESCRIPTION: pops the top two stack values, compares using the1595    // less than (<) operator.1596    // STACK RESULT: push the constant value 1 onto the stack if the result1597    // of the operation is true or the constant value 0 if the result of the1598    // operation is false.1599    case DW_OP_lt:1600      tmp = stack.back();1601      stack.pop_back();1602      stack.back().ResolveValue(exe_ctx) =1603          stack.back().ResolveValue(exe_ctx) < tmp.ResolveValue(exe_ctx);1604      break;1605 1606    // OPCODE: DW_OP_ne1607    // OPERANDS: none1608    // DESCRIPTION: pops the top two stack values, compares using the1609    // not equal (!=) operator.1610    // STACK RESULT: push the constant value 1 onto the stack if the result1611    // of the operation is true or the constant value 0 if the result of the1612    // operation is false.1613    case DW_OP_ne:1614      tmp = stack.back();1615      stack.pop_back();1616      stack.back().ResolveValue(exe_ctx) =1617          stack.back().ResolveValue(exe_ctx) != tmp.ResolveValue(exe_ctx);1618      break;1619 1620    // OPCODE: DW_OP_litn1621    // OPERANDS: none1622    // DESCRIPTION: encode the unsigned literal values from 0 through 31.1623    // STACK RESULT: push the unsigned literal constant value onto the top1624    // of the stack.1625    case DW_OP_lit0:1626    case DW_OP_lit1:1627    case DW_OP_lit2:1628    case DW_OP_lit3:1629    case DW_OP_lit4:1630    case DW_OP_lit5:1631    case DW_OP_lit6:1632    case DW_OP_lit7:1633    case DW_OP_lit8:1634    case DW_OP_lit9:1635    case DW_OP_lit10:1636    case DW_OP_lit11:1637    case DW_OP_lit12:1638    case DW_OP_lit13:1639    case DW_OP_lit14:1640    case DW_OP_lit15:1641    case DW_OP_lit16:1642    case DW_OP_lit17:1643    case DW_OP_lit18:1644    case DW_OP_lit19:1645    case DW_OP_lit20:1646    case DW_OP_lit21:1647    case DW_OP_lit22:1648    case DW_OP_lit23:1649    case DW_OP_lit24:1650    case DW_OP_lit25:1651    case DW_OP_lit26:1652    case DW_OP_lit27:1653    case DW_OP_lit28:1654    case DW_OP_lit29:1655    case DW_OP_lit30:1656    case DW_OP_lit31:1657      stack.push_back(to_generic(op - DW_OP_lit0));1658      break;1659 1660    // OPCODE: DW_OP_regN1661    // OPERANDS: none1662    // DESCRIPTION: Push the value in register n on the top of the stack.1663    case DW_OP_reg0:1664    case DW_OP_reg1:1665    case DW_OP_reg2:1666    case DW_OP_reg3:1667    case DW_OP_reg4:1668    case DW_OP_reg5:1669    case DW_OP_reg6:1670    case DW_OP_reg7:1671    case DW_OP_reg8:1672    case DW_OP_reg9:1673    case DW_OP_reg10:1674    case DW_OP_reg11:1675    case DW_OP_reg12:1676    case DW_OP_reg13:1677    case DW_OP_reg14:1678    case DW_OP_reg15:1679    case DW_OP_reg16:1680    case DW_OP_reg17:1681    case DW_OP_reg18:1682    case DW_OP_reg19:1683    case DW_OP_reg20:1684    case DW_OP_reg21:1685    case DW_OP_reg22:1686    case DW_OP_reg23:1687    case DW_OP_reg24:1688    case DW_OP_reg25:1689    case DW_OP_reg26:1690    case DW_OP_reg27:1691    case DW_OP_reg28:1692    case DW_OP_reg29:1693    case DW_OP_reg30:1694    case DW_OP_reg31: {1695      dwarf4_location_description_kind = Register;1696      reg_num = op - DW_OP_reg0;1697 1698      if (llvm::Error err =1699              ReadRegisterValueAsScalar(reg_ctx, reg_kind, reg_num, tmp))1700        return err;1701      stack.push_back(tmp);1702    } break;1703    // OPCODE: DW_OP_regx1704    // OPERANDS:1705    //      ULEB128 literal operand that encodes the register.1706    // DESCRIPTION: Push the value in register on the top of the stack.1707    case DW_OP_regx: {1708      dwarf4_location_description_kind = Register;1709      reg_num = opcodes.GetULEB128(&offset);1710      Status read_err;1711      if (llvm::Error err =1712              ReadRegisterValueAsScalar(reg_ctx, reg_kind, reg_num, tmp))1713        return err;1714      stack.push_back(tmp);1715    } break;1716 1717    // OPCODE: DW_OP_bregN1718    // OPERANDS:1719    //      SLEB128 offset from register N1720    // DESCRIPTION: Value is in memory at the address specified by register1721    // N plus an offset.1722    case DW_OP_breg0:1723    case DW_OP_breg1:1724    case DW_OP_breg2:1725    case DW_OP_breg3:1726    case DW_OP_breg4:1727    case DW_OP_breg5:1728    case DW_OP_breg6:1729    case DW_OP_breg7:1730    case DW_OP_breg8:1731    case DW_OP_breg9:1732    case DW_OP_breg10:1733    case DW_OP_breg11:1734    case DW_OP_breg12:1735    case DW_OP_breg13:1736    case DW_OP_breg14:1737    case DW_OP_breg15:1738    case DW_OP_breg16:1739    case DW_OP_breg17:1740    case DW_OP_breg18:1741    case DW_OP_breg19:1742    case DW_OP_breg20:1743    case DW_OP_breg21:1744    case DW_OP_breg22:1745    case DW_OP_breg23:1746    case DW_OP_breg24:1747    case DW_OP_breg25:1748    case DW_OP_breg26:1749    case DW_OP_breg27:1750    case DW_OP_breg28:1751    case DW_OP_breg29:1752    case DW_OP_breg30:1753    case DW_OP_breg31: {1754      reg_num = op - DW_OP_breg0;1755      if (llvm::Error err =1756              ReadRegisterValueAsScalar(reg_ctx, reg_kind, reg_num, tmp))1757        return err;1758 1759      int64_t breg_offset = opcodes.GetSLEB128(&offset);1760      tmp.ResolveValue(exe_ctx) += (uint64_t)breg_offset;1761      tmp.ClearContext();1762      stack.push_back(tmp);1763      stack.back().SetValueType(Value::ValueType::LoadAddress);1764    } break;1765    // OPCODE: DW_OP_bregx1766    // OPERANDS: 21767    //      ULEB128 literal operand that encodes the register.1768    //      SLEB128 offset from register N1769    // DESCRIPTION: Value is in memory at the address specified by register1770    // N plus an offset.1771    case DW_OP_bregx: {1772      reg_num = opcodes.GetULEB128(&offset);1773      if (llvm::Error err =1774              ReadRegisterValueAsScalar(reg_ctx, reg_kind, reg_num, tmp))1775        return err;1776 1777      int64_t breg_offset = opcodes.GetSLEB128(&offset);1778      tmp.ResolveValue(exe_ctx) += (uint64_t)breg_offset;1779      tmp.ClearContext();1780      stack.push_back(tmp);1781      stack.back().SetValueType(Value::ValueType::LoadAddress);1782    } break;1783 1784    case DW_OP_fbreg:1785      if (exe_ctx) {1786        if (frame) {1787          Scalar value;1788          if (llvm::Error err = frame->GetFrameBaseValue(value))1789            return err;1790          int64_t fbreg_offset = opcodes.GetSLEB128(&offset);1791          value += fbreg_offset;1792          stack.push_back(value);1793          stack.back().SetValueType(Value::ValueType::LoadAddress);1794        } else {1795          return llvm::createStringError(1796              "invalid stack frame in context for DW_OP_fbreg opcode");1797        }1798      } else {1799        return llvm::createStringError(1800            "NULL execution context for DW_OP_fbreg");1801      }1802 1803      break;1804 1805    // OPCODE: DW_OP_nop1806    // OPERANDS: none1807    // DESCRIPTION: A place holder. It has no effect on the location stack1808    // or any of its values.1809    case DW_OP_nop:1810      break;1811 1812    // OPCODE: DW_OP_piece1813    // OPERANDS: 11814    //      ULEB128: byte size of the piece1815    // DESCRIPTION: The operand describes the size in bytes of the piece of1816    // the object referenced by the DWARF expression whose result is at the top1817    // of the stack. If the piece is located in a register, but does not occupy1818    // the entire register, the placement of the piece within that register is1819    // defined by the ABI.1820    //1821    // Many compilers store a single variable in sets of registers, or store a1822    // variable partially in memory and partially in registers. DW_OP_piece1823    // provides a way of describing how large a part of a variable a particular1824    // DWARF expression refers to.1825    case DW_OP_piece: {1826      LocationDescriptionKind piece_locdesc = dwarf4_location_description_kind;1827      // Reset for the next piece.1828      dwarf4_location_description_kind = Memory;1829 1830      const uint64_t piece_byte_size = opcodes.GetULEB128(&offset);1831 1832      if (piece_byte_size > 0) {1833        Value curr_piece;1834 1835        if (stack.empty()) {1836          UpdateValueTypeFromLocationDescription(1837              log, dwarf_cu, LocationDescriptionKind::Empty);1838          // In a multi-piece expression, this means that the current piece is1839          // not available. Fill with zeros for now by resizing the data and1840          // appending it1841          curr_piece.ResizeData(piece_byte_size);1842          // Note that "0" is not a correct value for the unknown bits.1843          // It would be better to also return a mask of valid bits together1844          // with the expression result, so the debugger can print missing1845          // members as "<optimized out>" or something.1846          ::memset(curr_piece.GetBuffer().GetBytes(), 0, piece_byte_size);1847          pieces.AppendDataToHostBuffer(curr_piece);1848        } else {1849          Status error;1850          // Extract the current piece into "curr_piece"1851          Value curr_piece_source_value(stack.back());1852          stack.pop_back();1853          UpdateValueTypeFromLocationDescription(log, dwarf_cu, piece_locdesc,1854                                                 &curr_piece_source_value);1855 1856          const Value::ValueType curr_piece_source_value_type =1857              curr_piece_source_value.GetValueType();1858          Scalar &scalar = curr_piece_source_value.GetScalar();1859          lldb::addr_t addr = scalar.ULongLong(LLDB_INVALID_ADDRESS);1860          switch (curr_piece_source_value_type) {1861          case Value::ValueType::Invalid:1862            return llvm::createStringError("invalid value type");1863          case Value::ValueType::FileAddress:1864            if (target) {1865              curr_piece_source_value.ConvertToLoadAddress(module_sp.get(),1866                                                           target);1867              addr = scalar.ULongLong(LLDB_INVALID_ADDRESS);1868            } else {1869              return llvm::createStringError(1870                  "unable to convert file address 0x%" PRIx641871                  " to load address "1872                  "for DW_OP_piece(%" PRIu64 "): "1873                  "no target available",1874                  addr, piece_byte_size);1875            }1876            [[fallthrough]];1877          case Value::ValueType::LoadAddress: {1878            if (target) {1879              if (curr_piece.ResizeData(piece_byte_size) == piece_byte_size) {1880                if (target->ReadMemory(addr, curr_piece.GetBuffer().GetBytes(),1881                                       piece_byte_size, error,1882                                       /*force_live_memory=*/false) !=1883                    piece_byte_size) {1884                  const char *addr_type = (curr_piece_source_value_type ==1885                                           Value::ValueType::LoadAddress)1886                                              ? "load"1887                                              : "file";1888                  return llvm::createStringError(1889                      "failed to read memory DW_OP_piece(%" PRIu641890                      ") from %s address 0x%" PRIx64,1891                      piece_byte_size, addr_type, addr);1892                }1893              } else {1894                return llvm::createStringError(1895                    "failed to resize the piece memory buffer for "1896                    "DW_OP_piece(%" PRIu64 ")",1897                    piece_byte_size);1898              }1899            }1900          } break;1901          case Value::ValueType::HostAddress: {1902            return llvm::createStringError(1903                "failed to read memory DW_OP_piece(%" PRIu641904                ") from host address 0x%" PRIx64,1905                piece_byte_size, addr);1906          } break;1907 1908          case Value::ValueType::Scalar: {1909            uint32_t bit_size = piece_byte_size * 8;1910            uint32_t bit_offset = 0;1911            if (!scalar.ExtractBitfield(bit_size, bit_offset)) {1912              return llvm::createStringError(1913                  "unable to extract %" PRIu64 " bytes from a %" PRIu641914                  " byte scalar value.",1915                  piece_byte_size,1916                  (uint64_t)curr_piece_source_value.GetScalar().GetByteSize());1917            }1918 1919            // We have seen a case where we have expression like:1920            //      DW_OP_lit0, DW_OP_stack_value, DW_OP_piece 0x281921            // here we are assuming the compiler was trying to zero1922            // extend the value that we should append to the buffer.1923            scalar.TruncOrExtendTo(bit_size, /*sign=*/false);1924            curr_piece.GetScalar() = scalar;1925          } break;1926          }1927 1928          // Check if this is the first piece?1929          if (op_piece_offset == 0) {1930            // This is the first piece, we should push it back onto the stack1931            // so subsequent pieces will be able to access this piece and add1932            // to it.1933            if (pieces.AppendDataToHostBuffer(curr_piece) == 0) {1934              return llvm::createStringError("failed to append piece data");1935            }1936          } else {1937            // If this is the second or later piece there should be a value on1938            // the stack.1939            if (pieces.GetBuffer().GetByteSize() != op_piece_offset) {1940              return llvm::createStringError(1941                  "DW_OP_piece for offset %" PRIu641942                  " but top of stack is of size %" PRIu64,1943                  op_piece_offset, pieces.GetBuffer().GetByteSize());1944            }1945 1946            if (pieces.AppendDataToHostBuffer(curr_piece) == 0)1947              return llvm::createStringError("failed to append piece data");1948          }1949        }1950        op_piece_offset += piece_byte_size;1951      }1952    } break;1953 1954    case DW_OP_bit_piece: // 0x9d ULEB128 bit size, ULEB128 bit offset (DWARF3);1955      if (stack.size() < 1) {1956        UpdateValueTypeFromLocationDescription(log, dwarf_cu,1957                                               LocationDescriptionKind::Empty);1958        // Reset for the next piece.1959        dwarf4_location_description_kind = Memory;1960        return llvm::createStringError(1961            "expression stack needs at least 1 item for DW_OP_bit_piece");1962      } else {1963        UpdateValueTypeFromLocationDescription(1964            log, dwarf_cu, dwarf4_location_description_kind, &stack.back());1965        // Reset for the next piece.1966        dwarf4_location_description_kind = Memory;1967        const uint64_t piece_bit_size = opcodes.GetULEB128(&offset);1968        const uint64_t piece_bit_offset = opcodes.GetULEB128(&offset);1969        switch (stack.back().GetValueType()) {1970        case Value::ValueType::Invalid:1971          return llvm::createStringError(1972              "unable to extract bit value from invalid value");1973        case Value::ValueType::Scalar: {1974          if (!stack.back().GetScalar().ExtractBitfield(piece_bit_size,1975                                                        piece_bit_offset)) {1976            return llvm::createStringError(1977                "unable to extract %" PRIu64 " bit value with %" PRIu641978                " bit offset from a %" PRIu64 " bit scalar value.",1979                piece_bit_size, piece_bit_offset,1980                (uint64_t)(stack.back().GetScalar().GetByteSize() * 8));1981          }1982        } break;1983 1984        case Value::ValueType::FileAddress:1985        case Value::ValueType::LoadAddress:1986        case Value::ValueType::HostAddress:1987          return llvm::createStringError(1988              "unable to extract DW_OP_bit_piece(bit_size = %" PRIu641989              ", bit_offset = %" PRIu64 ") from an address value.",1990              piece_bit_size, piece_bit_offset);1991        }1992      }1993      break;1994 1995    // OPCODE: DW_OP_implicit_value1996    // OPERANDS: 21997    //      ULEB128  size of the value block in bytes1998    //      uint8_t* block bytes encoding value in target's memory1999    //      representation2000    // DESCRIPTION: Value is immediately stored in block in the debug info with2001    // the memory representation of the target.2002    case DW_OP_implicit_value: {2003      dwarf4_location_description_kind = Implicit;2004 2005      const uint32_t len = opcodes.GetULEB128(&offset);2006      const void *data = opcodes.GetData(&offset, len);2007 2008      if (!data) {2009        LLDB_LOG(log, "Evaluate_DW_OP_implicit_value: could not be read data");2010        return llvm::createStringError("could not evaluate %s",2011                                       DW_OP_value_to_name(op));2012      }2013 2014      Value result(data, len);2015      stack.push_back(result);2016      break;2017    }2018 2019    case DW_OP_implicit_pointer: {2020      dwarf4_location_description_kind = Implicit;2021      return llvm::createStringError("could not evaluate %s",2022                                     DW_OP_value_to_name(op));2023    }2024 2025    // OPCODE: DW_OP_push_object_address2026    // OPERANDS: none2027    // DESCRIPTION: Pushes the address of the object currently being2028    // evaluated as part of evaluation of a user presented expression. This2029    // object may correspond to an independent variable described by its own2030    // DIE or it may be a component of an array, structure, or class whose2031    // address has been dynamically determined by an earlier step during user2032    // expression evaluation.2033    case DW_OP_push_object_address:2034      if (object_address_ptr)2035        stack.push_back(*object_address_ptr);2036      else {2037        return llvm::createStringError("DW_OP_push_object_address used without "2038                                       "specifying an object address");2039      }2040      break;2041 2042    // OPCODE: DW_OP_call22043    // OPERANDS:2044    //      uint16_t compile unit relative offset of a DIE2045    // DESCRIPTION: Performs subroutine calls during evaluation2046    // of a DWARF expression. The operand is the 2-byte unsigned offset of a2047    // debugging information entry in the current compilation unit.2048    //2049    // Operand interpretation is exactly like that for DW_FORM_ref2.2050    //2051    // This operation transfers control of DWARF expression evaluation to the2052    // DW_AT_location attribute of the referenced DIE. If there is no such2053    // attribute, then there is no effect. Execution of the DWARF expression of2054    // a DW_AT_location attribute may add to and/or remove from values on the2055    // stack. Execution returns to the point following the call when the end of2056    // the attribute is reached. Values on the stack at the time of the call2057    // may be used as parameters by the called expression and values left on2058    // the stack by the called expression may be used as return values by prior2059    // agreement between the calling and called expressions.2060    case DW_OP_call2:2061      return llvm::createStringError("unimplemented opcode DW_OP_call2");2062    // OPCODE: DW_OP_call42063    // OPERANDS: 12064    //      uint32_t compile unit relative offset of a DIE2065    // DESCRIPTION: Performs a subroutine call during evaluation of a DWARF2066    // expression. For DW_OP_call4, the operand is a 4-byte unsigned offset of2067    // a debugging information entry in  the current compilation unit.2068    //2069    // Operand interpretation DW_OP_call4 is exactly like that for2070    // DW_FORM_ref4.2071    //2072    // This operation transfers control of DWARF expression evaluation to the2073    // DW_AT_location attribute of the referenced DIE. If there is no such2074    // attribute, then there is no effect. Execution of the DWARF expression of2075    // a DW_AT_location attribute may add to and/or remove from values on the2076    // stack. Execution returns to the point following the call when the end of2077    // the attribute is reached. Values on the stack at the time of the call2078    // may be used as parameters by the called expression and values left on2079    // the stack by the called expression may be used as return values by prior2080    // agreement between the calling and called expressions.2081    case DW_OP_call4:2082      return llvm::createStringError("unimplemented opcode DW_OP_call4");2083 2084    // OPCODE: DW_OP_stack_value2085    // OPERANDS: None2086    // DESCRIPTION: Specifies that the object does not exist in memory but2087    // rather is a constant value.  The value from the top of the stack is the2088    // value to be used.  This is the actual object value and not the location.2089    case DW_OP_stack_value:2090      dwarf4_location_description_kind = Implicit;2091      stack.back().SetValueType(Value::ValueType::Scalar);2092      break;2093 2094    // OPCODE: DW_OP_convert2095    // OPERANDS: 12096    //      A ULEB128 that is either a DIE offset of a2097    //      DW_TAG_base_type or 0 for the generic (pointer-sized) type.2098    //2099    // DESCRIPTION: Pop the top stack element, convert it to a2100    // different type, and push the result.2101    case DW_OP_convert: {2102      const uint64_t relative_die_offset = opcodes.GetULEB128(&offset);2103      uint64_t bit_size;2104      bool sign;2105      if (relative_die_offset == 0) {2106        // The generic type has the size of an address on the target2107        // machine and an unspecified signedness. Scalar has no2108        // "unspecified signedness", so we use unsigned types.2109        if (!module_sp)2110          return llvm::createStringError("no module");2111        sign = false;2112        bit_size = module_sp->GetArchitecture().GetAddressByteSize() * 8;2113        if (!bit_size)2114          return llvm::createStringError("unspecified architecture");2115      } else {2116        auto bit_size_sign_or_err =2117            dwarf_cu->GetDIEBitSizeAndSign(relative_die_offset);2118        if (!bit_size_sign_or_err)2119          return bit_size_sign_or_err.takeError();2120        bit_size = bit_size_sign_or_err->first;2121        sign = bit_size_sign_or_err->second;2122      }2123      Scalar &top = stack.back().ResolveValue(exe_ctx);2124      top.TruncOrExtendTo(bit_size, sign);2125      break;2126    }2127 2128    // OPCODE: DW_OP_call_frame_cfa2129    // OPERANDS: None2130    // DESCRIPTION: Specifies a DWARF expression that pushes the value of2131    // the canonical frame address consistent with the call frame information2132    // located in .debug_frame (or in the FDEs of the eh_frame section).2133    case DW_OP_call_frame_cfa:2134      if (frame) {2135        // Note that we don't have to parse FDEs because this DWARF expression2136        // is commonly evaluated with a valid stack frame.2137        StackID id = frame->GetStackID();2138        addr_t cfa = id.GetCallFrameAddressWithMetadata();2139        if (cfa != LLDB_INVALID_ADDRESS) {2140          stack.push_back(Scalar(cfa));2141          stack.back().SetValueType(Value::ValueType::LoadAddress);2142        } else {2143          return llvm::createStringError(2144              "stack frame does not include a canonical "2145              "frame address for DW_OP_call_frame_cfa "2146              "opcode");2147        }2148      } else {2149        return llvm::createStringError("unvalid stack frame in context for "2150                                       "DW_OP_call_frame_cfa opcode");2151      }2152      break;2153 2154    // OPCODE: DW_OP_form_tls_address (or the old pre-DWARFv3 vendor extension2155    // opcode, DW_OP_GNU_push_tls_address)2156    // OPERANDS: none2157    // DESCRIPTION: Pops a TLS offset from the stack, converts it to2158    // an address in the current thread's thread-local storage block, and2159    // pushes it on the stack.2160    case DW_OP_form_tls_address:2161    case DW_OP_GNU_push_tls_address: {2162      if (stack.size() < 1) {2163        if (op == DW_OP_form_tls_address)2164          return llvm::createStringError(2165              "DW_OP_form_tls_address needs an argument");2166        else2167          return llvm::createStringError(2168              "DW_OP_GNU_push_tls_address needs an argument");2169      }2170 2171      if (!exe_ctx || !module_sp)2172        return llvm::createStringError("no context to evaluate TLS within");2173 2174      Thread *thread = exe_ctx->GetThreadPtr();2175      if (!thread)2176        return llvm::createStringError("no thread to evaluate TLS within");2177 2178      // Lookup the TLS block address for this thread and module.2179      const addr_t tls_file_addr =2180          stack.back().GetScalar().ULongLong(LLDB_INVALID_ADDRESS);2181      const addr_t tls_load_addr =2182          thread->GetThreadLocalData(module_sp, tls_file_addr);2183 2184      if (tls_load_addr == LLDB_INVALID_ADDRESS)2185        return llvm::createStringError(2186            "no TLS data currently exists for this thread");2187 2188      stack.back().GetScalar() = tls_load_addr;2189      stack.back().SetValueType(Value::ValueType::LoadAddress);2190    } break;2191 2192    // OPCODE: DW_OP_addrx (DW_OP_GNU_addr_index is the legacy name.)2193    // OPERANDS: 12194    //      ULEB128: index to the .debug_addr section2195    // DESCRIPTION: Pushes an address to the stack from the .debug_addr2196    // section with the base address specified by the DW_AT_addr_base attribute2197    // and the 0 based index is the ULEB128 encoded index.2198    case DW_OP_addrx:2199    case DW_OP_GNU_addr_index: {2200      if (!dwarf_cu)2201        return llvm::createStringError("DW_OP_GNU_addr_index found without a "2202                                       "compile unit being specified");2203      uint64_t index = opcodes.GetULEB128(&offset);2204      lldb::addr_t value = dwarf_cu->ReadAddressFromDebugAddrSection(index);2205      stack.push_back(Scalar(value));2206      if (target &&2207          target->GetArchitecture().GetCore() == ArchSpec::eCore_wasm32) {2208        // wasm file sections aren't mapped into memory, therefore addresses can2209        // never point into a file section and are always LoadAddresses.2210        stack.back().SetValueType(Value::ValueType::LoadAddress);2211      } else {2212        stack.back().SetValueType(Value::ValueType::FileAddress);2213      }2214    } break;2215 2216    // OPCODE: DW_OP_GNU_const_index2217    // OPERANDS: 12218    //      ULEB128: index to the .debug_addr section2219    // DESCRIPTION: Pushes an constant with the size of a machine address to2220    // the stack from the .debug_addr section with the base address specified2221    // by the DW_AT_addr_base attribute and the 0 based index is the ULEB1282222    // encoded index.2223    case DW_OP_GNU_const_index: {2224      if (!dwarf_cu) {2225        return llvm::createStringError("DW_OP_GNU_const_index found without a "2226                                       "compile unit being specified");2227      }2228      uint64_t index = opcodes.GetULEB128(&offset);2229      lldb::addr_t value = dwarf_cu->ReadAddressFromDebugAddrSection(index);2230      stack.push_back(Scalar(value));2231    } break;2232 2233    case DW_OP_GNU_entry_value:2234    case DW_OP_entry_value: {2235      if (llvm::Error err = Evaluate_DW_OP_entry_value(stack, exe_ctx, reg_ctx,2236                                                       opcodes, offset, log))2237        return llvm::createStringError(2238            "could not evaluate DW_OP_entry_value: %s",2239            llvm::toString(std::move(err)).c_str());2240      break;2241    }2242 2243    default:2244      if (dwarf_cu) {2245        if (dwarf_cu->ParseVendorDWARFOpcode(op, opcodes, offset, reg_ctx,2246                                             reg_kind, stack)) {2247          break;2248        }2249      }2250      return llvm::createStringError(llvm::formatv(2251          "Unhandled opcode {0} in DWARFExpression", LocationAtom(op)));2252    }2253  }2254 2255  if (stack.empty()) {2256    // Nothing on the stack, check if we created a piece value from DW_OP_piece2257    // or DW_OP_bit_piece opcodes2258    if (pieces.GetBuffer().GetByteSize())2259      return pieces;2260 2261    return llvm::createStringError("stack empty after evaluation");2262  }2263 2264  UpdateValueTypeFromLocationDescription(2265      log, dwarf_cu, dwarf4_location_description_kind, &stack.back());2266 2267  if (log && log->GetVerbose()) {2268    size_t count = stack.size();2269    LLDB_LOGF(log,2270              "Stack after operation has %" PRIu64 " values:", (uint64_t)count);2271    for (size_t i = 0; i < count; ++i) {2272      StreamString new_value;2273      new_value.Printf("[%" PRIu64 "]", (uint64_t)i);2274      stack[i].Dump(&new_value);2275      LLDB_LOGF(log, "  %s", new_value.GetData());2276    }2277  }2278  return stack.back();2279}2280 2281bool DWARFExpression::MatchesOperand(2282    StackFrame &frame, const Instruction::Operand &operand) const {2283  using namespace OperandMatchers;2284 2285  RegisterContextSP reg_ctx_sp = frame.GetRegisterContext();2286  if (!reg_ctx_sp) {2287    return false;2288  }2289 2290  DataExtractor opcodes(m_data);2291 2292  lldb::offset_t op_offset = 0;2293  uint8_t opcode = opcodes.GetU8(&op_offset);2294 2295  if (opcode == DW_OP_fbreg) {2296    int64_t offset = opcodes.GetSLEB128(&op_offset);2297 2298    DWARFExpressionList *fb_expr = frame.GetFrameBaseExpression(nullptr);2299    if (!fb_expr) {2300      return false;2301    }2302 2303    auto recurse = [&frame, fb_expr](const Instruction::Operand &child) {2304      return fb_expr->MatchesOperand(frame, child);2305    };2306 2307    if (!offset &&2308        MatchUnaryOp(MatchOpType(Instruction::Operand::Type::Dereference),2309                     recurse)(operand)) {2310      return true;2311    }2312 2313    return MatchUnaryOp(2314        MatchOpType(Instruction::Operand::Type::Dereference),2315        MatchBinaryOp(MatchOpType(Instruction::Operand::Type::Sum),2316                      MatchImmOp(offset), recurse))(operand);2317  }2318 2319  bool dereference = false;2320  const RegisterInfo *reg = nullptr;2321  int64_t offset = 0;2322 2323  if (opcode >= DW_OP_reg0 && opcode <= DW_OP_reg31) {2324    reg = reg_ctx_sp->GetRegisterInfo(m_reg_kind, opcode - DW_OP_reg0);2325  } else if (opcode >= DW_OP_breg0 && opcode <= DW_OP_breg31) {2326    offset = opcodes.GetSLEB128(&op_offset);2327    reg = reg_ctx_sp->GetRegisterInfo(m_reg_kind, opcode - DW_OP_breg0);2328  } else if (opcode == DW_OP_regx) {2329    uint32_t reg_num = static_cast<uint32_t>(opcodes.GetULEB128(&op_offset));2330    reg = reg_ctx_sp->GetRegisterInfo(m_reg_kind, reg_num);2331  } else if (opcode == DW_OP_bregx) {2332    uint32_t reg_num = static_cast<uint32_t>(opcodes.GetULEB128(&op_offset));2333    offset = opcodes.GetSLEB128(&op_offset);2334    reg = reg_ctx_sp->GetRegisterInfo(m_reg_kind, reg_num);2335  } else {2336    return false;2337  }2338 2339  if (!reg) {2340    return false;2341  }2342 2343  if (dereference) {2344    if (!offset &&2345        MatchUnaryOp(MatchOpType(Instruction::Operand::Type::Dereference),2346                     MatchRegOp(*reg))(operand)) {2347      return true;2348    }2349 2350    return MatchUnaryOp(2351        MatchOpType(Instruction::Operand::Type::Dereference),2352        MatchBinaryOp(MatchOpType(Instruction::Operand::Type::Sum),2353                      MatchRegOp(*reg), MatchImmOp(offset)))(operand);2354  } else {2355    return MatchRegOp(*reg)(operand);2356  }2357}2358