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