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