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-exception
6//
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::dwarf;
45using namespace lldb_private::plugin::dwarf;
46
47// DWARFExpression constructor
48DWARFExpression::DWARFExpression() : m_data() {}
49
50DWARFExpression::DWARFExpression(const DataExtractor &data) : m_data(data) {}
51
52// Destructor
53DWARFExpression::~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 data_sp: 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) const {
71 auto *MCRegInfo = abi ? &abi->GetMCRegisterInfo() : nullptr;
72 auto GetRegName = [&MCRegInfo](uint64_t DwarfRegNum,
73 bool IsEH) -> llvm::StringRef {
74 if (!MCRegInfo)
75 return {};
76 if (std::optional<unsigned> LLVMRegNum =
77 MCRegInfo->getLLVMRegNum(RegNum: DwarfRegNum, isEH: IsEH))
78 if (const char *RegName = MCRegInfo->getName(RegNo: *LLVMRegNum))
79 return llvm::StringRef(RegName);
80 return {};
81 };
82 llvm::DIDumpOptions DumpOpts;
83 DumpOpts.GetNameForDWARFReg = GetRegName;
84 llvm::DWARFExpression E(m_data.GetAsLLVM(), m_data.GetAddressByteSize());
85 llvm::printDwarfExpression(E: &E, OS&: s->AsRawOstream(), DumpOpts, U: 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
94static llvm::Error ReadRegisterValueAsScalar(RegisterContext *reg_ctx,
95 lldb::RegisterKind reg_kind,
96 uint32_t reg_num, Value &value) {
97 if (reg_ctx == nullptr)
98 return llvm::createStringError(Fmt: "no register context in frame");
99
100 const uint32_t native_reg =
101 reg_ctx->ConvertRegisterKindToRegisterNumber(kind: reg_kind, num: reg_num);
102 if (native_reg == LLDB_INVALID_REGNUM)
103 return llvm::createStringError(
104 Fmt: "unable to convert register kind=%u reg_num=%u to a native "
105 "register number",
106 Vals: reg_kind, Vals: reg_num);
107
108 const RegisterInfo *reg_info = reg_ctx->GetRegisterInfoAtIndex(reg: native_reg);
109 RegisterValue reg_value;
110 if (reg_ctx->ReadRegister(reg_info, reg_value)) {
111 if (reg_value.GetScalarValue(scalar&: value.GetScalar())) {
112 value.SetValueType(Value::ValueType::Scalar);
113 value.SetContext(context_type: Value::ContextType::RegisterInfo,
114 p: const_cast<RegisterInfo *>(reg_info));
115 return llvm::Error::success();
116 }
117
118 // If we get this error, then we need to implement a value buffer in
119 // the dwarf expression evaluation function...
120 return llvm::createStringError(
121 Fmt: "register %s can't be converted to a scalar value", Vals: reg_info->name);
122 }
123
124 return llvm::createStringError(Fmt: "register %s is not available",
125 Vals: reg_info->name);
126}
127
128/// Return the length in bytes of the set of operands for \p op. No guarantees
129/// are made on the state of \p data after this call.
130static lldb::offset_t
131GetOpcodeDataSize(const DataExtractor &data, const lldb::offset_t data_offset,
132 const LocationAtom op,
133 const DWARFExpression::Delegate *dwarf_cu) {
134 lldb::offset_t offset = data_offset;
135 switch (op) {
136 // Only used in LLVM metadata.
137 case DW_OP_LLVM_fragment:
138 case DW_OP_LLVM_convert:
139 case DW_OP_LLVM_tag_offset:
140 case DW_OP_LLVM_entry_value:
141 case DW_OP_LLVM_implicit_pointer:
142 case DW_OP_LLVM_arg:
143 case DW_OP_LLVM_extract_bits_sext:
144 case DW_OP_LLVM_extract_bits_zext:
145 break;
146 // Vendor extensions:
147 case DW_OP_HP_is_value:
148 case DW_OP_HP_fltconst4:
149 case DW_OP_HP_fltconst8:
150 case DW_OP_HP_mod_range:
151 case DW_OP_HP_unmod_range:
152 case DW_OP_HP_tls:
153 case DW_OP_INTEL_bit_piece:
154 case DW_OP_WASM_location:
155 case DW_OP_WASM_location_int:
156 case DW_OP_APPLE_uninit:
157 case DW_OP_PGI_omp_thread_num:
158 case DW_OP_hi_user:
159 case DW_OP_GNU_implicit_pointer:
160 break;
161
162 case DW_OP_addr:
163 case DW_OP_call_ref: // 0x9a 1 address sized offset of DIE (DWARF3)
164 return data.GetAddressByteSize();
165
166 // Opcodes with no arguments
167 case DW_OP_deref: // 0x06
168 case DW_OP_dup: // 0x12
169 case DW_OP_drop: // 0x13
170 case DW_OP_over: // 0x14
171 case DW_OP_swap: // 0x16
172 case DW_OP_rot: // 0x17
173 case DW_OP_xderef: // 0x18
174 case DW_OP_abs: // 0x19
175 case DW_OP_and: // 0x1a
176 case DW_OP_div: // 0x1b
177 case DW_OP_minus: // 0x1c
178 case DW_OP_mod: // 0x1d
179 case DW_OP_mul: // 0x1e
180 case DW_OP_neg: // 0x1f
181 case DW_OP_not: // 0x20
182 case DW_OP_or: // 0x21
183 case DW_OP_plus: // 0x22
184 case DW_OP_shl: // 0x24
185 case DW_OP_shr: // 0x25
186 case DW_OP_shra: // 0x26
187 case DW_OP_xor: // 0x27
188 case DW_OP_eq: // 0x29
189 case DW_OP_ge: // 0x2a
190 case DW_OP_gt: // 0x2b
191 case DW_OP_le: // 0x2c
192 case DW_OP_lt: // 0x2d
193 case DW_OP_ne: // 0x2e
194 case DW_OP_lit0: // 0x30
195 case DW_OP_lit1: // 0x31
196 case DW_OP_lit2: // 0x32
197 case DW_OP_lit3: // 0x33
198 case DW_OP_lit4: // 0x34
199 case DW_OP_lit5: // 0x35
200 case DW_OP_lit6: // 0x36
201 case DW_OP_lit7: // 0x37
202 case DW_OP_lit8: // 0x38
203 case DW_OP_lit9: // 0x39
204 case DW_OP_lit10: // 0x3A
205 case DW_OP_lit11: // 0x3B
206 case DW_OP_lit12: // 0x3C
207 case DW_OP_lit13: // 0x3D
208 case DW_OP_lit14: // 0x3E
209 case DW_OP_lit15: // 0x3F
210 case DW_OP_lit16: // 0x40
211 case DW_OP_lit17: // 0x41
212 case DW_OP_lit18: // 0x42
213 case DW_OP_lit19: // 0x43
214 case DW_OP_lit20: // 0x44
215 case DW_OP_lit21: // 0x45
216 case DW_OP_lit22: // 0x46
217 case DW_OP_lit23: // 0x47
218 case DW_OP_lit24: // 0x48
219 case DW_OP_lit25: // 0x49
220 case DW_OP_lit26: // 0x4A
221 case DW_OP_lit27: // 0x4B
222 case DW_OP_lit28: // 0x4C
223 case DW_OP_lit29: // 0x4D
224 case DW_OP_lit30: // 0x4E
225 case DW_OP_lit31: // 0x4f
226 case DW_OP_reg0: // 0x50
227 case DW_OP_reg1: // 0x51
228 case DW_OP_reg2: // 0x52
229 case DW_OP_reg3: // 0x53
230 case DW_OP_reg4: // 0x54
231 case DW_OP_reg5: // 0x55
232 case DW_OP_reg6: // 0x56
233 case DW_OP_reg7: // 0x57
234 case DW_OP_reg8: // 0x58
235 case DW_OP_reg9: // 0x59
236 case DW_OP_reg10: // 0x5A
237 case DW_OP_reg11: // 0x5B
238 case DW_OP_reg12: // 0x5C
239 case DW_OP_reg13: // 0x5D
240 case DW_OP_reg14: // 0x5E
241 case DW_OP_reg15: // 0x5F
242 case DW_OP_reg16: // 0x60
243 case DW_OP_reg17: // 0x61
244 case DW_OP_reg18: // 0x62
245 case DW_OP_reg19: // 0x63
246 case DW_OP_reg20: // 0x64
247 case DW_OP_reg21: // 0x65
248 case DW_OP_reg22: // 0x66
249 case DW_OP_reg23: // 0x67
250 case DW_OP_reg24: // 0x68
251 case DW_OP_reg25: // 0x69
252 case DW_OP_reg26: // 0x6A
253 case DW_OP_reg27: // 0x6B
254 case DW_OP_reg28: // 0x6C
255 case DW_OP_reg29: // 0x6D
256 case DW_OP_reg30: // 0x6E
257 case DW_OP_reg31: // 0x6F
258 case DW_OP_nop: // 0x96
259 case DW_OP_push_object_address: // 0x97 DWARF3
260 case DW_OP_form_tls_address: // 0x9b DWARF3
261 case DW_OP_call_frame_cfa: // 0x9c DWARF3
262 case DW_OP_stack_value: // 0x9f DWARF4
263 case DW_OP_GNU_push_tls_address: // 0xe0 GNU extension
264 return 0;
265
266 // Opcodes with a single 1 byte arguments
267 case DW_OP_const1u: // 0x08 1 1-byte constant
268 case DW_OP_const1s: // 0x09 1 1-byte constant
269 case DW_OP_pick: // 0x15 1 1-byte stack index
270 case DW_OP_deref_size: // 0x94 1 1-byte size of data retrieved
271 case DW_OP_xderef_size: // 0x95 1 1-byte size of data retrieved
272 case DW_OP_deref_type: // 0xa6 1 1-byte constant
273 return 1;
274
275 // Opcodes with a single 2 byte arguments
276 case DW_OP_const2u: // 0x0a 1 2-byte constant
277 case DW_OP_const2s: // 0x0b 1 2-byte constant
278 case DW_OP_skip: // 0x2f 1 signed 2-byte constant
279 case DW_OP_bra: // 0x28 1 signed 2-byte constant
280 case DW_OP_call2: // 0x98 1 2-byte offset of DIE (DWARF3)
281 return 2;
282
283 // Opcodes with a single 4 byte arguments
284 case DW_OP_const4u: // 0x0c 1 4-byte constant
285 case DW_OP_const4s: // 0x0d 1 4-byte constant
286 case DW_OP_call4: // 0x99 1 4-byte offset of DIE (DWARF3)
287 return 4;
288
289 // Opcodes with a single 8 byte arguments
290 case DW_OP_const8u: // 0x0e 1 8-byte constant
291 case DW_OP_const8s: // 0x0f 1 8-byte constant
292 return 8;
293
294 // All opcodes that have a single ULEB (signed or unsigned) argument
295 case DW_OP_constu: // 0x10 1 ULEB128 constant
296 case DW_OP_consts: // 0x11 1 SLEB128 constant
297 case DW_OP_plus_uconst: // 0x23 1 ULEB128 addend
298 case DW_OP_breg0: // 0x70 1 ULEB128 register
299 case DW_OP_breg1: // 0x71 1 ULEB128 register
300 case DW_OP_breg2: // 0x72 1 ULEB128 register
301 case DW_OP_breg3: // 0x73 1 ULEB128 register
302 case DW_OP_breg4: // 0x74 1 ULEB128 register
303 case DW_OP_breg5: // 0x75 1 ULEB128 register
304 case DW_OP_breg6: // 0x76 1 ULEB128 register
305 case DW_OP_breg7: // 0x77 1 ULEB128 register
306 case DW_OP_breg8: // 0x78 1 ULEB128 register
307 case DW_OP_breg9: // 0x79 1 ULEB128 register
308 case DW_OP_breg10: // 0x7a 1 ULEB128 register
309 case DW_OP_breg11: // 0x7b 1 ULEB128 register
310 case DW_OP_breg12: // 0x7c 1 ULEB128 register
311 case DW_OP_breg13: // 0x7d 1 ULEB128 register
312 case DW_OP_breg14: // 0x7e 1 ULEB128 register
313 case DW_OP_breg15: // 0x7f 1 ULEB128 register
314 case DW_OP_breg16: // 0x80 1 ULEB128 register
315 case DW_OP_breg17: // 0x81 1 ULEB128 register
316 case DW_OP_breg18: // 0x82 1 ULEB128 register
317 case DW_OP_breg19: // 0x83 1 ULEB128 register
318 case DW_OP_breg20: // 0x84 1 ULEB128 register
319 case DW_OP_breg21: // 0x85 1 ULEB128 register
320 case DW_OP_breg22: // 0x86 1 ULEB128 register
321 case DW_OP_breg23: // 0x87 1 ULEB128 register
322 case DW_OP_breg24: // 0x88 1 ULEB128 register
323 case DW_OP_breg25: // 0x89 1 ULEB128 register
324 case DW_OP_breg26: // 0x8a 1 ULEB128 register
325 case DW_OP_breg27: // 0x8b 1 ULEB128 register
326 case DW_OP_breg28: // 0x8c 1 ULEB128 register
327 case DW_OP_breg29: // 0x8d 1 ULEB128 register
328 case DW_OP_breg30: // 0x8e 1 ULEB128 register
329 case DW_OP_breg31: // 0x8f 1 ULEB128 register
330 case DW_OP_regx: // 0x90 1 ULEB128 register
331 case DW_OP_fbreg: // 0x91 1 SLEB128 offset
332 case DW_OP_piece: // 0x93 1 ULEB128 size of piece addressed
333 case DW_OP_convert: // 0xa8 1 ULEB128 offset
334 case DW_OP_reinterpret: // 0xa9 1 ULEB128 offset
335 case DW_OP_addrx: // 0xa1 1 ULEB128 index
336 case DW_OP_constx: // 0xa2 1 ULEB128 index
337 case DW_OP_xderef_type: // 0xa7 1 ULEB128 index
338 case DW_OP_GNU_addr_index: // 0xfb 1 ULEB128 index
339 case DW_OP_GNU_const_index: // 0xfc 1 ULEB128 index
340 data.Skip_LEB128(offset_ptr: &offset);
341 return offset - data_offset;
342
343 // All opcodes that have a 2 ULEB (signed or unsigned) arguments
344 case DW_OP_bregx: // 0x92 2 ULEB128 register followed by SLEB128 offset
345 case DW_OP_bit_piece: // 0x9d ULEB128 bit size, ULEB128 bit offset (DWARF3);
346 case DW_OP_regval_type: // 0xa5 ULEB128 + ULEB128
347 data.Skip_LEB128(offset_ptr: &offset);
348 data.Skip_LEB128(offset_ptr: &offset);
349 return offset - data_offset;
350
351 case DW_OP_implicit_value: // 0x9e ULEB128 size followed by block of that size
352 // (DWARF4)
353 {
354 uint64_t block_len = data.Skip_LEB128(offset_ptr: &offset);
355 offset += block_len;
356 return offset - data_offset;
357 }
358
359 case DW_OP_implicit_pointer: // 0xa0 4-byte (or 8-byte for DWARF 64) constant
360 // + LEB128
361 {
362 data.Skip_LEB128(offset_ptr: &offset);
363 return (dwarf_cu ? dwarf_cu->GetAddressByteSize() : 4) + offset -
364 data_offset;
365 }
366
367 case DW_OP_GNU_entry_value:
368 case DW_OP_entry_value: // 0xa3 ULEB128 size + variable-length block
369 {
370 uint64_t subexpr_len = data.GetULEB128(offset_ptr: &offset);
371 return (offset - data_offset) + subexpr_len;
372 }
373
374 case DW_OP_const_type: // 0xa4 ULEB128 + size + variable-length block
375 {
376 data.Skip_LEB128(offset_ptr: &offset);
377 uint8_t length = data.GetU8(offset_ptr: &offset);
378 return (offset - data_offset) + length;
379 }
380
381 case DW_OP_LLVM_user: // 0xe9: ULEB128 + variable length constant
382 {
383 uint64_t constants = data.GetULEB128(offset_ptr: &offset);
384 return (offset - data_offset) + constants;
385 }
386 }
387
388 if (dwarf_cu)
389 return dwarf_cu->GetVendorDWARFOpcodeSize(data, data_offset, op);
390
391 return LLDB_INVALID_OFFSET;
392}
393
394static const char *DW_OP_value_to_name(uint32_t val) {
395 static char invalid[100];
396 llvm::StringRef llvmstr = llvm::dwarf::OperationEncodingString(Encoding: val);
397 if (llvmstr.empty()) {
398 snprintf(s: invalid, maxlen: sizeof(invalid), format: "Unknown DW_OP constant: 0x%x", val);
399 return invalid;
400 }
401 return llvmstr.data();
402}
403
404llvm::Expected<lldb::addr_t> DWARFExpression::GetLocation_DW_OP_addr(
405 const DWARFExpression::Delegate *dwarf_cu) const {
406 lldb::offset_t offset = 0;
407 while (m_data.ValidOffset(offset)) {
408 const LocationAtom op = static_cast<LocationAtom>(m_data.GetU8(offset_ptr: &offset));
409
410 if (op == DW_OP_addr)
411 return m_data.GetAddress(offset_ptr: &offset);
412
413 if (op == DW_OP_GNU_addr_index || op == DW_OP_addrx) {
414 const uint64_t index = m_data.GetULEB128(offset_ptr: &offset);
415 if (dwarf_cu)
416 return dwarf_cu->ReadAddressFromDebugAddrSection(index);
417 return llvm::createStringError(Fmt: "cannot evaluate %s without a DWARF unit",
418 Vals: DW_OP_value_to_name(val: op));
419 }
420
421 const lldb::offset_t op_arg_size =
422 GetOpcodeDataSize(data: m_data, data_offset: offset, op, dwarf_cu);
423 if (op_arg_size == LLDB_INVALID_OFFSET)
424 return llvm::createStringError(Fmt: "cannot get opcode data size for %s",
425 Vals: DW_OP_value_to_name(val: op));
426
427 offset += op_arg_size;
428 }
429
430 return LLDB_INVALID_ADDRESS;
431}
432
433bool DWARFExpression::Update_DW_OP_addr(
434 const DWARFExpression::Delegate *dwarf_cu, lldb::addr_t file_addr) {
435 lldb::offset_t offset = 0;
436 while (m_data.ValidOffset(offset)) {
437 const LocationAtom op = static_cast<LocationAtom>(m_data.GetU8(offset_ptr: &offset));
438
439 if (op == DW_OP_addr) {
440 const uint32_t addr_byte_size = m_data.GetAddressByteSize();
441 // We have to make a copy of the data as we don't know if this data is
442 // from a read only memory mapped buffer, so we duplicate all of the data
443 // first, then modify it, and if all goes well, we then replace the data
444 // for this expression
445
446 // Make en encoder that contains a copy of the location expression data
447 // so we can write the address into the buffer using the correct byte
448 // order.
449 DataEncoder encoder(m_data.GetDataStart(), m_data.GetByteSize(),
450 m_data.GetByteOrder(), addr_byte_size);
451
452 // Replace the address in the new buffer
453 if (encoder.PutAddress(offset, addr: file_addr) == UINT32_MAX)
454 return false;
455
456 // All went well, so now we can reset the data using a shared pointer to
457 // the heap data so "m_data" will now correctly manage the heap data.
458 m_data.SetData(data_sp: encoder.GetDataBuffer());
459 return true;
460 }
461 if (op == DW_OP_addrx) {
462 // Replace DW_OP_addrx with DW_OP_addr, since we can't modify the
463 // read-only debug_addr table.
464 // Subtract one to account for the opcode.
465 llvm::ArrayRef data_before_op = m_data.GetData().take_front(N: offset - 1);
466
467 // Read the addrx index to determine how many bytes it needs.
468 const lldb::offset_t old_offset = offset;
469 m_data.GetULEB128(offset_ptr: &offset);
470 if (old_offset == offset)
471 return false;
472 llvm::ArrayRef data_after_op = m_data.GetData().drop_front(N: offset);
473
474 DataEncoder encoder(m_data.GetByteOrder(), m_data.GetAddressByteSize());
475 encoder.AppendData(data: data_before_op);
476 encoder.AppendU8(value: DW_OP_addr);
477 encoder.AppendAddress(addr: file_addr);
478 encoder.AppendData(data: data_after_op);
479 m_data.SetData(data_sp: encoder.GetDataBuffer());
480 return true;
481 }
482 const lldb::offset_t op_arg_size =
483 GetOpcodeDataSize(data: m_data, data_offset: offset, op, dwarf_cu);
484 if (op_arg_size == LLDB_INVALID_OFFSET)
485 break;
486 offset += op_arg_size;
487 }
488 return false;
489}
490
491bool DWARFExpression::ContainsThreadLocalStorage(
492 const DWARFExpression::Delegate *dwarf_cu) const {
493 lldb::offset_t offset = 0;
494 while (m_data.ValidOffset(offset)) {
495 const LocationAtom op = static_cast<LocationAtom>(m_data.GetU8(offset_ptr: &offset));
496
497 if (op == DW_OP_form_tls_address || op == DW_OP_GNU_push_tls_address)
498 return true;
499 const lldb::offset_t op_arg_size =
500 GetOpcodeDataSize(data: m_data, data_offset: offset, op, dwarf_cu);
501 if (op_arg_size == LLDB_INVALID_OFFSET)
502 return false;
503 offset += op_arg_size;
504 }
505 return false;
506}
507bool DWARFExpression::LinkThreadLocalStorage(
508 const DWARFExpression::Delegate *dwarf_cu,
509 std::function<lldb::addr_t(lldb::addr_t file_addr)> const
510 &link_address_callback) {
511 const uint32_t addr_byte_size = m_data.GetAddressByteSize();
512 // We have to make a copy of the data as we don't know if this data is from a
513 // read only memory mapped buffer, so we duplicate all of the data first,
514 // then modify it, and if all goes well, we then replace the data for this
515 // expression.
516 // Make en encoder that contains a copy of the location expression data so we
517 // can write the address into the buffer using the correct byte order.
518 DataEncoder encoder(m_data.GetDataStart(), m_data.GetByteSize(),
519 m_data.GetByteOrder(), addr_byte_size);
520
521 lldb::offset_t offset = 0;
522 lldb::offset_t const_offset = 0;
523 lldb::addr_t const_value = 0;
524 size_t const_byte_size = 0;
525 while (m_data.ValidOffset(offset)) {
526 const LocationAtom op = static_cast<LocationAtom>(m_data.GetU8(offset_ptr: &offset));
527
528 bool decoded_data = false;
529 switch (op) {
530 case DW_OP_const4u:
531 // Remember the const offset in case we later have a
532 // DW_OP_form_tls_address or DW_OP_GNU_push_tls_address
533 const_offset = offset;
534 const_value = m_data.GetU32(offset_ptr: &offset);
535 decoded_data = true;
536 const_byte_size = 4;
537 break;
538
539 case DW_OP_const8u:
540 // Remember the const offset in case we later have a
541 // DW_OP_form_tls_address or DW_OP_GNU_push_tls_address
542 const_offset = offset;
543 const_value = m_data.GetU64(offset_ptr: &offset);
544 decoded_data = true;
545 const_byte_size = 8;
546 break;
547
548 case DW_OP_form_tls_address:
549 case DW_OP_GNU_push_tls_address:
550 // DW_OP_form_tls_address and DW_OP_GNU_push_tls_address must be preceded
551 // by a file address on the stack. We assume that DW_OP_const4u or
552 // DW_OP_const8u is used for these values, and we check that the last
553 // opcode we got before either of these was DW_OP_const4u or
554 // DW_OP_const8u. If so, then we can link the value accordingly. For
555 // Darwin, the value in the DW_OP_const4u or DW_OP_const8u is the file
556 // address of a structure that contains a function pointer, the pthread
557 // key and the offset into the data pointed to by the pthread key. So we
558 // must link this address and also set the module of this expression to
559 // the new_module_sp so we can resolve the file address correctly
560 if (const_byte_size > 0) {
561 lldb::addr_t linked_file_addr = link_address_callback(const_value);
562 if (linked_file_addr == LLDB_INVALID_ADDRESS)
563 return false;
564 // Replace the address in the new buffer
565 if (encoder.PutUnsigned(offset: const_offset, byte_size: const_byte_size,
566 value: linked_file_addr) == UINT32_MAX)
567 return false;
568 }
569 break;
570
571 default:
572 const_offset = 0;
573 const_value = 0;
574 const_byte_size = 0;
575 break;
576 }
577
578 if (!decoded_data) {
579 const lldb::offset_t op_arg_size =
580 GetOpcodeDataSize(data: m_data, data_offset: offset, op, dwarf_cu);
581 if (op_arg_size == LLDB_INVALID_OFFSET)
582 return false;
583 else
584 offset += op_arg_size;
585 }
586 }
587
588 m_data.SetData(data_sp: encoder.GetDataBuffer());
589 return true;
590}
591
592static llvm::Error Evaluate_DW_OP_entry_value(DWARFExpression::Stack &stack,
593 ExecutionContext *exe_ctx,
594 RegisterContext *reg_ctx,
595 const DataExtractor &opcodes,
596 lldb::offset_t &opcode_offset,
597 Log *log) {
598 // DW_OP_entry_value(sub-expr) describes the location a variable had upon
599 // function entry: this variable location is presumed to be optimized out at
600 // the current PC value. The caller of the function may have call site
601 // information that describes an alternate location for the variable (e.g. a
602 // constant literal, or a spilled stack value) in the parent frame.
603 //
604 // Example (this is pseudo-code & pseudo-DWARF, but hopefully illustrative):
605 //
606 // void child(int &sink, int x) {
607 // ...
608 // /* "x" gets optimized out. */
609 //
610 // /* The location of "x" here is: DW_OP_entry_value($reg2). */
611 // ++sink;
612 // }
613 //
614 // void parent() {
615 // int sink;
616 //
617 // /*
618 // * The callsite information emitted here is:
619 // *
620 // * DW_TAG_call_site
621 // * DW_AT_return_pc ... (for "child(sink, 123);")
622 // * DW_TAG_call_site_parameter (for "sink")
623 // * DW_AT_location ($reg1)
624 // * DW_AT_call_value ($SP - 8)
625 // * DW_TAG_call_site_parameter (for "x")
626 // * DW_AT_location ($reg2)
627 // * DW_AT_call_value ($literal 123)
628 // *
629 // * DW_TAG_call_site
630 // * DW_AT_return_pc ... (for "child(sink, 456);")
631 // * ...
632 // */
633 // child(sink, 123);
634 // child(sink, 456);
635 // }
636 //
637 // When the program stops at "++sink" within `child`, the debugger determines
638 // the call site by analyzing the return address. Once the call site is found,
639 // the debugger determines which parameter is referenced by DW_OP_entry_value
640 // and evaluates the corresponding location for that parameter in `parent`.
641
642 // 1. Find the function which pushed the current frame onto the stack.
643 if ((!exe_ctx || !exe_ctx->HasTargetScope()) || !reg_ctx) {
644 return llvm::createStringError(Fmt: "no exe/reg context");
645 }
646
647 StackFrame *current_frame = exe_ctx->GetFramePtr();
648 Thread *thread = exe_ctx->GetThreadPtr();
649 if (!current_frame || !thread)
650 return llvm::createStringError(Fmt: "no current frame/thread");
651
652 Target &target = exe_ctx->GetTargetRef();
653 StackFrameSP parent_frame = nullptr;
654 addr_t return_pc = LLDB_INVALID_ADDRESS;
655 uint32_t current_frame_idx = current_frame->GetFrameIndex();
656
657 for (uint32_t parent_frame_idx = current_frame_idx + 1;; parent_frame_idx++) {
658 parent_frame = thread->GetStackFrameAtIndex(idx: parent_frame_idx);
659 // If this is null, we're at the end of the stack.
660 if (!parent_frame)
661 break;
662
663 // Record the first valid return address, even if this is an inlined frame,
664 // in order to look up the associated call edge in the first non-inlined
665 // parent frame.
666 if (return_pc == LLDB_INVALID_ADDRESS) {
667 return_pc = parent_frame->GetFrameCodeAddress().GetLoadAddress(target: &target);
668 LLDB_LOG(log, "immediate ancestor with pc = {0:x}", return_pc);
669 }
670
671 // If we've found an inlined frame, skip it (these have no call site
672 // parameters).
673 if (parent_frame->IsInlined())
674 continue;
675
676 // We've found the first non-inlined parent frame.
677 break;
678 }
679 if (!parent_frame || !parent_frame->GetRegisterContext()) {
680 return llvm::createStringError(Fmt: "no parent frame with reg ctx");
681 }
682
683 Function *parent_func =
684 parent_frame->GetSymbolContext(resolve_scope: eSymbolContextFunction).function;
685 if (!parent_func)
686 return llvm::createStringError(Fmt: "no parent function");
687
688 // 2. Find the call edge in the parent function responsible for creating the
689 // current activation.
690 Function *current_func =
691 current_frame->GetSymbolContext(resolve_scope: eSymbolContextFunction).function;
692 if (!current_func)
693 return llvm::createStringError(Fmt: "no current function");
694
695 CallEdge *call_edge = nullptr;
696 ModuleList &modlist = target.GetImages();
697 ExecutionContext parent_exe_ctx = *exe_ctx;
698 parent_exe_ctx.SetFrameSP(parent_frame);
699 if (!parent_frame->IsArtificial()) {
700 // If the parent frame is not artificial, the current activation may be
701 // produced by an ambiguous tail call. In this case, refuse to proceed.
702 call_edge = parent_func->GetCallEdgeForReturnAddress(return_pc, target);
703 if (!call_edge) {
704 return llvm::createStringError(
705 S: llvm::formatv(Fmt: "no call edge for retn-pc = {0:x} in parent frame {1}",
706 Vals&: return_pc, Vals: parent_func->GetName()));
707 }
708 Function *callee_func = call_edge->GetCallee(images&: modlist, exe_ctx&: parent_exe_ctx);
709 if (callee_func != current_func) {
710 return llvm::createStringError(
711 Fmt: "ambiguous call sequence, can't find real parent frame");
712 }
713 } else {
714 // The StackFrameList solver machinery has deduced that an unambiguous tail
715 // call sequence that produced the current activation. The first edge in
716 // the parent that points to the current function must be valid.
717 for (auto &edge : parent_func->GetTailCallingEdges()) {
718 if (edge->GetCallee(images&: modlist, exe_ctx&: parent_exe_ctx) == current_func) {
719 call_edge = edge.get();
720 break;
721 }
722 }
723 }
724 if (!call_edge)
725 return llvm::createStringError(Fmt: "no unambiguous edge from parent "
726 "to current function");
727
728 // 3. Attempt to locate the DW_OP_entry_value expression in the set of
729 // available call site parameters. If found, evaluate the corresponding
730 // parameter in the context of the parent frame.
731 const uint32_t subexpr_len = opcodes.GetULEB128(offset_ptr: &opcode_offset);
732 const void *subexpr_data = opcodes.GetData(offset_ptr: &opcode_offset, length: subexpr_len);
733 if (!subexpr_data)
734 return llvm::createStringError(Fmt: "subexpr could not be read");
735
736 const CallSiteParameter *matched_param = nullptr;
737 for (const CallSiteParameter &param : call_edge->GetCallSiteParameters()) {
738 DataExtractor param_subexpr_extractor;
739 if (!param.LocationInCallee.GetExpressionData(data&: param_subexpr_extractor))
740 continue;
741 lldb::offset_t param_subexpr_offset = 0;
742 const void *param_subexpr_data =
743 param_subexpr_extractor.GetData(offset_ptr: &param_subexpr_offset, length: subexpr_len);
744 if (!param_subexpr_data ||
745 param_subexpr_extractor.BytesLeft(offset: param_subexpr_offset) != 0)
746 continue;
747
748 // At this point, the DW_OP_entry_value sub-expression and the callee-side
749 // expression in the call site parameter are known to have the same length.
750 // Check whether they are equal.
751 //
752 // Note that an equality check is sufficient: the contents of the
753 // DW_OP_entry_value subexpression are only used to identify the right call
754 // site parameter in the parent, and do not require any special handling.
755 if (memcmp(s1: subexpr_data, s2: param_subexpr_data, n: subexpr_len) == 0) {
756 matched_param = &param;
757 break;
758 }
759 }
760 if (!matched_param)
761 return llvm::createStringError(Fmt: "no matching call site param found");
762
763 // TODO: Add support for DW_OP_push_object_address within a DW_OP_entry_value
764 // subexpresion whenever llvm does.
765 const DWARFExpressionList &param_expr = matched_param->LocationInCaller;
766
767 llvm::Expected<Value> maybe_result = param_expr.Evaluate(
768 exe_ctx: &parent_exe_ctx, reg_ctx: parent_frame->GetRegisterContext().get(),
769 LLDB_INVALID_ADDRESS,
770 /*initial_value_ptr=*/nullptr,
771 /*object_address_ptr=*/nullptr);
772 if (!maybe_result) {
773 LLDB_LOG(log,
774 "Evaluate_DW_OP_entry_value: call site param evaluation failed");
775 return maybe_result.takeError();
776 }
777
778 stack.push_back(x: *maybe_result);
779 return llvm::Error::success();
780}
781
782namespace {
783/// The location description kinds described by the DWARF v5
784/// specification. Composite locations are handled out-of-band and
785/// thus aren't part of the enum.
786enum LocationDescriptionKind {
787 Empty,
788 Memory,
789 Register,
790 Implicit
791 /* Composite*/
792};
793/// Adjust value's ValueType according to the kind of location description.
794void UpdateValueTypeFromLocationDescription(
795 Log *log, const DWARFExpression::Delegate *dwarf_cu,
796 LocationDescriptionKind kind, Value *value = nullptr) {
797 // Note that this function is conflating DWARF expressions with
798 // DWARF location descriptions. Perhaps it would be better to define
799 // a wrapper for DWARFExpression::Eval() that deals with DWARF
800 // location descriptions (which consist of one or more DWARF
801 // expressions). But doing this would mean we'd also need factor the
802 // handling of DW_OP_(bit_)piece out of this function.
803 if (dwarf_cu && dwarf_cu->GetVersion() >= 4) {
804 const char *log_msg = "DWARF location description kind: %s";
805 switch (kind) {
806 case Empty:
807 LLDB_LOGF(log, log_msg, "Empty");
808 break;
809 case Memory:
810 LLDB_LOGF(log, log_msg, "Memory");
811 if (value->GetValueType() == Value::ValueType::Scalar)
812 value->SetValueType(Value::ValueType::LoadAddress);
813 break;
814 case Register:
815 LLDB_LOGF(log, log_msg, "Register");
816 value->SetValueType(Value::ValueType::Scalar);
817 break;
818 case Implicit:
819 LLDB_LOGF(log, log_msg, "Implicit");
820 if (value->GetValueType() == Value::ValueType::LoadAddress)
821 value->SetValueType(Value::ValueType::Scalar);
822 break;
823 }
824 }
825}
826} // namespace
827
828/// Helper function to move common code used to resolve a file address and turn
829/// into a load address.
830///
831/// \param exe_ctx Pointer to the execution context
832/// \param module_sp shared_ptr contains the module if we have one
833/// \param dw_op_type C-style string used to vary the error output
834/// \param file_addr the file address we are trying to resolve and turn into a
835/// load address
836/// \param so_addr out parameter, will be set to load address or section offset
837/// \param check_sectionoffset bool which determines if having a section offset
838/// but not a load address is considerd a success
839/// \returns std::optional containing the load address if resolving and getting
840/// the load address succeed or an empty Optinal otherwise. If
841/// check_sectionoffset is true we consider LLDB_INVALID_ADDRESS a
842/// success if so_addr.IsSectionOffset() is true.
843static llvm::Expected<lldb::addr_t>
844ResolveLoadAddress(ExecutionContext *exe_ctx, lldb::ModuleSP &module_sp,
845 const char *dw_op_type, lldb::addr_t file_addr,
846 Address &so_addr, bool check_sectionoffset = false) {
847 if (!module_sp)
848 return llvm::createStringError(Fmt: "need module to resolve file address for %s",
849 Vals: dw_op_type);
850
851 if (!module_sp->ResolveFileAddress(vm_addr: file_addr, so_addr))
852 return llvm::createStringError(Fmt: "failed to resolve file address in module");
853
854 const addr_t load_addr = so_addr.GetLoadAddress(target: exe_ctx->GetTargetPtr());
855
856 if (load_addr == LLDB_INVALID_ADDRESS &&
857 (check_sectionoffset && !so_addr.IsSectionOffset()))
858 return llvm::createStringError(Fmt: "failed to resolve load address");
859
860 return load_addr;
861}
862
863static llvm::Error Evaluate_DW_OP_deref(DWARFExpression::Stack &stack,
864 ExecutionContext *exe_ctx,
865 lldb::ModuleSP module_sp,
866 Process *process) {
867 if (stack.empty())
868 return llvm::createStringError(Fmt: "expression stack empty for DW_OP_deref");
869
870 const Value::ValueType value_type = stack.back().GetValueType();
871 switch (value_type) {
872 case Value::ValueType::HostAddress: {
873 void *src = (void *)stack.back().GetScalar().ULongLong();
874 intptr_t ptr;
875 ::memcpy(dest: &ptr, src: src, n: sizeof(void *));
876 stack.back().GetScalar() = ptr;
877 stack.back().ClearContext();
878 } break;
879 case Value::ValueType::FileAddress: {
880 auto file_addr = stack.back().GetScalar().ULongLong(LLDB_INVALID_ADDRESS);
881 Address so_addr;
882 auto maybe_load_addr = ResolveLoadAddress(exe_ctx, module_sp, dw_op_type: "DW_OP_deref",
883 file_addr, so_addr);
884 if (!maybe_load_addr)
885 return maybe_load_addr.takeError();
886 stack.back().GetScalar() = *maybe_load_addr;
887 // Fall through to load address promotion code below.
888 }
889 [[fallthrough]];
890 case Value::ValueType::Scalar:
891 // Promote Scalar to LoadAddress and fall through.
892 stack.back().SetValueType(Value::ValueType::LoadAddress);
893 [[fallthrough]];
894 case Value::ValueType::LoadAddress: {
895 if (!exe_ctx)
896 return llvm::createStringError(Fmt: "NULL execution context for DW_OP_deref");
897 if (!process)
898 return llvm::createStringError(Fmt: "NULL process for DW_OP_deref");
899 lldb::addr_t pointer_addr =
900 stack.back().GetScalar().ULongLong(LLDB_INVALID_ADDRESS);
901 Status error;
902 lldb::addr_t pointer_value =
903 process->ReadPointerFromMemory(vm_addr: pointer_addr, error);
904 if (pointer_value == LLDB_INVALID_ADDRESS)
905 return llvm::joinErrors(
906 E1: llvm::createStringError(
907 Fmt: "Failed to dereference pointer from 0x%" PRIx64
908 " for DW_OP_deref",
909 Vals: pointer_addr),
910 E2: error.takeError());
911 if (ABISP abi_sp = process->GetABI())
912 pointer_value = abi_sp->FixCodeAddress(pc: pointer_value);
913 stack.back().GetScalar() = pointer_value;
914 stack.back().ClearContext();
915 } break;
916 case Value::ValueType::Invalid:
917 return llvm::createStringError(Fmt: "invalid value type for DW_OP_deref");
918 }
919
920 return llvm::Error::success();
921}
922
923/// Helper function to move common code used to load sized data from a uint8_t
924/// buffer.
925///
926/// \param addr_bytes uint8_t buffer containg raw data
927/// \param size_addr_bytes how large is the underlying raw data
928/// \param byte_order what is the byter order of the underlyig data
929/// \param size How much of the underlying data we want to use
930/// \return The underlying data converted into a Scalar
931static Scalar DerefSizeExtractDataHelper(uint8_t *addr_bytes,
932 size_t size_addr_bytes,
933 ByteOrder byte_order, size_t size) {
934 DataExtractor addr_data(addr_bytes, size_addr_bytes, byte_order, size);
935
936 lldb::offset_t addr_data_offset = 0;
937 if (size <= 8)
938 return addr_data.GetMaxU64(offset_ptr: &addr_data_offset, byte_size: size);
939 else
940 return addr_data.GetAddress(offset_ptr: &addr_data_offset);
941}
942
943llvm::Expected<Value> DWARFExpression::Evaluate(
944 ExecutionContext *exe_ctx, RegisterContext *reg_ctx,
945 lldb::ModuleSP module_sp, const DataExtractor &opcodes,
946 const DWARFExpression::Delegate *dwarf_cu,
947 const lldb::RegisterKind reg_kind, const Value *initial_value_ptr,
948 const Value *object_address_ptr) {
949
950 if (opcodes.GetByteSize() == 0)
951 return llvm::createStringError(
952 Fmt: "no location, value may have been optimized out");
953
954 Stack stack;
955
956 Process *process = nullptr;
957 StackFrame *frame = nullptr;
958 Target *target = nullptr;
959
960 if (exe_ctx) {
961 process = exe_ctx->GetProcessPtr();
962 frame = exe_ctx->GetFramePtr();
963 target = exe_ctx->GetTargetPtr();
964 }
965 if (reg_ctx == nullptr && frame)
966 reg_ctx = frame->GetRegisterContext().get();
967
968 if (initial_value_ptr)
969 stack.push_back(x: *initial_value_ptr);
970
971 lldb::offset_t offset = 0;
972 Value tmp;
973 uint32_t reg_num;
974
975 /// Insertion point for evaluating multi-piece expression.
976 uint64_t op_piece_offset = 0;
977 Value pieces; // Used for DW_OP_piece
978
979 Log *log = GetLog(mask: LLDBLog::Expressions);
980 // A generic type is "an integral type that has the size of an address and an
981 // unspecified signedness". For now, just use the signedness of the operand.
982 // TODO: Implement a real typed stack, and store the genericness of the value
983 // there.
984 auto to_generic = [&](auto v) {
985 // TODO: Avoid implicit trunc?
986 // See https://github.com/llvm/llvm-project/issues/112510.
987 bool is_signed = std::is_signed<decltype(v)>::value;
988 return Scalar(llvm::APSInt(llvm::APInt(8 * opcodes.GetAddressByteSize(), v,
989 is_signed, /*implicitTrunc=*/true),
990 !is_signed));
991 };
992
993 // The default kind is a memory location. This is updated by any
994 // operation that changes this, such as DW_OP_stack_value, and reset
995 // by composition operations like DW_OP_piece.
996 LocationDescriptionKind dwarf4_location_description_kind = Memory;
997
998 while (opcodes.ValidOffset(offset)) {
999 const lldb::offset_t op_offset = offset;
1000 const uint8_t op = opcodes.GetU8(offset_ptr: &offset);
1001
1002 if (log && log->GetVerbose()) {
1003 size_t count = stack.size();
1004 LLDB_LOGF(log, "Stack before operation has %" PRIu64 " values:",
1005 (uint64_t)count);
1006 for (size_t i = 0; i < count; ++i) {
1007 StreamString new_value;
1008 new_value.Printf(format: "[%" PRIu64 "]", (uint64_t)i);
1009 stack[i].Dump(strm: &new_value);
1010 LLDB_LOGF(log, " %s", new_value.GetData());
1011 }
1012 LLDB_LOGF(log, "0x%8.8" PRIx64 ": %s", op_offset,
1013 DW_OP_value_to_name(op));
1014 }
1015
1016 if (std::optional<unsigned> arity =
1017 llvm::dwarf::OperationArity(O: static_cast<LocationAtom>(op))) {
1018 if (stack.size() < *arity)
1019 return llvm::createStringError(
1020 Fmt: "%s needs at least %d stack entries (stack has %d entries)",
1021 Vals: DW_OP_value_to_name(val: op), Vals: *arity, Vals: stack.size());
1022 }
1023
1024 switch (op) {
1025 // The DW_OP_addr operation has a single operand that encodes a machine
1026 // address and whose size is the size of an address on the target machine.
1027 case DW_OP_addr:
1028 stack.push_back(x: Scalar(opcodes.GetAddress(offset_ptr: &offset)));
1029 if (target &&
1030 target->GetArchitecture().GetCore() == ArchSpec::eCore_wasm32) {
1031 // wasm file sections aren't mapped into memory, therefore addresses can
1032 // never point into a file section and are always LoadAddresses.
1033 stack.back().SetValueType(Value::ValueType::LoadAddress);
1034 } else {
1035 stack.back().SetValueType(Value::ValueType::FileAddress);
1036 }
1037 break;
1038
1039 // The DW_OP_addr_sect_offset4 is used for any location expressions in
1040 // shared libraries that have a location like:
1041 // DW_OP_addr(0x1000)
1042 // If this address resides in a shared library, then this virtual address
1043 // won't make sense when it is evaluated in the context of a running
1044 // process where shared libraries have been slid. To account for this, this
1045 // new address type where we can store the section pointer and a 4 byte
1046 // offset.
1047 // case DW_OP_addr_sect_offset4:
1048 // {
1049 // result_type = eResultTypeFileAddress;
1050 // lldb::Section *sect = (lldb::Section
1051 // *)opcodes.GetMaxU64(&offset, sizeof(void *));
1052 // lldb::addr_t sect_offset = opcodes.GetU32(&offset);
1053 //
1054 // Address so_addr (sect, sect_offset);
1055 // lldb::addr_t load_addr = so_addr.GetLoadAddress();
1056 // if (load_addr != LLDB_INVALID_ADDRESS)
1057 // {
1058 // // We successfully resolve a file address to a load
1059 // // address.
1060 // stack.push_back(load_addr);
1061 // break;
1062 // }
1063 // else
1064 // {
1065 // // We were able
1066 // if (error_ptr)
1067 // error_ptr->SetErrorStringWithFormat ("Section %s in
1068 // %s is not currently loaded.\n",
1069 // sect->GetName().AsCString(),
1070 // sect->GetModule()->GetFileSpec().GetFilename().AsCString());
1071 // return false;
1072 // }
1073 // }
1074 // break;
1075
1076 // OPCODE: DW_OP_deref
1077 // OPERANDS: none
1078 // DESCRIPTION: Pops the top stack entry and treats it as an address.
1079 // The value retrieved from that address is pushed. The size of the data
1080 // retrieved from the dereferenced address is the size of an address on the
1081 // target machine.
1082 case DW_OP_deref: {
1083 if (llvm::Error err =
1084 Evaluate_DW_OP_deref(stack, exe_ctx, module_sp, process))
1085 return err;
1086 } break;
1087
1088 // OPCODE: DW_OP_deref_size
1089 // OPERANDS: 1
1090 // 1 - uint8_t that specifies the size of the data to dereference.
1091 // DESCRIPTION: Behaves like the DW_OP_deref operation: it pops the top
1092 // stack entry and treats it as an address. The value retrieved from that
1093 // address is pushed. In the DW_OP_deref_size operation, however, the size
1094 // in bytes of the data retrieved from the dereferenced address is
1095 // specified by the single operand. This operand is a 1-byte unsigned
1096 // integral constant whose value may not be larger than the size of an
1097 // address on the target machine. The data retrieved is zero extended to
1098 // the size of an address on the target machine before being pushed on the
1099 // expression stack.
1100 case DW_OP_deref_size: {
1101 if (stack.empty()) {
1102 return llvm::createStringError(
1103 Fmt: "expression stack empty for DW_OP_deref_size");
1104 }
1105 uint8_t size = opcodes.GetU8(offset_ptr: &offset);
1106 if (size > 8) {
1107 return llvm::createStringError(
1108 Fmt: "Invalid address size for DW_OP_deref_size: %d\n", Vals: size);
1109 }
1110 Value::ValueType value_type = stack.back().GetValueType();
1111 switch (value_type) {
1112 case Value::ValueType::HostAddress: {
1113 void *src = (void *)stack.back().GetScalar().ULongLong();
1114 intptr_t ptr;
1115 ::memcpy(dest: &ptr, src: src, n: sizeof(void *));
1116 // I can't decide whether the size operand should apply to the bytes in
1117 // their
1118 // lldb-host endianness or the target endianness.. I doubt this'll ever
1119 // come up but I'll opt for assuming big endian regardless.
1120 switch (size) {
1121 case 1:
1122 ptr = ptr & 0xff;
1123 break;
1124 case 2:
1125 ptr = ptr & 0xffff;
1126 break;
1127 case 3:
1128 ptr = ptr & 0xffffff;
1129 break;
1130 case 4:
1131 ptr = ptr & 0xffffffff;
1132 break;
1133 // the casts are added to work around the case where intptr_t is a 32
1134 // bit quantity;
1135 // presumably we won't hit the 5..7 cases if (void*) is 32-bits in this
1136 // program.
1137 case 5:
1138 ptr = (intptr_t)ptr & 0xffffffffffULL;
1139 break;
1140 case 6:
1141 ptr = (intptr_t)ptr & 0xffffffffffffULL;
1142 break;
1143 case 7:
1144 ptr = (intptr_t)ptr & 0xffffffffffffffULL;
1145 break;
1146 default:
1147 break;
1148 }
1149 stack.back().GetScalar() = ptr;
1150 stack.back().ClearContext();
1151 } break;
1152 case Value::ValueType::FileAddress: {
1153 auto file_addr =
1154 stack.back().GetScalar().ULongLong(LLDB_INVALID_ADDRESS);
1155 Address so_addr;
1156 auto maybe_load_addr = ResolveLoadAddress(
1157 exe_ctx, module_sp, dw_op_type: "DW_OP_deref_size", file_addr, so_addr,
1158 /*check_sectionoffset=*/true);
1159
1160 if (!maybe_load_addr)
1161 return maybe_load_addr.takeError();
1162
1163 addr_t load_addr = *maybe_load_addr;
1164
1165 if (load_addr == LLDB_INVALID_ADDRESS && so_addr.IsSectionOffset()) {
1166 uint8_t addr_bytes[8];
1167 Status error;
1168
1169 if (target &&
1170 target->ReadMemory(addr: so_addr, dst: &addr_bytes, dst_len: size, error,
1171 /*force_live_memory=*/false) == size) {
1172 ObjectFile *objfile = module_sp->GetObjectFile();
1173
1174 stack.back().GetScalar() = DerefSizeExtractDataHelper(
1175 addr_bytes, size_addr_bytes: size, byte_order: objfile->GetByteOrder(), size);
1176 stack.back().ClearContext();
1177 break;
1178 } else {
1179 return llvm::createStringError(
1180 Fmt: "Failed to dereference pointer for DW_OP_deref_size: "
1181 "%s\n",
1182 Vals: error.AsCString());
1183 }
1184 }
1185 stack.back().GetScalar() = load_addr;
1186 // Fall through to load address promotion code below.
1187 }
1188
1189 [[fallthrough]];
1190 case Value::ValueType::Scalar:
1191 case Value::ValueType::LoadAddress:
1192 if (exe_ctx) {
1193 if (process) {
1194 lldb::addr_t pointer_addr =
1195 stack.back().GetScalar().ULongLong(LLDB_INVALID_ADDRESS);
1196 uint8_t addr_bytes[sizeof(lldb::addr_t)];
1197 Status error;
1198 if (process->ReadMemory(vm_addr: pointer_addr, buf: &addr_bytes, size, error) ==
1199 size) {
1200
1201 stack.back().GetScalar() =
1202 DerefSizeExtractDataHelper(addr_bytes, size_addr_bytes: sizeof(addr_bytes),
1203 byte_order: process->GetByteOrder(), size);
1204 stack.back().ClearContext();
1205 } else {
1206 return llvm::createStringError(
1207 Fmt: "Failed to dereference pointer from 0x%" PRIx64
1208 " for DW_OP_deref: %s\n",
1209 Vals: pointer_addr, Vals: error.AsCString());
1210 }
1211 } else {
1212
1213 return llvm::createStringError(Fmt: "NULL process for DW_OP_deref_size");
1214 }
1215 } else {
1216 return llvm::createStringError(
1217 Fmt: "NULL execution context for DW_OP_deref_size");
1218 }
1219 break;
1220
1221 case Value::ValueType::Invalid:
1222
1223 return llvm::createStringError(Fmt: "invalid value for DW_OP_deref_size");
1224 }
1225
1226 } break;
1227
1228 // OPCODE: DW_OP_xderef_size
1229 // OPERANDS: 1
1230 // 1 - uint8_t that specifies the size of the data to dereference.
1231 // DESCRIPTION: Behaves like the DW_OP_xderef operation: the entry at
1232 // the top of the stack is treated as an address. The second stack entry is
1233 // treated as an "address space identifier" for those architectures that
1234 // support multiple address spaces. The top two stack elements are popped,
1235 // a data item is retrieved through an implementation-defined address
1236 // calculation and pushed as the new stack top. In the DW_OP_xderef_size
1237 // operation, however, the size in bytes of the data retrieved from the
1238 // dereferenced address is specified by the single operand. This operand is
1239 // a 1-byte unsigned integral constant whose value may not be larger than
1240 // the size of an address on the target machine. The data retrieved is zero
1241 // extended to the size of an address on the target machine before being
1242 // pushed on the expression stack.
1243 case DW_OP_xderef_size:
1244 return llvm::createStringError(Fmt: "unimplemented opcode: DW_OP_xderef_size");
1245 // OPCODE: DW_OP_xderef
1246 // OPERANDS: none
1247 // DESCRIPTION: Provides an extended dereference mechanism. The entry at
1248 // the top of the stack is treated as an address. The second stack entry is
1249 // treated as an "address space identifier" for those architectures that
1250 // support multiple address spaces. The top two stack elements are popped,
1251 // a data item is retrieved through an implementation-defined address
1252 // calculation and pushed as the new stack top. The size of the data
1253 // retrieved from the dereferenced address is the size of an address on the
1254 // target machine.
1255 case DW_OP_xderef:
1256 return llvm::createStringError(Fmt: "unimplemented opcode: DW_OP_xderef");
1257
1258 // All DW_OP_constXXX opcodes have a single operand as noted below:
1259 //
1260 // Opcode Operand 1
1261 // DW_OP_const1u 1-byte unsigned integer constant
1262 // DW_OP_const1s 1-byte signed integer constant
1263 // DW_OP_const2u 2-byte unsigned integer constant
1264 // DW_OP_const2s 2-byte signed integer constant
1265 // DW_OP_const4u 4-byte unsigned integer constant
1266 // DW_OP_const4s 4-byte signed integer constant
1267 // DW_OP_const8u 8-byte unsigned integer constant
1268 // DW_OP_const8s 8-byte signed integer constant
1269 // DW_OP_constu unsigned LEB128 integer constant
1270 // DW_OP_consts signed LEB128 integer constant
1271 case DW_OP_const1u:
1272 stack.push_back(x: to_generic(opcodes.GetU8(offset_ptr: &offset)));
1273 break;
1274 case DW_OP_const1s:
1275 stack.push_back(x: to_generic((int8_t)opcodes.GetU8(offset_ptr: &offset)));
1276 break;
1277 case DW_OP_const2u:
1278 stack.push_back(x: to_generic(opcodes.GetU16(offset_ptr: &offset)));
1279 break;
1280 case DW_OP_const2s:
1281 stack.push_back(x: to_generic((int16_t)opcodes.GetU16(offset_ptr: &offset)));
1282 break;
1283 case DW_OP_const4u:
1284 stack.push_back(x: to_generic(opcodes.GetU32(offset_ptr: &offset)));
1285 break;
1286 case DW_OP_const4s:
1287 stack.push_back(x: to_generic((int32_t)opcodes.GetU32(offset_ptr: &offset)));
1288 break;
1289 case DW_OP_const8u:
1290 stack.push_back(x: to_generic(opcodes.GetU64(offset_ptr: &offset)));
1291 break;
1292 case DW_OP_const8s:
1293 stack.push_back(x: to_generic((int64_t)opcodes.GetU64(offset_ptr: &offset)));
1294 break;
1295 // These should also use to_generic, but we can't do that due to a
1296 // producer-side bug in llvm. See llvm.org/pr48087.
1297 case DW_OP_constu:
1298 stack.push_back(x: Scalar(opcodes.GetULEB128(offset_ptr: &offset)));
1299 break;
1300 case DW_OP_consts:
1301 stack.push_back(x: Scalar(opcodes.GetSLEB128(offset_ptr: &offset)));
1302 break;
1303
1304 // OPCODE: DW_OP_dup
1305 // OPERANDS: none
1306 // DESCRIPTION: duplicates the value at the top of the stack
1307 case DW_OP_dup:
1308 if (stack.empty()) {
1309 return llvm::createStringError(Fmt: "expression stack empty for DW_OP_dup");
1310 } else
1311 stack.push_back(x: stack.back());
1312 break;
1313
1314 // OPCODE: DW_OP_drop
1315 // OPERANDS: none
1316 // DESCRIPTION: pops the value at the top of the stack
1317 case DW_OP_drop:
1318 if (stack.empty()) {
1319 return llvm::createStringError(Fmt: "expression stack empty for DW_OP_drop");
1320 } else
1321 stack.pop_back();
1322 break;
1323
1324 // OPCODE: DW_OP_over
1325 // OPERANDS: none
1326 // DESCRIPTION: Duplicates the entry currently second in the stack at
1327 // the top of the stack.
1328 case DW_OP_over:
1329 stack.push_back(x: stack[stack.size() - 2]);
1330 break;
1331
1332 // OPCODE: DW_OP_pick
1333 // OPERANDS: uint8_t index into the current stack
1334 // DESCRIPTION: The stack entry with the specified index (0 through 255,
1335 // inclusive) is pushed on the stack
1336 case DW_OP_pick: {
1337 uint8_t pick_idx = opcodes.GetU8(offset_ptr: &offset);
1338 if (pick_idx < stack.size())
1339 stack.push_back(x: stack[stack.size() - 1 - pick_idx]);
1340 else {
1341 return llvm::createStringError(
1342 Fmt: "Index %u out of range for DW_OP_pick.\n", Vals: pick_idx);
1343 }
1344 } break;
1345
1346 // OPCODE: DW_OP_swap
1347 // OPERANDS: none
1348 // DESCRIPTION: swaps the top two stack entries. The entry at the top
1349 // of the stack becomes the second stack entry, and the second entry
1350 // becomes the top of the stack
1351 case DW_OP_swap:
1352 tmp = stack.back();
1353 stack.back() = stack[stack.size() - 2];
1354 stack[stack.size() - 2] = tmp;
1355 break;
1356
1357 // OPCODE: DW_OP_rot
1358 // OPERANDS: none
1359 // DESCRIPTION: Rotates the first three stack entries. The entry at
1360 // the top of the stack becomes the third stack entry, the second entry
1361 // becomes the top of the stack, and the third entry becomes the second
1362 // entry.
1363 case DW_OP_rot: {
1364 size_t last_idx = stack.size() - 1;
1365 Value old_top = stack[last_idx];
1366 stack[last_idx] = stack[last_idx - 1];
1367 stack[last_idx - 1] = stack[last_idx - 2];
1368 stack[last_idx - 2] = old_top;
1369 } break;
1370
1371 // OPCODE: DW_OP_abs
1372 // OPERANDS: none
1373 // DESCRIPTION: pops the top stack entry, interprets it as a signed
1374 // value and pushes its absolute value. If the absolute value can not be
1375 // represented, the result is undefined.
1376 case DW_OP_abs:
1377 if (!stack.back().ResolveValue(exe_ctx).AbsoluteValue()) {
1378 return llvm::createStringError(
1379 Fmt: "failed to take the absolute value of the first stack item");
1380 }
1381 break;
1382
1383 // OPCODE: DW_OP_and
1384 // OPERANDS: none
1385 // DESCRIPTION: pops the top two stack values, performs a bitwise and
1386 // operation on the two, and pushes the result.
1387 case DW_OP_and:
1388 tmp = stack.back();
1389 stack.pop_back();
1390 stack.back().ResolveValue(exe_ctx) =
1391 stack.back().ResolveValue(exe_ctx) & tmp.ResolveValue(exe_ctx);
1392 break;
1393
1394 // OPCODE: DW_OP_div
1395 // OPERANDS: none
1396 // DESCRIPTION: pops the top two stack values, divides the former second
1397 // entry by the former top of the stack using signed division, and pushes
1398 // the result.
1399 case DW_OP_div: {
1400 tmp = stack.back();
1401 if (tmp.ResolveValue(exe_ctx).IsZero())
1402 return llvm::createStringError(Fmt: "divide by zero");
1403
1404 stack.pop_back();
1405 Scalar divisor, dividend;
1406 divisor = tmp.ResolveValue(exe_ctx);
1407 dividend = stack.back().ResolveValue(exe_ctx);
1408 divisor.MakeSigned();
1409 dividend.MakeSigned();
1410 stack.back() = dividend / divisor;
1411
1412 if (!stack.back().ResolveValue(exe_ctx).IsValid())
1413 return llvm::createStringError(Fmt: "divide failed");
1414 } break;
1415
1416 // OPCODE: DW_OP_minus
1417 // OPERANDS: none
1418 // DESCRIPTION: pops the top two stack values, subtracts the former top
1419 // of the stack from the former second entry, and pushes the result.
1420 case DW_OP_minus:
1421 tmp = stack.back();
1422 stack.pop_back();
1423 stack.back().ResolveValue(exe_ctx) =
1424 stack.back().ResolveValue(exe_ctx) - tmp.ResolveValue(exe_ctx);
1425 break;
1426
1427 // OPCODE: DW_OP_mod
1428 // OPERANDS: none
1429 // DESCRIPTION: pops the top two stack values and pushes the result of
1430 // the calculation: former second stack entry modulo the former top of the
1431 // stack.
1432 case DW_OP_mod:
1433 tmp = stack.back();
1434 stack.pop_back();
1435 stack.back().ResolveValue(exe_ctx) =
1436 stack.back().ResolveValue(exe_ctx) % tmp.ResolveValue(exe_ctx);
1437 break;
1438
1439 // OPCODE: DW_OP_mul
1440 // OPERANDS: none
1441 // DESCRIPTION: pops the top two stack entries, multiplies them
1442 // together, and pushes the result.
1443 case DW_OP_mul:
1444 tmp = stack.back();
1445 stack.pop_back();
1446 stack.back().ResolveValue(exe_ctx) =
1447 stack.back().ResolveValue(exe_ctx) * tmp.ResolveValue(exe_ctx);
1448 break;
1449
1450 // OPCODE: DW_OP_neg
1451 // OPERANDS: none
1452 // DESCRIPTION: pops the top stack entry, and pushes its negation.
1453 case DW_OP_neg:
1454 if (!stack.back().ResolveValue(exe_ctx).UnaryNegate())
1455 return llvm::createStringError(Fmt: "unary negate failed");
1456 break;
1457
1458 // OPCODE: DW_OP_not
1459 // OPERANDS: none
1460 // DESCRIPTION: pops the top stack entry, and pushes its bitwise
1461 // complement
1462 case DW_OP_not:
1463 if (!stack.back().ResolveValue(exe_ctx).OnesComplement())
1464 return llvm::createStringError(Fmt: "logical NOT failed");
1465 break;
1466
1467 // OPCODE: DW_OP_or
1468 // OPERANDS: none
1469 // DESCRIPTION: pops the top two stack entries, performs a bitwise or
1470 // operation on the two, and pushes the result.
1471 case DW_OP_or:
1472 tmp = stack.back();
1473 stack.pop_back();
1474 stack.back().ResolveValue(exe_ctx) =
1475 stack.back().ResolveValue(exe_ctx) | tmp.ResolveValue(exe_ctx);
1476 break;
1477
1478 // OPCODE: DW_OP_plus
1479 // OPERANDS: none
1480 // DESCRIPTION: pops the top two stack entries, adds them together, and
1481 // pushes the result.
1482 case DW_OP_plus:
1483 tmp = stack.back();
1484 stack.pop_back();
1485 stack.back().GetScalar() += tmp.GetScalar();
1486 break;
1487
1488 // OPCODE: DW_OP_plus_uconst
1489 // OPERANDS: none
1490 // DESCRIPTION: pops the top stack entry, adds it to the unsigned LEB128
1491 // constant operand and pushes the result.
1492 case DW_OP_plus_uconst: {
1493 const uint64_t uconst_value = opcodes.GetULEB128(offset_ptr: &offset);
1494 // Implicit conversion from a UINT to a Scalar...
1495 stack.back().GetScalar() += uconst_value;
1496 if (!stack.back().GetScalar().IsValid())
1497 return llvm::createStringError(Fmt: "DW_OP_plus_uconst failed");
1498 } break;
1499
1500 // OPCODE: DW_OP_shl
1501 // OPERANDS: none
1502 // DESCRIPTION: pops the top two stack entries, shifts the former
1503 // second entry left by the number of bits specified by the former top of
1504 // the stack, and pushes the result.
1505 case DW_OP_shl:
1506 tmp = stack.back();
1507 stack.pop_back();
1508 stack.back().ResolveValue(exe_ctx) <<= tmp.ResolveValue(exe_ctx);
1509 break;
1510
1511 // OPCODE: DW_OP_shr
1512 // OPERANDS: none
1513 // DESCRIPTION: pops the top two stack entries, shifts the former second
1514 // entry right logically (filling with zero bits) by the number of bits
1515 // specified by the former top of the stack, and pushes the result.
1516 case DW_OP_shr:
1517 tmp = stack.back();
1518 stack.pop_back();
1519 if (!stack.back().ResolveValue(exe_ctx).ShiftRightLogical(
1520 rhs: tmp.ResolveValue(exe_ctx)))
1521 return llvm::createStringError(Fmt: "DW_OP_shr failed");
1522 break;
1523
1524 // OPCODE: DW_OP_shra
1525 // OPERANDS: none
1526 // DESCRIPTION: pops the top two stack entries, shifts the former second
1527 // entry right arithmetically (divide the magnitude by 2, keep the same
1528 // sign for the result) by the number of bits specified by the former top
1529 // of the stack, and pushes the result.
1530 case DW_OP_shra:
1531 tmp = stack.back();
1532 stack.pop_back();
1533 stack.back().ResolveValue(exe_ctx) >>= tmp.ResolveValue(exe_ctx);
1534 break;
1535
1536 // OPCODE: DW_OP_xor
1537 // OPERANDS: none
1538 // DESCRIPTION: pops the top two stack entries, performs the bitwise
1539 // exclusive-or operation on the two, and pushes the result.
1540 case DW_OP_xor:
1541 tmp = stack.back();
1542 stack.pop_back();
1543 stack.back().ResolveValue(exe_ctx) =
1544 stack.back().ResolveValue(exe_ctx) ^ tmp.ResolveValue(exe_ctx);
1545 break;
1546
1547 // OPCODE: DW_OP_skip
1548 // OPERANDS: int16_t
1549 // DESCRIPTION: An unconditional branch. Its single operand is a 2-byte
1550 // signed integer constant. The 2-byte constant is the number of bytes of
1551 // the DWARF expression to skip forward or backward from the current
1552 // operation, beginning after the 2-byte constant.
1553 case DW_OP_skip: {
1554 int16_t skip_offset = (int16_t)opcodes.GetU16(offset_ptr: &offset);
1555 lldb::offset_t new_offset = offset + skip_offset;
1556 // New offset can point at the end of the data, in this case we should
1557 // terminate the DWARF expression evaluation (will happen in the loop
1558 // condition).
1559 if (new_offset <= opcodes.GetByteSize())
1560 offset = new_offset;
1561 else {
1562 return llvm::createStringError(S: llvm::formatv(
1563 Fmt: "Invalid opcode offset in DW_OP_skip: {0}+({1}) > {2}", Vals&: offset,
1564 Vals&: skip_offset, Vals: opcodes.GetByteSize()));
1565 }
1566 } break;
1567
1568 // OPCODE: DW_OP_bra
1569 // OPERANDS: int16_t
1570 // DESCRIPTION: A conditional branch. Its single operand is a 2-byte
1571 // signed integer constant. This operation pops the top of stack. If the
1572 // value popped is not the constant 0, the 2-byte constant operand is the
1573 // number of bytes of the DWARF expression to skip forward or backward from
1574 // the current operation, beginning after the 2-byte constant.
1575 case DW_OP_bra: {
1576 tmp = stack.back();
1577 stack.pop_back();
1578 int16_t bra_offset = (int16_t)opcodes.GetU16(offset_ptr: &offset);
1579 Scalar zero(0);
1580 if (tmp.ResolveValue(exe_ctx) != zero) {
1581 lldb::offset_t new_offset = offset + bra_offset;
1582 // New offset can point at the end of the data, in this case we should
1583 // terminate the DWARF expression evaluation (will happen in the loop
1584 // condition).
1585 if (new_offset <= opcodes.GetByteSize())
1586 offset = new_offset;
1587 else {
1588 return llvm::createStringError(S: llvm::formatv(
1589 Fmt: "Invalid opcode offset in DW_OP_bra: {0}+({1}) > {2}", Vals&: offset,
1590 Vals&: bra_offset, Vals: opcodes.GetByteSize()));
1591 }
1592 }
1593 } break;
1594
1595 // OPCODE: DW_OP_eq
1596 // OPERANDS: none
1597 // DESCRIPTION: pops the top two stack values, compares using the
1598 // equals (==) operator.
1599 // STACK RESULT: push the constant value 1 onto the stack if the result
1600 // of the operation is true or the constant value 0 if the result of the
1601 // operation is false.
1602 case DW_OP_eq:
1603 tmp = stack.back();
1604 stack.pop_back();
1605 stack.back().ResolveValue(exe_ctx) =
1606 stack.back().ResolveValue(exe_ctx) == tmp.ResolveValue(exe_ctx);
1607 break;
1608
1609 // OPCODE: DW_OP_ge
1610 // OPERANDS: none
1611 // DESCRIPTION: pops the top two stack values, compares using the
1612 // greater than or equal to (>=) operator.
1613 // STACK RESULT: push the constant value 1 onto the stack if the result
1614 // of the operation is true or the constant value 0 if the result of the
1615 // operation is false.
1616 case DW_OP_ge:
1617 tmp = stack.back();
1618 stack.pop_back();
1619 stack.back().ResolveValue(exe_ctx) =
1620 stack.back().ResolveValue(exe_ctx) >= tmp.ResolveValue(exe_ctx);
1621 break;
1622
1623 // OPCODE: DW_OP_gt
1624 // OPERANDS: none
1625 // DESCRIPTION: pops the top two stack values, compares using the
1626 // greater than (>) operator.
1627 // STACK RESULT: push the constant value 1 onto the stack if the result
1628 // of the operation is true or the constant value 0 if the result of the
1629 // operation is false.
1630 case DW_OP_gt:
1631 tmp = stack.back();
1632 stack.pop_back();
1633 stack.back().ResolveValue(exe_ctx) =
1634 stack.back().ResolveValue(exe_ctx) > tmp.ResolveValue(exe_ctx);
1635 break;
1636
1637 // OPCODE: DW_OP_le
1638 // OPERANDS: none
1639 // DESCRIPTION: pops the top two stack values, compares using the
1640 // less than or equal to (<=) operator.
1641 // STACK RESULT: push the constant value 1 onto the stack if the result
1642 // of the operation is true or the constant value 0 if the result of the
1643 // operation is false.
1644 case DW_OP_le:
1645 tmp = stack.back();
1646 stack.pop_back();
1647 stack.back().ResolveValue(exe_ctx) =
1648 stack.back().ResolveValue(exe_ctx) <= tmp.ResolveValue(exe_ctx);
1649 break;
1650
1651 // OPCODE: DW_OP_lt
1652 // OPERANDS: none
1653 // DESCRIPTION: pops the top two stack values, compares using the
1654 // less than (<) operator.
1655 // STACK RESULT: push the constant value 1 onto the stack if the result
1656 // of the operation is true or the constant value 0 if the result of the
1657 // operation is false.
1658 case DW_OP_lt:
1659 tmp = stack.back();
1660 stack.pop_back();
1661 stack.back().ResolveValue(exe_ctx) =
1662 stack.back().ResolveValue(exe_ctx) < tmp.ResolveValue(exe_ctx);
1663 break;
1664
1665 // OPCODE: DW_OP_ne
1666 // OPERANDS: none
1667 // DESCRIPTION: pops the top two stack values, compares using the
1668 // not equal (!=) operator.
1669 // STACK RESULT: push the constant value 1 onto the stack if the result
1670 // of the operation is true or the constant value 0 if the result of the
1671 // operation is false.
1672 case DW_OP_ne:
1673 tmp = stack.back();
1674 stack.pop_back();
1675 stack.back().ResolveValue(exe_ctx) =
1676 stack.back().ResolveValue(exe_ctx) != tmp.ResolveValue(exe_ctx);
1677 break;
1678
1679 // OPCODE: DW_OP_litn
1680 // OPERANDS: none
1681 // DESCRIPTION: encode the unsigned literal values from 0 through 31.
1682 // STACK RESULT: push the unsigned literal constant value onto the top
1683 // of the stack.
1684 case DW_OP_lit0:
1685 case DW_OP_lit1:
1686 case DW_OP_lit2:
1687 case DW_OP_lit3:
1688 case DW_OP_lit4:
1689 case DW_OP_lit5:
1690 case DW_OP_lit6:
1691 case DW_OP_lit7:
1692 case DW_OP_lit8:
1693 case DW_OP_lit9:
1694 case DW_OP_lit10:
1695 case DW_OP_lit11:
1696 case DW_OP_lit12:
1697 case DW_OP_lit13:
1698 case DW_OP_lit14:
1699 case DW_OP_lit15:
1700 case DW_OP_lit16:
1701 case DW_OP_lit17:
1702 case DW_OP_lit18:
1703 case DW_OP_lit19:
1704 case DW_OP_lit20:
1705 case DW_OP_lit21:
1706 case DW_OP_lit22:
1707 case DW_OP_lit23:
1708 case DW_OP_lit24:
1709 case DW_OP_lit25:
1710 case DW_OP_lit26:
1711 case DW_OP_lit27:
1712 case DW_OP_lit28:
1713 case DW_OP_lit29:
1714 case DW_OP_lit30:
1715 case DW_OP_lit31:
1716 stack.push_back(x: to_generic(op - DW_OP_lit0));
1717 break;
1718
1719 // OPCODE: DW_OP_regN
1720 // OPERANDS: none
1721 // DESCRIPTION: Push the value in register n on the top of the stack.
1722 case DW_OP_reg0:
1723 case DW_OP_reg1:
1724 case DW_OP_reg2:
1725 case DW_OP_reg3:
1726 case DW_OP_reg4:
1727 case DW_OP_reg5:
1728 case DW_OP_reg6:
1729 case DW_OP_reg7:
1730 case DW_OP_reg8:
1731 case DW_OP_reg9:
1732 case DW_OP_reg10:
1733 case DW_OP_reg11:
1734 case DW_OP_reg12:
1735 case DW_OP_reg13:
1736 case DW_OP_reg14:
1737 case DW_OP_reg15:
1738 case DW_OP_reg16:
1739 case DW_OP_reg17:
1740 case DW_OP_reg18:
1741 case DW_OP_reg19:
1742 case DW_OP_reg20:
1743 case DW_OP_reg21:
1744 case DW_OP_reg22:
1745 case DW_OP_reg23:
1746 case DW_OP_reg24:
1747 case DW_OP_reg25:
1748 case DW_OP_reg26:
1749 case DW_OP_reg27:
1750 case DW_OP_reg28:
1751 case DW_OP_reg29:
1752 case DW_OP_reg30:
1753 case DW_OP_reg31: {
1754 dwarf4_location_description_kind = Register;
1755 reg_num = op - DW_OP_reg0;
1756
1757 if (llvm::Error err =
1758 ReadRegisterValueAsScalar(reg_ctx, reg_kind, reg_num, value&: tmp))
1759 return err;
1760 stack.push_back(x: tmp);
1761 } break;
1762 // OPCODE: DW_OP_regx
1763 // OPERANDS:
1764 // ULEB128 literal operand that encodes the register.
1765 // DESCRIPTION: Push the value in register on the top of the stack.
1766 case DW_OP_regx: {
1767 dwarf4_location_description_kind = Register;
1768 reg_num = opcodes.GetULEB128(offset_ptr: &offset);
1769 Status read_err;
1770 if (llvm::Error err =
1771 ReadRegisterValueAsScalar(reg_ctx, reg_kind, reg_num, value&: tmp))
1772 return err;
1773 stack.push_back(x: tmp);
1774 } break;
1775
1776 // OPCODE: DW_OP_bregN
1777 // OPERANDS:
1778 // SLEB128 offset from register N
1779 // DESCRIPTION: Value is in memory at the address specified by register
1780 // N plus an offset.
1781 case DW_OP_breg0:
1782 case DW_OP_breg1:
1783 case DW_OP_breg2:
1784 case DW_OP_breg3:
1785 case DW_OP_breg4:
1786 case DW_OP_breg5:
1787 case DW_OP_breg6:
1788 case DW_OP_breg7:
1789 case DW_OP_breg8:
1790 case DW_OP_breg9:
1791 case DW_OP_breg10:
1792 case DW_OP_breg11:
1793 case DW_OP_breg12:
1794 case DW_OP_breg13:
1795 case DW_OP_breg14:
1796 case DW_OP_breg15:
1797 case DW_OP_breg16:
1798 case DW_OP_breg17:
1799 case DW_OP_breg18:
1800 case DW_OP_breg19:
1801 case DW_OP_breg20:
1802 case DW_OP_breg21:
1803 case DW_OP_breg22:
1804 case DW_OP_breg23:
1805 case DW_OP_breg24:
1806 case DW_OP_breg25:
1807 case DW_OP_breg26:
1808 case DW_OP_breg27:
1809 case DW_OP_breg28:
1810 case DW_OP_breg29:
1811 case DW_OP_breg30:
1812 case DW_OP_breg31: {
1813 reg_num = op - DW_OP_breg0;
1814 if (llvm::Error err =
1815 ReadRegisterValueAsScalar(reg_ctx, reg_kind, reg_num, value&: tmp))
1816 return err;
1817
1818 int64_t breg_offset = opcodes.GetSLEB128(offset_ptr: &offset);
1819 tmp.ResolveValue(exe_ctx) += (uint64_t)breg_offset;
1820 tmp.ClearContext();
1821 stack.push_back(x: tmp);
1822 stack.back().SetValueType(Value::ValueType::LoadAddress);
1823 } break;
1824 // OPCODE: DW_OP_bregx
1825 // OPERANDS: 2
1826 // ULEB128 literal operand that encodes the register.
1827 // SLEB128 offset from register N
1828 // DESCRIPTION: Value is in memory at the address specified by register
1829 // N plus an offset.
1830 case DW_OP_bregx: {
1831 reg_num = opcodes.GetULEB128(offset_ptr: &offset);
1832 if (llvm::Error err =
1833 ReadRegisterValueAsScalar(reg_ctx, reg_kind, reg_num, value&: tmp))
1834 return err;
1835
1836 int64_t breg_offset = opcodes.GetSLEB128(offset_ptr: &offset);
1837 tmp.ResolveValue(exe_ctx) += (uint64_t)breg_offset;
1838 tmp.ClearContext();
1839 stack.push_back(x: tmp);
1840 stack.back().SetValueType(Value::ValueType::LoadAddress);
1841 } break;
1842
1843 case DW_OP_fbreg:
1844 if (exe_ctx) {
1845 if (frame) {
1846 Scalar value;
1847 if (llvm::Error err = frame->GetFrameBaseValue(value))
1848 return err;
1849 int64_t fbreg_offset = opcodes.GetSLEB128(offset_ptr: &offset);
1850 value += fbreg_offset;
1851 stack.push_back(x: value);
1852 stack.back().SetValueType(Value::ValueType::LoadAddress);
1853 } else {
1854 return llvm::createStringError(
1855 Fmt: "invalid stack frame in context for DW_OP_fbreg opcode");
1856 }
1857 } else {
1858 return llvm::createStringError(
1859 Fmt: "NULL execution context for DW_OP_fbreg");
1860 }
1861
1862 break;
1863
1864 // OPCODE: DW_OP_nop
1865 // OPERANDS: none
1866 // DESCRIPTION: A place holder. It has no effect on the location stack
1867 // or any of its values.
1868 case DW_OP_nop:
1869 break;
1870
1871 // OPCODE: DW_OP_piece
1872 // OPERANDS: 1
1873 // ULEB128: byte size of the piece
1874 // DESCRIPTION: The operand describes the size in bytes of the piece of
1875 // the object referenced by the DWARF expression whose result is at the top
1876 // of the stack. If the piece is located in a register, but does not occupy
1877 // the entire register, the placement of the piece within that register is
1878 // defined by the ABI.
1879 //
1880 // Many compilers store a single variable in sets of registers, or store a
1881 // variable partially in memory and partially in registers. DW_OP_piece
1882 // provides a way of describing how large a part of a variable a particular
1883 // DWARF expression refers to.
1884 case DW_OP_piece: {
1885 LocationDescriptionKind piece_locdesc = dwarf4_location_description_kind;
1886 // Reset for the next piece.
1887 dwarf4_location_description_kind = Memory;
1888
1889 const uint64_t piece_byte_size = opcodes.GetULEB128(offset_ptr: &offset);
1890
1891 if (piece_byte_size > 0) {
1892 Value curr_piece;
1893
1894 if (stack.empty()) {
1895 UpdateValueTypeFromLocationDescription(
1896 log, dwarf_cu, kind: LocationDescriptionKind::Empty);
1897 // In a multi-piece expression, this means that the current piece is
1898 // not available. Fill with zeros for now by resizing the data and
1899 // appending it
1900 curr_piece.ResizeData(len: piece_byte_size);
1901 // Note that "0" is not a correct value for the unknown bits.
1902 // It would be better to also return a mask of valid bits together
1903 // with the expression result, so the debugger can print missing
1904 // members as "<optimized out>" or something.
1905 ::memset(s: curr_piece.GetBuffer().GetBytes(), c: 0, n: piece_byte_size);
1906 pieces.AppendDataToHostBuffer(rhs: curr_piece);
1907 } else {
1908 Status error;
1909 // Extract the current piece into "curr_piece"
1910 Value curr_piece_source_value(stack.back());
1911 stack.pop_back();
1912 UpdateValueTypeFromLocationDescription(log, dwarf_cu, kind: piece_locdesc,
1913 value: &curr_piece_source_value);
1914
1915 const Value::ValueType curr_piece_source_value_type =
1916 curr_piece_source_value.GetValueType();
1917 Scalar &scalar = curr_piece_source_value.GetScalar();
1918 lldb::addr_t addr = scalar.ULongLong(LLDB_INVALID_ADDRESS);
1919 switch (curr_piece_source_value_type) {
1920 case Value::ValueType::Invalid:
1921 return llvm::createStringError(Fmt: "invalid value type");
1922 case Value::ValueType::FileAddress:
1923 if (target) {
1924 curr_piece_source_value.ConvertToLoadAddress(module: module_sp.get(),
1925 target);
1926 addr = scalar.ULongLong(LLDB_INVALID_ADDRESS);
1927 } else {
1928 return llvm::createStringError(
1929 Fmt: "unable to convert file address 0x%" PRIx64
1930 " to load address "
1931 "for DW_OP_piece(%" PRIu64 "): "
1932 "no target available",
1933 Vals: addr, Vals: piece_byte_size);
1934 }
1935 [[fallthrough]];
1936 case Value::ValueType::LoadAddress: {
1937 if (target) {
1938 if (curr_piece.ResizeData(len: piece_byte_size) == piece_byte_size) {
1939 if (target->ReadMemory(addr, dst: curr_piece.GetBuffer().GetBytes(),
1940 dst_len: piece_byte_size, error,
1941 /*force_live_memory=*/false) !=
1942 piece_byte_size) {
1943 const char *addr_type = (curr_piece_source_value_type ==
1944 Value::ValueType::LoadAddress)
1945 ? "load"
1946 : "file";
1947 return llvm::createStringError(
1948 Fmt: "failed to read memory DW_OP_piece(%" PRIu64
1949 ") from %s address 0x%" PRIx64,
1950 Vals: piece_byte_size, Vals: addr_type, Vals: addr);
1951 }
1952 } else {
1953 return llvm::createStringError(
1954 Fmt: "failed to resize the piece memory buffer for "
1955 "DW_OP_piece(%" PRIu64 ")",
1956 Vals: piece_byte_size);
1957 }
1958 }
1959 } break;
1960 case Value::ValueType::HostAddress: {
1961 return llvm::createStringError(
1962 Fmt: "failed to read memory DW_OP_piece(%" PRIu64
1963 ") from host address 0x%" PRIx64,
1964 Vals: piece_byte_size, Vals: addr);
1965 } break;
1966
1967 case Value::ValueType::Scalar: {
1968 uint32_t bit_size = piece_byte_size * 8;
1969 uint32_t bit_offset = 0;
1970 if (!scalar.ExtractBitfield(bit_size, bit_offset)) {
1971 return llvm::createStringError(
1972 Fmt: "unable to extract %" PRIu64 " bytes from a %" PRIu64
1973 " byte scalar value.",
1974 Vals: piece_byte_size,
1975 Vals: (uint64_t)curr_piece_source_value.GetScalar().GetByteSize());
1976 }
1977 // Create curr_piece with bit_size. By default Scalar
1978 // grows to the nearest host integer type.
1979 llvm::APInt fail_value(1, 0, false);
1980 llvm::APInt ap_int = scalar.UInt128(fail_value);
1981 assert(ap_int.getBitWidth() >= bit_size);
1982 llvm::ArrayRef<uint64_t> buf{ap_int.getRawData(),
1983 ap_int.getNumWords()};
1984 curr_piece.GetScalar() = Scalar(llvm::APInt(bit_size, buf));
1985 } break;
1986 }
1987
1988 // Check if this is the first piece?
1989 if (op_piece_offset == 0) {
1990 // This is the first piece, we should push it back onto the stack
1991 // so subsequent pieces will be able to access this piece and add
1992 // to it.
1993 if (pieces.AppendDataToHostBuffer(rhs: curr_piece) == 0) {
1994 return llvm::createStringError(Fmt: "failed to append piece data");
1995 }
1996 } else {
1997 // If this is the second or later piece there should be a value on
1998 // the stack.
1999 if (pieces.GetBuffer().GetByteSize() != op_piece_offset) {
2000 return llvm::createStringError(
2001 Fmt: "DW_OP_piece for offset %" PRIu64
2002 " but top of stack is of size %" PRIu64,
2003 Vals: op_piece_offset, Vals: pieces.GetBuffer().GetByteSize());
2004 }
2005
2006 if (pieces.AppendDataToHostBuffer(rhs: curr_piece) == 0)
2007 return llvm::createStringError(Fmt: "failed to append piece data");
2008 }
2009 }
2010 op_piece_offset += piece_byte_size;
2011 }
2012 } break;
2013
2014 case DW_OP_bit_piece: // 0x9d ULEB128 bit size, ULEB128 bit offset (DWARF3);
2015 if (stack.size() < 1) {
2016 UpdateValueTypeFromLocationDescription(log, dwarf_cu,
2017 kind: LocationDescriptionKind::Empty);
2018 // Reset for the next piece.
2019 dwarf4_location_description_kind = Memory;
2020 return llvm::createStringError(
2021 Fmt: "expression stack needs at least 1 item for DW_OP_bit_piece");
2022 } else {
2023 UpdateValueTypeFromLocationDescription(
2024 log, dwarf_cu, kind: dwarf4_location_description_kind, value: &stack.back());
2025 // Reset for the next piece.
2026 dwarf4_location_description_kind = Memory;
2027 const uint64_t piece_bit_size = opcodes.GetULEB128(offset_ptr: &offset);
2028 const uint64_t piece_bit_offset = opcodes.GetULEB128(offset_ptr: &offset);
2029 switch (stack.back().GetValueType()) {
2030 case Value::ValueType::Invalid:
2031 return llvm::createStringError(
2032 Fmt: "unable to extract bit value from invalid value");
2033 case Value::ValueType::Scalar: {
2034 if (!stack.back().GetScalar().ExtractBitfield(bit_size: piece_bit_size,
2035 bit_offset: piece_bit_offset)) {
2036 return llvm::createStringError(
2037 Fmt: "unable to extract %" PRIu64 " bit value with %" PRIu64
2038 " bit offset from a %" PRIu64 " bit scalar value.",
2039 Vals: piece_bit_size, Vals: piece_bit_offset,
2040 Vals: (uint64_t)(stack.back().GetScalar().GetByteSize() * 8));
2041 }
2042 } break;
2043
2044 case Value::ValueType::FileAddress:
2045 case Value::ValueType::LoadAddress:
2046 case Value::ValueType::HostAddress:
2047 return llvm::createStringError(
2048 Fmt: "unable to extract DW_OP_bit_piece(bit_size = %" PRIu64
2049 ", bit_offset = %" PRIu64 ") from an address value.",
2050 Vals: piece_bit_size, Vals: piece_bit_offset);
2051 }
2052 }
2053 break;
2054
2055 // OPCODE: DW_OP_implicit_value
2056 // OPERANDS: 2
2057 // ULEB128 size of the value block in bytes
2058 // uint8_t* block bytes encoding value in target's memory
2059 // representation
2060 // DESCRIPTION: Value is immediately stored in block in the debug info with
2061 // the memory representation of the target.
2062 case DW_OP_implicit_value: {
2063 dwarf4_location_description_kind = Implicit;
2064
2065 const uint32_t len = opcodes.GetULEB128(offset_ptr: &offset);
2066 const void *data = opcodes.GetData(offset_ptr: &offset, length: len);
2067
2068 if (!data) {
2069 LLDB_LOG(log, "Evaluate_DW_OP_implicit_value: could not be read data");
2070 return llvm::createStringError(Fmt: "could not evaluate %s",
2071 Vals: DW_OP_value_to_name(val: op));
2072 }
2073
2074 Value result(data, len);
2075 stack.push_back(x: result);
2076 break;
2077 }
2078
2079 case DW_OP_implicit_pointer: {
2080 dwarf4_location_description_kind = Implicit;
2081 return llvm::createStringError(Fmt: "Could not evaluate %s.",
2082 Vals: DW_OP_value_to_name(val: op));
2083 }
2084
2085 // OPCODE: DW_OP_push_object_address
2086 // OPERANDS: none
2087 // DESCRIPTION: Pushes the address of the object currently being
2088 // evaluated as part of evaluation of a user presented expression. This
2089 // object may correspond to an independent variable described by its own
2090 // DIE or it may be a component of an array, structure, or class whose
2091 // address has been dynamically determined by an earlier step during user
2092 // expression evaluation.
2093 case DW_OP_push_object_address:
2094 if (object_address_ptr)
2095 stack.push_back(x: *object_address_ptr);
2096 else {
2097 return llvm::createStringError(Fmt: "DW_OP_push_object_address used without "
2098 "specifying an object address");
2099 }
2100 break;
2101
2102 // OPCODE: DW_OP_call2
2103 // OPERANDS:
2104 // uint16_t compile unit relative offset of a DIE
2105 // DESCRIPTION: Performs subroutine calls during evaluation
2106 // of a DWARF expression. The operand is the 2-byte unsigned offset of a
2107 // debugging information entry in the current compilation unit.
2108 //
2109 // Operand interpretation is exactly like that for DW_FORM_ref2.
2110 //
2111 // This operation transfers control of DWARF expression evaluation to the
2112 // DW_AT_location attribute of the referenced DIE. If there is no such
2113 // attribute, then there is no effect. Execution of the DWARF expression of
2114 // a DW_AT_location attribute may add to and/or remove from values on the
2115 // stack. Execution returns to the point following the call when the end of
2116 // the attribute is reached. Values on the stack at the time of the call
2117 // may be used as parameters by the called expression and values left on
2118 // the stack by the called expression may be used as return values by prior
2119 // agreement between the calling and called expressions.
2120 case DW_OP_call2:
2121 return llvm::createStringError(Fmt: "unimplemented opcode DW_OP_call2");
2122 // OPCODE: DW_OP_call4
2123 // OPERANDS: 1
2124 // uint32_t compile unit relative offset of a DIE
2125 // DESCRIPTION: Performs a subroutine call during evaluation of a DWARF
2126 // expression. For DW_OP_call4, the operand is a 4-byte unsigned offset of
2127 // a debugging information entry in the current compilation unit.
2128 //
2129 // Operand interpretation DW_OP_call4 is exactly like that for
2130 // DW_FORM_ref4.
2131 //
2132 // This operation transfers control of DWARF expression evaluation to the
2133 // DW_AT_location attribute of the referenced DIE. If there is no such
2134 // attribute, then there is no effect. Execution of the DWARF expression of
2135 // a DW_AT_location attribute may add to and/or remove from values on the
2136 // stack. Execution returns to the point following the call when the end of
2137 // the attribute is reached. Values on the stack at the time of the call
2138 // may be used as parameters by the called expression and values left on
2139 // the stack by the called expression may be used as return values by prior
2140 // agreement between the calling and called expressions.
2141 case DW_OP_call4:
2142 return llvm::createStringError(Fmt: "unimplemented opcode DW_OP_call4");
2143
2144 // OPCODE: DW_OP_stack_value
2145 // OPERANDS: None
2146 // DESCRIPTION: Specifies that the object does not exist in memory but
2147 // rather is a constant value. The value from the top of the stack is the
2148 // value to be used. This is the actual object value and not the location.
2149 case DW_OP_stack_value:
2150 dwarf4_location_description_kind = Implicit;
2151 stack.back().SetValueType(Value::ValueType::Scalar);
2152 break;
2153
2154 // OPCODE: DW_OP_convert
2155 // OPERANDS: 1
2156 // A ULEB128 that is either a DIE offset of a
2157 // DW_TAG_base_type or 0 for the generic (pointer-sized) type.
2158 //
2159 // DESCRIPTION: Pop the top stack element, convert it to a
2160 // different type, and push the result.
2161 case DW_OP_convert: {
2162 const uint64_t relative_die_offset = opcodes.GetULEB128(offset_ptr: &offset);
2163 uint64_t bit_size;
2164 bool sign;
2165 if (relative_die_offset == 0) {
2166 // The generic type has the size of an address on the target
2167 // machine and an unspecified signedness. Scalar has no
2168 // "unspecified signedness", so we use unsigned types.
2169 if (!module_sp)
2170 return llvm::createStringError(Fmt: "no module");
2171 sign = false;
2172 bit_size = module_sp->GetArchitecture().GetAddressByteSize() * 8;
2173 if (!bit_size)
2174 return llvm::createStringError(Fmt: "unspecified architecture");
2175 } else {
2176 auto bit_size_sign_or_err =
2177 dwarf_cu->GetDIEBitSizeAndSign(relative_die_offset);
2178 if (!bit_size_sign_or_err)
2179 return bit_size_sign_or_err.takeError();
2180 bit_size = bit_size_sign_or_err->first;
2181 sign = bit_size_sign_or_err->second;
2182 }
2183 Scalar &top = stack.back().ResolveValue(exe_ctx);
2184 top.TruncOrExtendTo(bits: bit_size, sign);
2185 break;
2186 }
2187
2188 // OPCODE: DW_OP_call_frame_cfa
2189 // OPERANDS: None
2190 // DESCRIPTION: Specifies a DWARF expression that pushes the value of
2191 // the canonical frame address consistent with the call frame information
2192 // located in .debug_frame (or in the FDEs of the eh_frame section).
2193 case DW_OP_call_frame_cfa:
2194 if (frame) {
2195 // Note that we don't have to parse FDEs because this DWARF expression
2196 // is commonly evaluated with a valid stack frame.
2197 StackID id = frame->GetStackID();
2198 addr_t cfa = id.GetCallFrameAddress();
2199 if (cfa != LLDB_INVALID_ADDRESS) {
2200 stack.push_back(x: Scalar(cfa));
2201 stack.back().SetValueType(Value::ValueType::LoadAddress);
2202 } else {
2203 return llvm::createStringError(
2204 Fmt: "stack frame does not include a canonical "
2205 "frame address for DW_OP_call_frame_cfa "
2206 "opcode");
2207 }
2208 } else {
2209 return llvm::createStringError(Fmt: "unvalid stack frame in context for "
2210 "DW_OP_call_frame_cfa opcode");
2211 }
2212 break;
2213
2214 // OPCODE: DW_OP_form_tls_address (or the old pre-DWARFv3 vendor extension
2215 // opcode, DW_OP_GNU_push_tls_address)
2216 // OPERANDS: none
2217 // DESCRIPTION: Pops a TLS offset from the stack, converts it to
2218 // an address in the current thread's thread-local storage block, and
2219 // pushes it on the stack.
2220 case DW_OP_form_tls_address:
2221 case DW_OP_GNU_push_tls_address: {
2222 if (stack.size() < 1) {
2223 if (op == DW_OP_form_tls_address)
2224 return llvm::createStringError(
2225 Fmt: "DW_OP_form_tls_address needs an argument");
2226 else
2227 return llvm::createStringError(
2228 Fmt: "DW_OP_GNU_push_tls_address needs an argument");
2229 }
2230
2231 if (!exe_ctx || !module_sp)
2232 return llvm::createStringError(Fmt: "no context to evaluate TLS within");
2233
2234 Thread *thread = exe_ctx->GetThreadPtr();
2235 if (!thread)
2236 return llvm::createStringError(Fmt: "no thread to evaluate TLS within");
2237
2238 // Lookup the TLS block address for this thread and module.
2239 const addr_t tls_file_addr =
2240 stack.back().GetScalar().ULongLong(LLDB_INVALID_ADDRESS);
2241 const addr_t tls_load_addr =
2242 thread->GetThreadLocalData(module: module_sp, tls_file_addr);
2243
2244 if (tls_load_addr == LLDB_INVALID_ADDRESS)
2245 return llvm::createStringError(
2246 Fmt: "no TLS data currently exists for this thread");
2247
2248 stack.back().GetScalar() = tls_load_addr;
2249 stack.back().SetValueType(Value::ValueType::LoadAddress);
2250 } break;
2251
2252 // OPCODE: DW_OP_addrx (DW_OP_GNU_addr_index is the legacy name.)
2253 // OPERANDS: 1
2254 // ULEB128: index to the .debug_addr section
2255 // DESCRIPTION: Pushes an address to the stack from the .debug_addr
2256 // section with the base address specified by the DW_AT_addr_base attribute
2257 // and the 0 based index is the ULEB128 encoded index.
2258 case DW_OP_addrx:
2259 case DW_OP_GNU_addr_index: {
2260 if (!dwarf_cu)
2261 return llvm::createStringError(Fmt: "DW_OP_GNU_addr_index found without a "
2262 "compile unit being specified");
2263 uint64_t index = opcodes.GetULEB128(offset_ptr: &offset);
2264 lldb::addr_t value = dwarf_cu->ReadAddressFromDebugAddrSection(index);
2265 stack.push_back(x: Scalar(value));
2266 if (target &&
2267 target->GetArchitecture().GetCore() == ArchSpec::eCore_wasm32) {
2268 // wasm file sections aren't mapped into memory, therefore addresses can
2269 // never point into a file section and are always LoadAddresses.
2270 stack.back().SetValueType(Value::ValueType::LoadAddress);
2271 } else {
2272 stack.back().SetValueType(Value::ValueType::FileAddress);
2273 }
2274 } break;
2275
2276 // OPCODE: DW_OP_GNU_const_index
2277 // OPERANDS: 1
2278 // ULEB128: index to the .debug_addr section
2279 // DESCRIPTION: Pushes an constant with the size of a machine address to
2280 // the stack from the .debug_addr section with the base address specified
2281 // by the DW_AT_addr_base attribute and the 0 based index is the ULEB128
2282 // encoded index.
2283 case DW_OP_GNU_const_index: {
2284 if (!dwarf_cu) {
2285 return llvm::createStringError(Fmt: "DW_OP_GNU_const_index found without a "
2286 "compile unit being specified");
2287 }
2288 uint64_t index = opcodes.GetULEB128(offset_ptr: &offset);
2289 lldb::addr_t value = dwarf_cu->ReadAddressFromDebugAddrSection(index);
2290 stack.push_back(x: Scalar(value));
2291 } break;
2292
2293 case DW_OP_GNU_entry_value:
2294 case DW_OP_entry_value: {
2295 if (llvm::Error err = Evaluate_DW_OP_entry_value(stack, exe_ctx, reg_ctx,
2296 opcodes, opcode_offset&: offset, log))
2297 return llvm::createStringError(
2298 Fmt: "could not evaluate DW_OP_entry_value: %s",
2299 Vals: llvm::toString(E: std::move(err)).c_str());
2300 break;
2301 }
2302
2303 default:
2304 if (dwarf_cu) {
2305 if (dwarf_cu->ParseVendorDWARFOpcode(op, opcodes, offset, stack)) {
2306 break;
2307 }
2308 }
2309 return llvm::createStringError(S: llvm::formatv(
2310 Fmt: "Unhandled opcode {0} in DWARFExpression", Vals: LocationAtom(op)));
2311 }
2312 }
2313
2314 if (stack.empty()) {
2315 // Nothing on the stack, check if we created a piece value from DW_OP_piece
2316 // or DW_OP_bit_piece opcodes
2317 if (pieces.GetBuffer().GetByteSize())
2318 return pieces;
2319
2320 return llvm::createStringError(Fmt: "stack empty after evaluation");
2321 }
2322
2323 UpdateValueTypeFromLocationDescription(
2324 log, dwarf_cu, kind: dwarf4_location_description_kind, value: &stack.back());
2325
2326 if (log && log->GetVerbose()) {
2327 size_t count = stack.size();
2328 LLDB_LOGF(log,
2329 "Stack after operation has %" PRIu64 " values:", (uint64_t)count);
2330 for (size_t i = 0; i < count; ++i) {
2331 StreamString new_value;
2332 new_value.Printf(format: "[%" PRIu64 "]", (uint64_t)i);
2333 stack[i].Dump(strm: &new_value);
2334 LLDB_LOGF(log, " %s", new_value.GetData());
2335 }
2336 }
2337 return stack.back();
2338}
2339
2340bool DWARFExpression::MatchesOperand(
2341 StackFrame &frame, const Instruction::Operand &operand) const {
2342 using namespace OperandMatchers;
2343
2344 RegisterContextSP reg_ctx_sp = frame.GetRegisterContext();
2345 if (!reg_ctx_sp) {
2346 return false;
2347 }
2348
2349 DataExtractor opcodes(m_data);
2350
2351 lldb::offset_t op_offset = 0;
2352 uint8_t opcode = opcodes.GetU8(offset_ptr: &op_offset);
2353
2354 if (opcode == DW_OP_fbreg) {
2355 int64_t offset = opcodes.GetSLEB128(offset_ptr: &op_offset);
2356
2357 DWARFExpressionList *fb_expr = frame.GetFrameBaseExpression(error_ptr: nullptr);
2358 if (!fb_expr) {
2359 return false;
2360 }
2361
2362 auto recurse = [&frame, fb_expr](const Instruction::Operand &child) {
2363 return fb_expr->MatchesOperand(frame, operand: child);
2364 };
2365
2366 if (!offset &&
2367 MatchUnaryOp(base: MatchOpType(type: Instruction::Operand::Type::Dereference),
2368 child: recurse)(operand)) {
2369 return true;
2370 }
2371
2372 return MatchUnaryOp(
2373 base: MatchOpType(type: Instruction::Operand::Type::Dereference),
2374 child: MatchBinaryOp(base: MatchOpType(type: Instruction::Operand::Type::Sum),
2375 left: MatchImmOp(imm: offset), right: recurse))(operand);
2376 }
2377
2378 bool dereference = false;
2379 const RegisterInfo *reg = nullptr;
2380 int64_t offset = 0;
2381
2382 if (opcode >= DW_OP_reg0 && opcode <= DW_OP_reg31) {
2383 reg = reg_ctx_sp->GetRegisterInfo(reg_kind: m_reg_kind, reg_num: opcode - DW_OP_reg0);
2384 } else if (opcode >= DW_OP_breg0 && opcode <= DW_OP_breg31) {
2385 offset = opcodes.GetSLEB128(offset_ptr: &op_offset);
2386 reg = reg_ctx_sp->GetRegisterInfo(reg_kind: m_reg_kind, reg_num: opcode - DW_OP_breg0);
2387 } else if (opcode == DW_OP_regx) {
2388 uint32_t reg_num = static_cast<uint32_t>(opcodes.GetULEB128(offset_ptr: &op_offset));
2389 reg = reg_ctx_sp->GetRegisterInfo(reg_kind: m_reg_kind, reg_num);
2390 } else if (opcode == DW_OP_bregx) {
2391 uint32_t reg_num = static_cast<uint32_t>(opcodes.GetULEB128(offset_ptr: &op_offset));
2392 offset = opcodes.GetSLEB128(offset_ptr: &op_offset);
2393 reg = reg_ctx_sp->GetRegisterInfo(reg_kind: m_reg_kind, reg_num);
2394 } else {
2395 return false;
2396 }
2397
2398 if (!reg) {
2399 return false;
2400 }
2401
2402 if (dereference) {
2403 if (!offset &&
2404 MatchUnaryOp(base: MatchOpType(type: Instruction::Operand::Type::Dereference),
2405 child: MatchRegOp(info: *reg))(operand)) {
2406 return true;
2407 }
2408
2409 return MatchUnaryOp(
2410 base: MatchOpType(type: Instruction::Operand::Type::Dereference),
2411 child: MatchBinaryOp(base: MatchOpType(type: Instruction::Operand::Type::Sum),
2412 left: MatchRegOp(info: *reg), right: MatchImmOp(imm: offset)))(operand);
2413 } else {
2414 return MatchRegOp(info: *reg)(operand);
2415 }
2416}
2417

source code of lldb/source/Expression/DWARFExpression.cpp