1 //===-- DWARFExpression.cpp -------------------------------------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "lldb/Expression/DWARFExpression.h"
10 
11 #include <inttypes.h>
12 
13 #include <vector>
14 
15 #include "lldb/Core/Module.h"
16 #include "lldb/Core/Value.h"
17 #include "lldb/Core/dwarf.h"
18 #include "lldb/Utility/DataEncoder.h"
19 #include "lldb/Utility/Log.h"
20 #include "lldb/Utility/RegisterValue.h"
21 #include "lldb/Utility/Scalar.h"
22 #include "lldb/Utility/StreamString.h"
23 #include "lldb/Utility/VMRange.h"
24 
25 #include "lldb/Host/Host.h"
26 #include "lldb/Utility/Endian.h"
27 
28 #include "lldb/Symbol/Function.h"
29 
30 #include "lldb/Target/ABI.h"
31 #include "lldb/Target/ExecutionContext.h"
32 #include "lldb/Target/Process.h"
33 #include "lldb/Target/RegisterContext.h"
34 #include "lldb/Target/StackFrame.h"
35 #include "lldb/Target/StackID.h"
36 #include "lldb/Target/Target.h"
37 #include "lldb/Target/Thread.h"
38 
39 #include "Plugins/SymbolFile/DWARF/DWARFUnit.h"
40 
41 using namespace lldb;
42 using namespace lldb_private;
43 
44 static lldb::addr_t
45 ReadAddressFromDebugAddrSection(const DWARFUnit *dwarf_cu,
46                                 uint32_t index) {
47   uint32_t index_size = dwarf_cu->GetAddressByteSize();
48   dw_offset_t addr_base = dwarf_cu->GetAddrBase();
49   lldb::offset_t offset = addr_base + index * index_size;
50   const DWARFDataExtractor &data =
51       dwarf_cu->GetSymbolFileDWARF().GetDWARFContext().getOrLoadAddrData();
52   if (data.ValidOffsetForDataOfSize(offset, index_size))
53     return data.GetMaxU64_unchecked(&offset, index_size);
54   return LLDB_INVALID_ADDRESS;
55 }
56 
57 /// Return the location list parser for the given format.
58 static std::unique_ptr<llvm::DWARFLocationTable>
59 GetLocationTable(DWARFExpression::LocationListFormat format, const DataExtractor &data) {
60   llvm::DWARFDataExtractor llvm_data(
61       toStringRef(data.GetData()),
62       data.GetByteOrder() == lldb::eByteOrderLittle, data.GetAddressByteSize());
63 
64   switch (format) {
65   case DWARFExpression::NonLocationList:
66     return nullptr;
67   // DWARF<=4 .debug_loc
68   case DWARFExpression::RegularLocationList:
69     return std::make_unique<llvm::DWARFDebugLoc>(llvm_data);
70   // Non-standard DWARF 4 extension (fission) .debug_loc.dwo
71   case DWARFExpression::SplitDwarfLocationList:
72   // DWARF 5 .debug_loclists(.dwo)
73   case DWARFExpression::LocLists:
74     return std::make_unique<llvm::DWARFDebugLoclists>(
75         llvm_data, format == DWARFExpression::LocLists ? 5 : 4);
76   }
77   llvm_unreachable("Invalid LocationListFormat!");
78 }
79 
80 // DWARFExpression constructor
81 DWARFExpression::DWARFExpression()
82     : m_module_wp(), m_data(), m_dwarf_cu(nullptr),
83       m_reg_kind(eRegisterKindDWARF) {}
84 
85 DWARFExpression::DWARFExpression(lldb::ModuleSP module_sp,
86                                  const DataExtractor &data,
87                                  const DWARFUnit *dwarf_cu)
88     : m_module_wp(), m_data(data), m_dwarf_cu(dwarf_cu),
89       m_reg_kind(eRegisterKindDWARF) {
90   if (module_sp)
91     m_module_wp = module_sp;
92 }
93 
94 // Destructor
95 DWARFExpression::~DWARFExpression() {}
96 
97 bool DWARFExpression::IsValid() const { return m_data.GetByteSize() > 0; }
98 
99 void DWARFExpression::UpdateValue(uint64_t const_value,
100                                   lldb::offset_t const_value_byte_size,
101                                   uint8_t addr_byte_size) {
102   if (!const_value_byte_size)
103     return;
104 
105   m_data.SetData(
106       DataBufferSP(new DataBufferHeap(&const_value, const_value_byte_size)));
107   m_data.SetByteOrder(endian::InlHostByteOrder());
108   m_data.SetAddressByteSize(addr_byte_size);
109 }
110 
111 void DWARFExpression::DumpLocation(Stream *s, const DataExtractor &data,
112                                    lldb::DescriptionLevel level,
113                                    ABI *abi) const {
114   llvm::DWARFExpression(data.GetAsLLVM(), llvm::dwarf::DWARF_VERSION,
115                         data.GetAddressByteSize())
116       .print(s->AsRawOstream(), abi ? &abi->GetMCRegisterInfo() : nullptr,
117              nullptr);
118 }
119 
120 void DWARFExpression::SetLocationListAddresses(addr_t cu_file_addr,
121                                                addr_t func_file_addr) {
122   m_loclist_addresses = LoclistAddresses{cu_file_addr, func_file_addr};
123 }
124 
125 int DWARFExpression::GetRegisterKind() { return m_reg_kind; }
126 
127 void DWARFExpression::SetRegisterKind(RegisterKind reg_kind) {
128   m_reg_kind = reg_kind;
129 }
130 
131 bool DWARFExpression::IsLocationList() const {
132   return bool(m_loclist_addresses);
133 }
134 
135 namespace {
136 /// Implement enough of the DWARFObject interface in order to be able to call
137 /// DWARFLocationTable::dumpLocationList. We don't have access to a real
138 /// DWARFObject here because DWARFExpression is used in non-DWARF scenarios too.
139 class DummyDWARFObject final: public llvm::DWARFObject {
140 public:
141   DummyDWARFObject(bool IsLittleEndian) : IsLittleEndian(IsLittleEndian) {}
142 
143   bool isLittleEndian() const override { return IsLittleEndian; }
144 
145   llvm::Optional<llvm::RelocAddrEntry> find(const llvm::DWARFSection &Sec,
146                                             uint64_t Pos) const override {
147     return llvm::None;
148   }
149 private:
150   bool IsLittleEndian;
151 };
152 }
153 
154 void DWARFExpression::GetDescription(Stream *s, lldb::DescriptionLevel level,
155                                      addr_t location_list_base_addr,
156                                      ABI *abi) const {
157   if (IsLocationList()) {
158     // We have a location list
159     lldb::offset_t offset = 0;
160     std::unique_ptr<llvm::DWARFLocationTable> loctable_up = GetLocationTable(
161         m_dwarf_cu->GetSymbolFileDWARF().GetLocationListFormat(), m_data);
162     if (!loctable_up)
163       return;
164 
165     llvm::MCRegisterInfo *MRI = abi ? &abi->GetMCRegisterInfo() : nullptr;
166 
167     loctable_up->dumpLocationList(
168         &offset, s->AsRawOstream(),
169         llvm::object::SectionedAddress{m_loclist_addresses->cu_file_addr}, MRI,
170         DummyDWARFObject(m_data.GetByteOrder() == eByteOrderLittle), nullptr,
171         llvm::DIDumpOptions(), s->GetIndentLevel() + 2);
172   } else {
173     // We have a normal location that contains DW_OP location opcodes
174     DumpLocation(s, m_data, level, abi);
175   }
176 }
177 
178 static bool ReadRegisterValueAsScalar(RegisterContext *reg_ctx,
179                                       lldb::RegisterKind reg_kind,
180                                       uint32_t reg_num, Status *error_ptr,
181                                       Value &value) {
182   if (reg_ctx == nullptr) {
183     if (error_ptr)
184       error_ptr->SetErrorStringWithFormat("No register context in frame.\n");
185   } else {
186     uint32_t native_reg =
187         reg_ctx->ConvertRegisterKindToRegisterNumber(reg_kind, reg_num);
188     if (native_reg == LLDB_INVALID_REGNUM) {
189       if (error_ptr)
190         error_ptr->SetErrorStringWithFormat("Unable to convert register "
191                                             "kind=%u reg_num=%u to a native "
192                                             "register number.\n",
193                                             reg_kind, reg_num);
194     } else {
195       const RegisterInfo *reg_info =
196           reg_ctx->GetRegisterInfoAtIndex(native_reg);
197       RegisterValue reg_value;
198       if (reg_ctx->ReadRegister(reg_info, reg_value)) {
199         if (reg_value.GetScalarValue(value.GetScalar())) {
200           value.SetValueType(Value::eValueTypeScalar);
201           value.SetContext(Value::eContextTypeRegisterInfo,
202                            const_cast<RegisterInfo *>(reg_info));
203           if (error_ptr)
204             error_ptr->Clear();
205           return true;
206         } else {
207           // If we get this error, then we need to implement a value buffer in
208           // the dwarf expression evaluation function...
209           if (error_ptr)
210             error_ptr->SetErrorStringWithFormat(
211                 "register %s can't be converted to a scalar value",
212                 reg_info->name);
213         }
214       } else {
215         if (error_ptr)
216           error_ptr->SetErrorStringWithFormat("register %s is not available",
217                                               reg_info->name);
218       }
219     }
220   }
221   return false;
222 }
223 
224 /// Return the length in bytes of the set of operands for \p op. No guarantees
225 /// are made on the state of \p data after this call.
226 static offset_t GetOpcodeDataSize(const DataExtractor &data,
227                                   const lldb::offset_t data_offset,
228                                   const uint8_t op) {
229   lldb::offset_t offset = data_offset;
230   switch (op) {
231   case DW_OP_addr:
232   case DW_OP_call_ref: // 0x9a 1 address sized offset of DIE (DWARF3)
233     return data.GetAddressByteSize();
234 
235   // Opcodes with no arguments
236   case DW_OP_deref:                // 0x06
237   case DW_OP_dup:                  // 0x12
238   case DW_OP_drop:                 // 0x13
239   case DW_OP_over:                 // 0x14
240   case DW_OP_swap:                 // 0x16
241   case DW_OP_rot:                  // 0x17
242   case DW_OP_xderef:               // 0x18
243   case DW_OP_abs:                  // 0x19
244   case DW_OP_and:                  // 0x1a
245   case DW_OP_div:                  // 0x1b
246   case DW_OP_minus:                // 0x1c
247   case DW_OP_mod:                  // 0x1d
248   case DW_OP_mul:                  // 0x1e
249   case DW_OP_neg:                  // 0x1f
250   case DW_OP_not:                  // 0x20
251   case DW_OP_or:                   // 0x21
252   case DW_OP_plus:                 // 0x22
253   case DW_OP_shl:                  // 0x24
254   case DW_OP_shr:                  // 0x25
255   case DW_OP_shra:                 // 0x26
256   case DW_OP_xor:                  // 0x27
257   case DW_OP_eq:                   // 0x29
258   case DW_OP_ge:                   // 0x2a
259   case DW_OP_gt:                   // 0x2b
260   case DW_OP_le:                   // 0x2c
261   case DW_OP_lt:                   // 0x2d
262   case DW_OP_ne:                   // 0x2e
263   case DW_OP_lit0:                 // 0x30
264   case DW_OP_lit1:                 // 0x31
265   case DW_OP_lit2:                 // 0x32
266   case DW_OP_lit3:                 // 0x33
267   case DW_OP_lit4:                 // 0x34
268   case DW_OP_lit5:                 // 0x35
269   case DW_OP_lit6:                 // 0x36
270   case DW_OP_lit7:                 // 0x37
271   case DW_OP_lit8:                 // 0x38
272   case DW_OP_lit9:                 // 0x39
273   case DW_OP_lit10:                // 0x3A
274   case DW_OP_lit11:                // 0x3B
275   case DW_OP_lit12:                // 0x3C
276   case DW_OP_lit13:                // 0x3D
277   case DW_OP_lit14:                // 0x3E
278   case DW_OP_lit15:                // 0x3F
279   case DW_OP_lit16:                // 0x40
280   case DW_OP_lit17:                // 0x41
281   case DW_OP_lit18:                // 0x42
282   case DW_OP_lit19:                // 0x43
283   case DW_OP_lit20:                // 0x44
284   case DW_OP_lit21:                // 0x45
285   case DW_OP_lit22:                // 0x46
286   case DW_OP_lit23:                // 0x47
287   case DW_OP_lit24:                // 0x48
288   case DW_OP_lit25:                // 0x49
289   case DW_OP_lit26:                // 0x4A
290   case DW_OP_lit27:                // 0x4B
291   case DW_OP_lit28:                // 0x4C
292   case DW_OP_lit29:                // 0x4D
293   case DW_OP_lit30:                // 0x4E
294   case DW_OP_lit31:                // 0x4f
295   case DW_OP_reg0:                 // 0x50
296   case DW_OP_reg1:                 // 0x51
297   case DW_OP_reg2:                 // 0x52
298   case DW_OP_reg3:                 // 0x53
299   case DW_OP_reg4:                 // 0x54
300   case DW_OP_reg5:                 // 0x55
301   case DW_OP_reg6:                 // 0x56
302   case DW_OP_reg7:                 // 0x57
303   case DW_OP_reg8:                 // 0x58
304   case DW_OP_reg9:                 // 0x59
305   case DW_OP_reg10:                // 0x5A
306   case DW_OP_reg11:                // 0x5B
307   case DW_OP_reg12:                // 0x5C
308   case DW_OP_reg13:                // 0x5D
309   case DW_OP_reg14:                // 0x5E
310   case DW_OP_reg15:                // 0x5F
311   case DW_OP_reg16:                // 0x60
312   case DW_OP_reg17:                // 0x61
313   case DW_OP_reg18:                // 0x62
314   case DW_OP_reg19:                // 0x63
315   case DW_OP_reg20:                // 0x64
316   case DW_OP_reg21:                // 0x65
317   case DW_OP_reg22:                // 0x66
318   case DW_OP_reg23:                // 0x67
319   case DW_OP_reg24:                // 0x68
320   case DW_OP_reg25:                // 0x69
321   case DW_OP_reg26:                // 0x6A
322   case DW_OP_reg27:                // 0x6B
323   case DW_OP_reg28:                // 0x6C
324   case DW_OP_reg29:                // 0x6D
325   case DW_OP_reg30:                // 0x6E
326   case DW_OP_reg31:                // 0x6F
327   case DW_OP_nop:                  // 0x96
328   case DW_OP_push_object_address:  // 0x97 DWARF3
329   case DW_OP_form_tls_address:     // 0x9b DWARF3
330   case DW_OP_call_frame_cfa:       // 0x9c DWARF3
331   case DW_OP_stack_value:          // 0x9f DWARF4
332   case DW_OP_GNU_push_tls_address: // 0xe0 GNU extension
333     return 0;
334 
335   // Opcodes with a single 1 byte arguments
336   case DW_OP_const1u:     // 0x08 1 1-byte constant
337   case DW_OP_const1s:     // 0x09 1 1-byte constant
338   case DW_OP_pick:        // 0x15 1 1-byte stack index
339   case DW_OP_deref_size:  // 0x94 1 1-byte size of data retrieved
340   case DW_OP_xderef_size: // 0x95 1 1-byte size of data retrieved
341     return 1;
342 
343   // Opcodes with a single 2 byte arguments
344   case DW_OP_const2u: // 0x0a 1 2-byte constant
345   case DW_OP_const2s: // 0x0b 1 2-byte constant
346   case DW_OP_skip:    // 0x2f 1 signed 2-byte constant
347   case DW_OP_bra:     // 0x28 1 signed 2-byte constant
348   case DW_OP_call2:   // 0x98 1 2-byte offset of DIE (DWARF3)
349     return 2;
350 
351   // Opcodes with a single 4 byte arguments
352   case DW_OP_const4u: // 0x0c 1 4-byte constant
353   case DW_OP_const4s: // 0x0d 1 4-byte constant
354   case DW_OP_call4:   // 0x99 1 4-byte offset of DIE (DWARF3)
355     return 4;
356 
357   // Opcodes with a single 8 byte arguments
358   case DW_OP_const8u: // 0x0e 1 8-byte constant
359   case DW_OP_const8s: // 0x0f 1 8-byte constant
360     return 8;
361 
362   // All opcodes that have a single ULEB (signed or unsigned) argument
363   case DW_OP_addrx:           // 0xa1 1 ULEB128 index
364   case DW_OP_constu:          // 0x10 1 ULEB128 constant
365   case DW_OP_consts:          // 0x11 1 SLEB128 constant
366   case DW_OP_plus_uconst:     // 0x23 1 ULEB128 addend
367   case DW_OP_breg0:           // 0x70 1 ULEB128 register
368   case DW_OP_breg1:           // 0x71 1 ULEB128 register
369   case DW_OP_breg2:           // 0x72 1 ULEB128 register
370   case DW_OP_breg3:           // 0x73 1 ULEB128 register
371   case DW_OP_breg4:           // 0x74 1 ULEB128 register
372   case DW_OP_breg5:           // 0x75 1 ULEB128 register
373   case DW_OP_breg6:           // 0x76 1 ULEB128 register
374   case DW_OP_breg7:           // 0x77 1 ULEB128 register
375   case DW_OP_breg8:           // 0x78 1 ULEB128 register
376   case DW_OP_breg9:           // 0x79 1 ULEB128 register
377   case DW_OP_breg10:          // 0x7a 1 ULEB128 register
378   case DW_OP_breg11:          // 0x7b 1 ULEB128 register
379   case DW_OP_breg12:          // 0x7c 1 ULEB128 register
380   case DW_OP_breg13:          // 0x7d 1 ULEB128 register
381   case DW_OP_breg14:          // 0x7e 1 ULEB128 register
382   case DW_OP_breg15:          // 0x7f 1 ULEB128 register
383   case DW_OP_breg16:          // 0x80 1 ULEB128 register
384   case DW_OP_breg17:          // 0x81 1 ULEB128 register
385   case DW_OP_breg18:          // 0x82 1 ULEB128 register
386   case DW_OP_breg19:          // 0x83 1 ULEB128 register
387   case DW_OP_breg20:          // 0x84 1 ULEB128 register
388   case DW_OP_breg21:          // 0x85 1 ULEB128 register
389   case DW_OP_breg22:          // 0x86 1 ULEB128 register
390   case DW_OP_breg23:          // 0x87 1 ULEB128 register
391   case DW_OP_breg24:          // 0x88 1 ULEB128 register
392   case DW_OP_breg25:          // 0x89 1 ULEB128 register
393   case DW_OP_breg26:          // 0x8a 1 ULEB128 register
394   case DW_OP_breg27:          // 0x8b 1 ULEB128 register
395   case DW_OP_breg28:          // 0x8c 1 ULEB128 register
396   case DW_OP_breg29:          // 0x8d 1 ULEB128 register
397   case DW_OP_breg30:          // 0x8e 1 ULEB128 register
398   case DW_OP_breg31:          // 0x8f 1 ULEB128 register
399   case DW_OP_regx:            // 0x90 1 ULEB128 register
400   case DW_OP_fbreg:           // 0x91 1 SLEB128 offset
401   case DW_OP_piece:           // 0x93 1 ULEB128 size of piece addressed
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     data.Skip_LEB128(&offset);
411     data.Skip_LEB128(&offset);
412     return offset - data_offset;
413 
414   case DW_OP_implicit_value: // 0x9e ULEB128 size followed by block of that size
415                              // (DWARF4)
416   {
417     uint64_t block_len = data.Skip_LEB128(&offset);
418     offset += block_len;
419     return offset - data_offset;
420   }
421 
422   case DW_OP_entry_value: // 0xa3 ULEB128 size + variable-length block
423   {
424     uint64_t subexpr_len = data.GetULEB128(&offset);
425     return (offset - data_offset) + subexpr_len;
426   }
427 
428   default:
429     break;
430   }
431   return LLDB_INVALID_OFFSET;
432 }
433 
434 lldb::addr_t DWARFExpression::GetLocation_DW_OP_addr(uint32_t op_addr_idx,
435                                                      bool &error) const {
436   error = false;
437   if (IsLocationList())
438     return LLDB_INVALID_ADDRESS;
439   lldb::offset_t offset = 0;
440   uint32_t curr_op_addr_idx = 0;
441   while (m_data.ValidOffset(offset)) {
442     const uint8_t op = m_data.GetU8(&offset);
443 
444     if (op == DW_OP_addr) {
445       const lldb::addr_t op_file_addr = m_data.GetAddress(&offset);
446       if (curr_op_addr_idx == op_addr_idx)
447         return op_file_addr;
448       else
449         ++curr_op_addr_idx;
450     } else if (op == DW_OP_GNU_addr_index || op == DW_OP_addrx) {
451       uint64_t index = m_data.GetULEB128(&offset);
452       if (curr_op_addr_idx == op_addr_idx) {
453         if (!m_dwarf_cu) {
454           error = true;
455           break;
456         }
457 
458         return ReadAddressFromDebugAddrSection(m_dwarf_cu, index);
459       } else
460         ++curr_op_addr_idx;
461     } else {
462       const offset_t op_arg_size = GetOpcodeDataSize(m_data, offset, op);
463       if (op_arg_size == LLDB_INVALID_OFFSET) {
464         error = true;
465         break;
466       }
467       offset += op_arg_size;
468     }
469   }
470   return LLDB_INVALID_ADDRESS;
471 }
472 
473 bool DWARFExpression::Update_DW_OP_addr(lldb::addr_t file_addr) {
474   if (IsLocationList())
475     return false;
476   lldb::offset_t offset = 0;
477   while (m_data.ValidOffset(offset)) {
478     const uint8_t op = m_data.GetU8(&offset);
479 
480     if (op == DW_OP_addr) {
481       const uint32_t addr_byte_size = m_data.GetAddressByteSize();
482       // We have to make a copy of the data as we don't know if this data is
483       // from a read only memory mapped buffer, so we duplicate all of the data
484       // first, then modify it, and if all goes well, we then replace the data
485       // for this expression
486 
487       // So first we copy the data into a heap buffer
488       std::unique_ptr<DataBufferHeap> head_data_up(
489           new DataBufferHeap(m_data.GetDataStart(), m_data.GetByteSize()));
490 
491       // Make en encoder so we can write the address into the buffer using the
492       // correct byte order (endianness)
493       DataEncoder encoder(head_data_up->GetBytes(), head_data_up->GetByteSize(),
494                           m_data.GetByteOrder(), addr_byte_size);
495 
496       // Replace the address in the new buffer
497       if (encoder.PutUnsigned(offset, addr_byte_size, file_addr) == UINT32_MAX)
498         return false;
499 
500       // All went well, so now we can reset the data using a shared pointer to
501       // the heap data so "m_data" will now correctly manage the heap data.
502       m_data.SetData(DataBufferSP(head_data_up.release()));
503       return true;
504     } else {
505       const offset_t op_arg_size = GetOpcodeDataSize(m_data, offset, op);
506       if (op_arg_size == LLDB_INVALID_OFFSET)
507         break;
508       offset += op_arg_size;
509     }
510   }
511   return false;
512 }
513 
514 bool DWARFExpression::ContainsThreadLocalStorage() const {
515   // We are assuming for now that any thread local variable will not have a
516   // location list. This has been true for all thread local variables we have
517   // seen so far produced by any compiler.
518   if (IsLocationList())
519     return false;
520   lldb::offset_t offset = 0;
521   while (m_data.ValidOffset(offset)) {
522     const uint8_t op = m_data.GetU8(&offset);
523 
524     if (op == DW_OP_form_tls_address || op == DW_OP_GNU_push_tls_address)
525       return true;
526     const offset_t op_arg_size = GetOpcodeDataSize(m_data, offset, op);
527     if (op_arg_size == LLDB_INVALID_OFFSET)
528       return false;
529     else
530       offset += op_arg_size;
531   }
532   return false;
533 }
534 bool DWARFExpression::LinkThreadLocalStorage(
535     lldb::ModuleSP new_module_sp,
536     std::function<lldb::addr_t(lldb::addr_t file_addr)> const
537         &link_address_callback) {
538   // We are assuming for now that any thread local variable will not have a
539   // location list. This has been true for all thread local variables we have
540   // seen so far produced by any compiler.
541   if (IsLocationList())
542     return false;
543 
544   const uint32_t addr_byte_size = m_data.GetAddressByteSize();
545   // We have to make a copy of the data as we don't know if this data is from a
546   // read only memory mapped buffer, so we duplicate all of the data first,
547   // then modify it, and if all goes well, we then replace the data for this
548   // expression
549 
550   // So first we copy the data into a heap buffer
551   std::shared_ptr<DataBufferHeap> heap_data_sp(
552       new DataBufferHeap(m_data.GetDataStart(), m_data.GetByteSize()));
553 
554   // Make en encoder so we can write the address into the buffer using the
555   // correct byte order (endianness)
556   DataEncoder encoder(heap_data_sp->GetBytes(), heap_data_sp->GetByteSize(),
557                       m_data.GetByteOrder(), addr_byte_size);
558 
559   lldb::offset_t offset = 0;
560   lldb::offset_t const_offset = 0;
561   lldb::addr_t const_value = 0;
562   size_t const_byte_size = 0;
563   while (m_data.ValidOffset(offset)) {
564     const uint8_t op = m_data.GetU8(&offset);
565 
566     bool decoded_data = false;
567     switch (op) {
568     case DW_OP_const4u:
569       // Remember the const offset in case we later have a
570       // DW_OP_form_tls_address or DW_OP_GNU_push_tls_address
571       const_offset = offset;
572       const_value = m_data.GetU32(&offset);
573       decoded_data = true;
574       const_byte_size = 4;
575       break;
576 
577     case DW_OP_const8u:
578       // Remember the const offset in case we later have a
579       // DW_OP_form_tls_address or DW_OP_GNU_push_tls_address
580       const_offset = offset;
581       const_value = m_data.GetU64(&offset);
582       decoded_data = true;
583       const_byte_size = 8;
584       break;
585 
586     case DW_OP_form_tls_address:
587     case DW_OP_GNU_push_tls_address:
588       // DW_OP_form_tls_address and DW_OP_GNU_push_tls_address must be preceded
589       // by a file address on the stack. We assume that DW_OP_const4u or
590       // DW_OP_const8u is used for these values, and we check that the last
591       // opcode we got before either of these was DW_OP_const4u or
592       // DW_OP_const8u. If so, then we can link the value accodingly. For
593       // Darwin, the value in the DW_OP_const4u or DW_OP_const8u is the file
594       // address of a structure that contains a function pointer, the pthread
595       // key and the offset into the data pointed to by the pthread key. So we
596       // must link this address and also set the module of this expression to
597       // the new_module_sp so we can resolve the file address correctly
598       if (const_byte_size > 0) {
599         lldb::addr_t linked_file_addr = link_address_callback(const_value);
600         if (linked_file_addr == LLDB_INVALID_ADDRESS)
601           return false;
602         // Replace the address in the new buffer
603         if (encoder.PutUnsigned(const_offset, const_byte_size,
604                                 linked_file_addr) == UINT32_MAX)
605           return false;
606       }
607       break;
608 
609     default:
610       const_offset = 0;
611       const_value = 0;
612       const_byte_size = 0;
613       break;
614     }
615 
616     if (!decoded_data) {
617       const offset_t op_arg_size = GetOpcodeDataSize(m_data, offset, op);
618       if (op_arg_size == LLDB_INVALID_OFFSET)
619         return false;
620       else
621         offset += op_arg_size;
622     }
623   }
624 
625   // If we linked the TLS address correctly, update the module so that when the
626   // expression is evaluated it can resolve the file address to a load address
627   // and read the
628   // TLS data
629   m_module_wp = new_module_sp;
630   m_data.SetData(heap_data_sp);
631   return true;
632 }
633 
634 bool DWARFExpression::LocationListContainsAddress(addr_t func_load_addr,
635                                                   lldb::addr_t addr) const {
636   if (func_load_addr == LLDB_INVALID_ADDRESS || addr == LLDB_INVALID_ADDRESS)
637     return false;
638 
639   if (!IsLocationList())
640     return false;
641 
642   return GetLocationExpression(func_load_addr, addr) != llvm::None;
643 }
644 
645 bool DWARFExpression::DumpLocationForAddress(Stream *s,
646                                              lldb::DescriptionLevel level,
647                                              addr_t func_load_addr,
648                                              addr_t address, ABI *abi) {
649   if (!IsLocationList()) {
650     DumpLocation(s, m_data, level, abi);
651     return true;
652   }
653   if (llvm::Optional<DataExtractor> expr =
654           GetLocationExpression(func_load_addr, address)) {
655     DumpLocation(s, *expr, level, abi);
656     return true;
657   }
658   return false;
659 }
660 
661 static bool Evaluate_DW_OP_entry_value(std::vector<Value> &stack,
662                                        ExecutionContext *exe_ctx,
663                                        RegisterContext *reg_ctx,
664                                        const DataExtractor &opcodes,
665                                        lldb::offset_t &opcode_offset,
666                                        Status *error_ptr, Log *log) {
667   // DW_OP_entry_value(sub-expr) describes the location a variable had upon
668   // function entry: this variable location is presumed to be optimized out at
669   // the current PC value.  The caller of the function may have call site
670   // information that describes an alternate location for the variable (e.g. a
671   // constant literal, or a spilled stack value) in the parent frame.
672   //
673   // Example (this is pseudo-code & pseudo-DWARF, but hopefully illustrative):
674   //
675   //     void child(int &sink, int x) {
676   //       ...
677   //       /* "x" gets optimized out. */
678   //
679   //       /* The location of "x" here is: DW_OP_entry_value($reg2). */
680   //       ++sink;
681   //     }
682   //
683   //     void parent() {
684   //       int sink;
685   //
686   //       /*
687   //        * The callsite information emitted here is:
688   //        *
689   //        * DW_TAG_call_site
690   //        *   DW_AT_return_pc ... (for "child(sink, 123);")
691   //        *   DW_TAG_call_site_parameter (for "sink")
692   //        *     DW_AT_location   ($reg1)
693   //        *     DW_AT_call_value ($SP - 8)
694   //        *   DW_TAG_call_site_parameter (for "x")
695   //        *     DW_AT_location   ($reg2)
696   //        *     DW_AT_call_value ($literal 123)
697   //        *
698   //        * DW_TAG_call_site
699   //        *   DW_AT_return_pc ... (for "child(sink, 456);")
700   //        *   ...
701   //        */
702   //       child(sink, 123);
703   //       child(sink, 456);
704   //     }
705   //
706   // When the program stops at "++sink" within `child`, the debugger determines
707   // the call site by analyzing the return address. Once the call site is found,
708   // the debugger determines which parameter is referenced by DW_OP_entry_value
709   // and evaluates the corresponding location for that parameter in `parent`.
710 
711   // 1. Find the function which pushed the current frame onto the stack.
712   if ((!exe_ctx || !exe_ctx->HasTargetScope()) || !reg_ctx) {
713     LLDB_LOG(log, "Evaluate_DW_OP_entry_value: no exe/reg context");
714     return false;
715   }
716 
717   StackFrame *current_frame = exe_ctx->GetFramePtr();
718   Thread *thread = exe_ctx->GetThreadPtr();
719   if (!current_frame || !thread) {
720     LLDB_LOG(log, "Evaluate_DW_OP_entry_value: no current frame/thread");
721     return false;
722   }
723 
724   Target &target = exe_ctx->GetTargetRef();
725   StackFrameSP parent_frame = nullptr;
726   addr_t return_pc = LLDB_INVALID_ADDRESS;
727   uint32_t current_frame_idx = current_frame->GetFrameIndex();
728   uint32_t num_frames = thread->GetStackFrameCount();
729   for (uint32_t parent_frame_idx = current_frame_idx + 1;
730        parent_frame_idx < num_frames; ++parent_frame_idx) {
731     parent_frame = thread->GetStackFrameAtIndex(parent_frame_idx);
732     // Require a valid sequence of frames.
733     if (!parent_frame)
734       break;
735 
736     // Record the first valid return address, even if this is an inlined frame,
737     // in order to look up the associated call edge in the first non-inlined
738     // parent frame.
739     if (return_pc == LLDB_INVALID_ADDRESS) {
740       return_pc = parent_frame->GetFrameCodeAddress().GetLoadAddress(&target);
741       LLDB_LOG(log,
742                "Evaluate_DW_OP_entry_value: immediate ancestor with pc = {0:x}",
743                return_pc);
744     }
745 
746     // If we've found an inlined frame, skip it (these have no call site
747     // parameters).
748     if (parent_frame->IsInlined())
749       continue;
750 
751     // We've found the first non-inlined parent frame.
752     break;
753   }
754   if (!parent_frame || !parent_frame->GetRegisterContext()) {
755     LLDB_LOG(log, "Evaluate_DW_OP_entry_value: no parent frame with reg ctx");
756     return false;
757   }
758 
759   Function *parent_func =
760       parent_frame->GetSymbolContext(eSymbolContextFunction).function;
761   if (!parent_func) {
762     LLDB_LOG(log, "Evaluate_DW_OP_entry_value: no parent function");
763     return false;
764   }
765 
766   // 2. Find the call edge in the parent function responsible for creating the
767   //    current activation.
768   Function *current_func =
769       current_frame->GetSymbolContext(eSymbolContextFunction).function;
770   if (!current_func) {
771     LLDB_LOG(log, "Evaluate_DW_OP_entry_value: no current function");
772     return false;
773   }
774 
775   CallEdge *call_edge = nullptr;
776   ModuleList &modlist = target.GetImages();
777   ExecutionContext parent_exe_ctx = *exe_ctx;
778   parent_exe_ctx.SetFrameSP(parent_frame);
779   if (!parent_frame->IsArtificial()) {
780     // If the parent frame is not artificial, the current activation may be
781     // produced by an ambiguous tail call. In this case, refuse to proceed.
782     call_edge = parent_func->GetCallEdgeForReturnAddress(return_pc, target);
783     if (!call_edge) {
784       LLDB_LOG(log,
785                "Evaluate_DW_OP_entry_value: no call edge for retn-pc = {0:x} "
786                "in parent frame {1}",
787                return_pc, parent_func->GetName());
788       return false;
789     }
790     Function *callee_func = call_edge->GetCallee(modlist, parent_exe_ctx);
791     if (callee_func != current_func) {
792       LLDB_LOG(log, "Evaluate_DW_OP_entry_value: ambiguous call sequence, "
793                     "can't find real parent frame");
794       return false;
795     }
796   } else {
797     // The StackFrameList solver machinery has deduced that an unambiguous tail
798     // call sequence that produced the current activation.  The first edge in
799     // the parent that points to the current function must be valid.
800     for (auto &edge : parent_func->GetTailCallingEdges()) {
801       if (edge->GetCallee(modlist, parent_exe_ctx) == current_func) {
802         call_edge = edge.get();
803         break;
804       }
805     }
806   }
807   if (!call_edge) {
808     LLDB_LOG(log, "Evaluate_DW_OP_entry_value: no unambiguous edge from parent "
809                   "to current function");
810     return false;
811   }
812 
813   // 3. Attempt to locate the DW_OP_entry_value expression in the set of
814   //    available call site parameters. If found, evaluate the corresponding
815   //    parameter in the context of the parent frame.
816   const uint32_t subexpr_len = opcodes.GetULEB128(&opcode_offset);
817   const void *subexpr_data = opcodes.GetData(&opcode_offset, subexpr_len);
818   if (!subexpr_data) {
819     LLDB_LOG(log, "Evaluate_DW_OP_entry_value: subexpr could not be read");
820     return false;
821   }
822 
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_len);
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_len) == 0) {
843       matched_param = &param;
844       break;
845     }
846   }
847   if (!matched_param) {
848     LLDB_LOG(log,
849              "Evaluate_DW_OP_entry_value: no matching call site param found");
850     return false;
851   }
852 
853   // TODO: Add support for DW_OP_push_object_address within a DW_OP_entry_value
854   // subexpresion whenever llvm does.
855   Value result;
856   const DWARFExpression &param_expr = matched_param->LocationInCaller;
857   if (!param_expr.Evaluate(&parent_exe_ctx,
858                            parent_frame->GetRegisterContext().get(),
859                            /*loclist_base_addr=*/LLDB_INVALID_ADDRESS,
860                            /*initial_value_ptr=*/nullptr,
861                            /*object_address_ptr=*/nullptr, result, error_ptr)) {
862     LLDB_LOG(log,
863              "Evaluate_DW_OP_entry_value: call site param evaluation failed");
864     return false;
865   }
866 
867   stack.push_back(result);
868   return true;
869 }
870 
871 bool DWARFExpression::Evaluate(ExecutionContextScope *exe_scope,
872                                lldb::addr_t loclist_base_load_addr,
873                                const Value *initial_value_ptr,
874                                const Value *object_address_ptr, Value &result,
875                                Status *error_ptr) const {
876   ExecutionContext exe_ctx(exe_scope);
877   return Evaluate(&exe_ctx, nullptr, loclist_base_load_addr, initial_value_ptr,
878                   object_address_ptr, result, error_ptr);
879 }
880 
881 bool DWARFExpression::Evaluate(ExecutionContext *exe_ctx,
882                                RegisterContext *reg_ctx,
883                                lldb::addr_t func_load_addr,
884                                const Value *initial_value_ptr,
885                                const Value *object_address_ptr, Value &result,
886                                Status *error_ptr) const {
887   ModuleSP module_sp = m_module_wp.lock();
888 
889   if (IsLocationList()) {
890     addr_t pc;
891     StackFrame *frame = nullptr;
892     if (reg_ctx)
893       pc = reg_ctx->GetPC();
894     else {
895       frame = exe_ctx->GetFramePtr();
896       if (!frame)
897         return false;
898       RegisterContextSP reg_ctx_sp = frame->GetRegisterContext();
899       if (!reg_ctx_sp)
900         return false;
901       pc = reg_ctx_sp->GetPC();
902     }
903 
904     if (func_load_addr != LLDB_INVALID_ADDRESS) {
905       if (pc == LLDB_INVALID_ADDRESS) {
906         if (error_ptr)
907           error_ptr->SetErrorString("Invalid PC in frame.");
908         return false;
909       }
910 
911       if (llvm::Optional<DataExtractor> expr =
912               GetLocationExpression(func_load_addr, pc)) {
913         return DWARFExpression::Evaluate(
914             exe_ctx, reg_ctx, module_sp, *expr, m_dwarf_cu, m_reg_kind,
915             initial_value_ptr, object_address_ptr, result, error_ptr);
916       }
917     }
918     if (error_ptr)
919       error_ptr->SetErrorString("variable not available");
920     return false;
921   }
922 
923   // Not a location list, just a single expression.
924   return DWARFExpression::Evaluate(exe_ctx, reg_ctx, module_sp, m_data,
925                                    m_dwarf_cu, m_reg_kind, initial_value_ptr,
926                                    object_address_ptr, result, error_ptr);
927 }
928 
929 bool DWARFExpression::Evaluate(
930     ExecutionContext *exe_ctx, RegisterContext *reg_ctx,
931     lldb::ModuleSP module_sp, const DataExtractor &opcodes,
932     const DWARFUnit *dwarf_cu, const lldb::RegisterKind reg_kind,
933     const Value *initial_value_ptr, const Value *object_address_ptr,
934     Value &result, Status *error_ptr) {
935 
936   if (opcodes.GetByteSize() == 0) {
937     if (error_ptr)
938       error_ptr->SetErrorString(
939           "no location, value may have been optimized out");
940     return false;
941   }
942   std::vector<Value> stack;
943 
944   Process *process = nullptr;
945   StackFrame *frame = nullptr;
946 
947   if (exe_ctx) {
948     process = exe_ctx->GetProcessPtr();
949     frame = exe_ctx->GetFramePtr();
950   }
951   if (reg_ctx == nullptr && frame)
952     reg_ctx = frame->GetRegisterContext().get();
953 
954   if (initial_value_ptr)
955     stack.push_back(*initial_value_ptr);
956 
957   lldb::offset_t offset = 0;
958   Value tmp;
959   uint32_t reg_num;
960 
961   /// Insertion point for evaluating multi-piece expression.
962   uint64_t op_piece_offset = 0;
963   Value pieces; // Used for DW_OP_piece
964 
965   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
966 
967   while (opcodes.ValidOffset(offset)) {
968     const lldb::offset_t op_offset = offset;
969     const uint8_t op = opcodes.GetU8(&offset);
970 
971     if (log && log->GetVerbose()) {
972       size_t count = stack.size();
973       LLDB_LOGF(log, "Stack before operation has %" PRIu64 " values:",
974                 (uint64_t)count);
975       for (size_t i = 0; i < count; ++i) {
976         StreamString new_value;
977         new_value.Printf("[%" PRIu64 "]", (uint64_t)i);
978         stack[i].Dump(&new_value);
979         LLDB_LOGF(log, "  %s", new_value.GetData());
980       }
981       LLDB_LOGF(log, "0x%8.8" PRIx64 ": %s", op_offset,
982                 DW_OP_value_to_name(op));
983     }
984 
985     switch (op) {
986     // The DW_OP_addr operation has a single operand that encodes a machine
987     // address and whose size is the size of an address on the target machine.
988     case DW_OP_addr:
989       stack.push_back(Scalar(opcodes.GetAddress(&offset)));
990       stack.back().SetValueType(Value::eValueTypeFileAddress);
991       // Convert the file address to a load address, so subsequent
992       // DWARF operators can operate on it.
993       if (frame)
994         stack.back().ConvertToLoadAddress(module_sp.get(),
995                                           frame->CalculateTarget().get());
996       break;
997 
998     // The DW_OP_addr_sect_offset4 is used for any location expressions in
999     // shared libraries that have a location like:
1000     //  DW_OP_addr(0x1000)
1001     // If this address resides in a shared library, then this virtual address
1002     // won't make sense when it is evaluated in the context of a running
1003     // process where shared libraries have been slid. To account for this, this
1004     // new address type where we can store the section pointer and a 4 byte
1005     // offset.
1006     //      case DW_OP_addr_sect_offset4:
1007     //          {
1008     //              result_type = eResultTypeFileAddress;
1009     //              lldb::Section *sect = (lldb::Section
1010     //              *)opcodes.GetMaxU64(&offset, sizeof(void *));
1011     //              lldb::addr_t sect_offset = opcodes.GetU32(&offset);
1012     //
1013     //              Address so_addr (sect, sect_offset);
1014     //              lldb::addr_t load_addr = so_addr.GetLoadAddress();
1015     //              if (load_addr != LLDB_INVALID_ADDRESS)
1016     //              {
1017     //                  // We successfully resolve a file address to a load
1018     //                  // address.
1019     //                  stack.push_back(load_addr);
1020     //                  break;
1021     //              }
1022     //              else
1023     //              {
1024     //                  // We were able
1025     //                  if (error_ptr)
1026     //                      error_ptr->SetErrorStringWithFormat ("Section %s in
1027     //                      %s is not currently loaded.\n",
1028     //                      sect->GetName().AsCString(),
1029     //                      sect->GetModule()->GetFileSpec().GetFilename().AsCString());
1030     //                  return false;
1031     //              }
1032     //          }
1033     //          break;
1034 
1035     // OPCODE: DW_OP_deref
1036     // OPERANDS: none
1037     // DESCRIPTION: Pops the top stack entry and treats it as an address.
1038     // The value retrieved from that address is pushed. The size of the data
1039     // retrieved from the dereferenced address is the size of an address on the
1040     // target machine.
1041     case DW_OP_deref: {
1042       if (stack.empty()) {
1043         if (error_ptr)
1044           error_ptr->SetErrorString("Expression stack empty for DW_OP_deref.");
1045         return false;
1046       }
1047       Value::ValueType value_type = stack.back().GetValueType();
1048       switch (value_type) {
1049       case Value::eValueTypeHostAddress: {
1050         void *src = (void *)stack.back().GetScalar().ULongLong();
1051         intptr_t ptr;
1052         ::memcpy(&ptr, src, sizeof(void *));
1053         stack.back().GetScalar() = ptr;
1054         stack.back().ClearContext();
1055       } break;
1056       case Value::eValueTypeFileAddress: {
1057         auto file_addr = stack.back().GetScalar().ULongLong(
1058             LLDB_INVALID_ADDRESS);
1059         if (!module_sp) {
1060           if (error_ptr)
1061             error_ptr->SetErrorStringWithFormat(
1062                 "need module to resolve file address for DW_OP_deref");
1063           return false;
1064         }
1065         Address so_addr;
1066         if (!module_sp->ResolveFileAddress(file_addr, so_addr)) {
1067           if (error_ptr)
1068             error_ptr->SetErrorStringWithFormat(
1069                 "failed to resolve file address in module");
1070           return false;
1071         }
1072         addr_t load_Addr = so_addr.GetLoadAddress(exe_ctx->GetTargetPtr());
1073         if (load_Addr == LLDB_INVALID_ADDRESS) {
1074           if (error_ptr)
1075             error_ptr->SetErrorStringWithFormat(
1076                 "failed to resolve load address");
1077           return false;
1078         }
1079         stack.back().GetScalar() = load_Addr;
1080         stack.back().SetValueType(Value::eValueTypeLoadAddress);
1081         // Fall through to load address code below...
1082       } LLVM_FALLTHROUGH;
1083       case Value::eValueTypeLoadAddress:
1084         if (exe_ctx) {
1085           if (process) {
1086             lldb::addr_t pointer_addr =
1087                 stack.back().GetScalar().ULongLong(LLDB_INVALID_ADDRESS);
1088             Status error;
1089             lldb::addr_t pointer_value =
1090                 process->ReadPointerFromMemory(pointer_addr, error);
1091             if (pointer_value != LLDB_INVALID_ADDRESS) {
1092               stack.back().GetScalar() = pointer_value;
1093               stack.back().ClearContext();
1094             } else {
1095               if (error_ptr)
1096                 error_ptr->SetErrorStringWithFormat(
1097                     "Failed to dereference pointer from 0x%" PRIx64
1098                     " for DW_OP_deref: %s\n",
1099                     pointer_addr, error.AsCString());
1100               return false;
1101             }
1102           } else {
1103             if (error_ptr)
1104               error_ptr->SetErrorStringWithFormat(
1105                   "NULL process for DW_OP_deref.\n");
1106             return false;
1107           }
1108         } else {
1109           if (error_ptr)
1110             error_ptr->SetErrorStringWithFormat(
1111                 "NULL execution context for DW_OP_deref.\n");
1112           return false;
1113         }
1114         break;
1115 
1116       default:
1117         break;
1118       }
1119 
1120     } break;
1121 
1122     // OPCODE: DW_OP_deref_size
1123     // OPERANDS: 1
1124     //  1 - uint8_t that specifies the size of the data to dereference.
1125     // DESCRIPTION: Behaves like the DW_OP_deref operation: it pops the top
1126     // stack entry and treats it as an address. The value retrieved from that
1127     // address is pushed. In the DW_OP_deref_size operation, however, the size
1128     // in bytes of the data retrieved from the dereferenced address is
1129     // specified by the single operand. This operand is a 1-byte unsigned
1130     // integral constant whose value may not be larger than the size of an
1131     // address on the target machine. The data retrieved is zero extended to
1132     // the size of an address on the target machine before being pushed on the
1133     // expression stack.
1134     case DW_OP_deref_size: {
1135       if (stack.empty()) {
1136         if (error_ptr)
1137           error_ptr->SetErrorString(
1138               "Expression stack empty for DW_OP_deref_size.");
1139         return false;
1140       }
1141       uint8_t size = opcodes.GetU8(&offset);
1142       Value::ValueType value_type = stack.back().GetValueType();
1143       switch (value_type) {
1144       case Value::eValueTypeHostAddress: {
1145         void *src = (void *)stack.back().GetScalar().ULongLong();
1146         intptr_t ptr;
1147         ::memcpy(&ptr, src, sizeof(void *));
1148         // I can't decide whether the size operand should apply to the bytes in
1149         // their
1150         // lldb-host endianness or the target endianness.. I doubt this'll ever
1151         // come up but I'll opt for assuming big endian regardless.
1152         switch (size) {
1153         case 1:
1154           ptr = ptr & 0xff;
1155           break;
1156         case 2:
1157           ptr = ptr & 0xffff;
1158           break;
1159         case 3:
1160           ptr = ptr & 0xffffff;
1161           break;
1162         case 4:
1163           ptr = ptr & 0xffffffff;
1164           break;
1165         // the casts are added to work around the case where intptr_t is a 32
1166         // bit quantity;
1167         // presumably we won't hit the 5..7 cases if (void*) is 32-bits in this
1168         // program.
1169         case 5:
1170           ptr = (intptr_t)ptr & 0xffffffffffULL;
1171           break;
1172         case 6:
1173           ptr = (intptr_t)ptr & 0xffffffffffffULL;
1174           break;
1175         case 7:
1176           ptr = (intptr_t)ptr & 0xffffffffffffffULL;
1177           break;
1178         default:
1179           break;
1180         }
1181         stack.back().GetScalar() = ptr;
1182         stack.back().ClearContext();
1183       } break;
1184       case Value::eValueTypeLoadAddress:
1185         if (exe_ctx) {
1186           if (process) {
1187             lldb::addr_t pointer_addr =
1188                 stack.back().GetScalar().ULongLong(LLDB_INVALID_ADDRESS);
1189             uint8_t addr_bytes[sizeof(lldb::addr_t)];
1190             Status error;
1191             if (process->ReadMemory(pointer_addr, &addr_bytes, size, error) ==
1192                 size) {
1193               DataExtractor addr_data(addr_bytes, sizeof(addr_bytes),
1194                                       process->GetByteOrder(), size);
1195               lldb::offset_t addr_data_offset = 0;
1196               switch (size) {
1197               case 1:
1198                 stack.back().GetScalar() = addr_data.GetU8(&addr_data_offset);
1199                 break;
1200               case 2:
1201                 stack.back().GetScalar() = addr_data.GetU16(&addr_data_offset);
1202                 break;
1203               case 4:
1204                 stack.back().GetScalar() = addr_data.GetU32(&addr_data_offset);
1205                 break;
1206               case 8:
1207                 stack.back().GetScalar() = addr_data.GetU64(&addr_data_offset);
1208                 break;
1209               default:
1210                 stack.back().GetScalar() =
1211                     addr_data.GetPointer(&addr_data_offset);
1212               }
1213               stack.back().ClearContext();
1214             } else {
1215               if (error_ptr)
1216                 error_ptr->SetErrorStringWithFormat(
1217                     "Failed to dereference pointer from 0x%" PRIx64
1218                     " for DW_OP_deref: %s\n",
1219                     pointer_addr, error.AsCString());
1220               return false;
1221             }
1222           } else {
1223             if (error_ptr)
1224               error_ptr->SetErrorStringWithFormat(
1225                   "NULL process for DW_OP_deref.\n");
1226             return false;
1227           }
1228         } else {
1229           if (error_ptr)
1230             error_ptr->SetErrorStringWithFormat(
1231                 "NULL execution context for DW_OP_deref.\n");
1232           return false;
1233         }
1234         break;
1235 
1236       default:
1237         break;
1238       }
1239 
1240     } break;
1241 
1242     // OPCODE: DW_OP_xderef_size
1243     // OPERANDS: 1
1244     //  1 - uint8_t that specifies the size of the data to dereference.
1245     // DESCRIPTION: Behaves like the DW_OP_xderef operation: the entry at
1246     // the top of the stack is treated as an address. The second stack entry is
1247     // treated as an "address space identifier" for those architectures that
1248     // support multiple address spaces. The top two stack elements are popped,
1249     // a data item is retrieved through an implementation-defined address
1250     // calculation and pushed as the new stack top. In the DW_OP_xderef_size
1251     // operation, however, the size in bytes of the data retrieved from the
1252     // dereferenced address is specified by the single operand. This operand is
1253     // a 1-byte unsigned integral constant whose value may not be larger than
1254     // the size of an address on the target machine. The data retrieved is zero
1255     // extended to the size of an address on the target machine before being
1256     // pushed on the expression stack.
1257     case DW_OP_xderef_size:
1258       if (error_ptr)
1259         error_ptr->SetErrorString("Unimplemented opcode: DW_OP_xderef_size.");
1260       return false;
1261     // OPCODE: DW_OP_xderef
1262     // OPERANDS: none
1263     // DESCRIPTION: Provides an extended dereference mechanism. The entry at
1264     // the top of the stack is treated as an address. The second stack entry is
1265     // treated as an "address space identifier" for those architectures that
1266     // support multiple address spaces. The top two stack elements are popped,
1267     // a data item is retrieved through an implementation-defined address
1268     // calculation and pushed as the new stack top. The size of the data
1269     // retrieved from the dereferenced address is the size of an address on the
1270     // target machine.
1271     case DW_OP_xderef:
1272       if (error_ptr)
1273         error_ptr->SetErrorString("Unimplemented opcode: DW_OP_xderef.");
1274       return false;
1275 
1276     // All DW_OP_constXXX opcodes have a single operand as noted below:
1277     //
1278     // Opcode           Operand 1
1279     // DW_OP_const1u    1-byte unsigned integer constant DW_OP_const1s
1280     // 1-byte signed integer constant DW_OP_const2u    2-byte unsigned integer
1281     // constant DW_OP_const2s    2-byte signed integer constant DW_OP_const4u
1282     // 4-byte unsigned integer constant DW_OP_const4s    4-byte signed integer
1283     // constant DW_OP_const8u    8-byte unsigned integer constant DW_OP_const8s
1284     // 8-byte signed integer constant DW_OP_constu     unsigned LEB128 integer
1285     // constant DW_OP_consts     signed LEB128 integer constant
1286     case DW_OP_const1u:
1287       stack.push_back(Scalar((uint8_t)opcodes.GetU8(&offset)));
1288       break;
1289     case DW_OP_const1s:
1290       stack.push_back(Scalar((int8_t)opcodes.GetU8(&offset)));
1291       break;
1292     case DW_OP_const2u:
1293       stack.push_back(Scalar((uint16_t)opcodes.GetU16(&offset)));
1294       break;
1295     case DW_OP_const2s:
1296       stack.push_back(Scalar((int16_t)opcodes.GetU16(&offset)));
1297       break;
1298     case DW_OP_const4u:
1299       stack.push_back(Scalar((uint32_t)opcodes.GetU32(&offset)));
1300       break;
1301     case DW_OP_const4s:
1302       stack.push_back(Scalar((int32_t)opcodes.GetU32(&offset)));
1303       break;
1304     case DW_OP_const8u:
1305       stack.push_back(Scalar((uint64_t)opcodes.GetU64(&offset)));
1306       break;
1307     case DW_OP_const8s:
1308       stack.push_back(Scalar((int64_t)opcodes.GetU64(&offset)));
1309       break;
1310     case DW_OP_constu:
1311       stack.push_back(Scalar(opcodes.GetULEB128(&offset)));
1312       break;
1313     case DW_OP_consts:
1314       stack.push_back(Scalar(opcodes.GetSLEB128(&offset)));
1315       break;
1316 
1317     // OPCODE: DW_OP_dup
1318     // OPERANDS: none
1319     // DESCRIPTION: duplicates the value at the top of the stack
1320     case DW_OP_dup:
1321       if (stack.empty()) {
1322         if (error_ptr)
1323           error_ptr->SetErrorString("Expression stack empty for DW_OP_dup.");
1324         return false;
1325       } else
1326         stack.push_back(stack.back());
1327       break;
1328 
1329     // OPCODE: DW_OP_drop
1330     // OPERANDS: none
1331     // DESCRIPTION: pops the value at the top of the stack
1332     case DW_OP_drop:
1333       if (stack.empty()) {
1334         if (error_ptr)
1335           error_ptr->SetErrorString("Expression stack empty for DW_OP_drop.");
1336         return false;
1337       } else
1338         stack.pop_back();
1339       break;
1340 
1341     // OPCODE: DW_OP_over
1342     // OPERANDS: none
1343     // DESCRIPTION: Duplicates the entry currently second in the stack at
1344     // the top of the stack.
1345     case DW_OP_over:
1346       if (stack.size() < 2) {
1347         if (error_ptr)
1348           error_ptr->SetErrorString(
1349               "Expression stack needs at least 2 items for DW_OP_over.");
1350         return false;
1351       } else
1352         stack.push_back(stack[stack.size() - 2]);
1353       break;
1354 
1355     // OPCODE: DW_OP_pick
1356     // OPERANDS: uint8_t index into the current stack
1357     // DESCRIPTION: The stack entry with the specified index (0 through 255,
1358     // inclusive) is pushed on the stack
1359     case DW_OP_pick: {
1360       uint8_t pick_idx = opcodes.GetU8(&offset);
1361       if (pick_idx < stack.size())
1362         stack.push_back(stack[stack.size() - 1 - pick_idx]);
1363       else {
1364         if (error_ptr)
1365           error_ptr->SetErrorStringWithFormat(
1366               "Index %u out of range for DW_OP_pick.\n", pick_idx);
1367         return false;
1368       }
1369     } break;
1370 
1371     // OPCODE: DW_OP_swap
1372     // OPERANDS: none
1373     // DESCRIPTION: swaps the top two stack entries. The entry at the top
1374     // of the stack becomes the second stack entry, and the second entry
1375     // becomes the top of the stack
1376     case DW_OP_swap:
1377       if (stack.size() < 2) {
1378         if (error_ptr)
1379           error_ptr->SetErrorString(
1380               "Expression stack needs at least 2 items for DW_OP_swap.");
1381         return false;
1382       } else {
1383         tmp = stack.back();
1384         stack.back() = stack[stack.size() - 2];
1385         stack[stack.size() - 2] = tmp;
1386       }
1387       break;
1388 
1389     // OPCODE: DW_OP_rot
1390     // OPERANDS: none
1391     // DESCRIPTION: Rotates the first three stack entries. The entry at
1392     // the top of the stack becomes the third stack entry, the second entry
1393     // becomes the top of the stack, and the third entry becomes the second
1394     // entry.
1395     case DW_OP_rot:
1396       if (stack.size() < 3) {
1397         if (error_ptr)
1398           error_ptr->SetErrorString(
1399               "Expression stack needs at least 3 items for DW_OP_rot.");
1400         return false;
1401       } else {
1402         size_t last_idx = stack.size() - 1;
1403         Value old_top = stack[last_idx];
1404         stack[last_idx] = stack[last_idx - 1];
1405         stack[last_idx - 1] = stack[last_idx - 2];
1406         stack[last_idx - 2] = old_top;
1407       }
1408       break;
1409 
1410     // OPCODE: DW_OP_abs
1411     // OPERANDS: none
1412     // DESCRIPTION: pops the top stack entry, interprets it as a signed
1413     // value and pushes its absolute value. If the absolute value can not be
1414     // represented, the result is undefined.
1415     case DW_OP_abs:
1416       if (stack.empty()) {
1417         if (error_ptr)
1418           error_ptr->SetErrorString(
1419               "Expression stack needs at least 1 item for DW_OP_abs.");
1420         return false;
1421       } else if (!stack.back().ResolveValue(exe_ctx).AbsoluteValue()) {
1422         if (error_ptr)
1423           error_ptr->SetErrorString(
1424               "Failed to take the absolute value of the first stack item.");
1425         return false;
1426       }
1427       break;
1428 
1429     // OPCODE: DW_OP_and
1430     // OPERANDS: none
1431     // DESCRIPTION: pops the top two stack values, performs a bitwise and
1432     // operation on the two, and pushes the result.
1433     case DW_OP_and:
1434       if (stack.size() < 2) {
1435         if (error_ptr)
1436           error_ptr->SetErrorString(
1437               "Expression stack needs at least 2 items for DW_OP_and.");
1438         return false;
1439       } else {
1440         tmp = stack.back();
1441         stack.pop_back();
1442         stack.back().ResolveValue(exe_ctx) =
1443             stack.back().ResolveValue(exe_ctx) & tmp.ResolveValue(exe_ctx);
1444       }
1445       break;
1446 
1447     // OPCODE: DW_OP_div
1448     // OPERANDS: none
1449     // DESCRIPTION: pops the top two stack values, divides the former second
1450     // entry by the former top of the stack using signed division, and pushes
1451     // the result.
1452     case DW_OP_div:
1453       if (stack.size() < 2) {
1454         if (error_ptr)
1455           error_ptr->SetErrorString(
1456               "Expression stack needs at least 2 items for DW_OP_div.");
1457         return false;
1458       } else {
1459         tmp = stack.back();
1460         if (tmp.ResolveValue(exe_ctx).IsZero()) {
1461           if (error_ptr)
1462             error_ptr->SetErrorString("Divide by zero.");
1463           return false;
1464         } else {
1465           stack.pop_back();
1466           stack.back() =
1467               stack.back().ResolveValue(exe_ctx) / tmp.ResolveValue(exe_ctx);
1468           if (!stack.back().ResolveValue(exe_ctx).IsValid()) {
1469             if (error_ptr)
1470               error_ptr->SetErrorString("Divide failed.");
1471             return false;
1472           }
1473         }
1474       }
1475       break;
1476 
1477     // OPCODE: DW_OP_minus
1478     // OPERANDS: none
1479     // DESCRIPTION: pops the top two stack values, subtracts the former top
1480     // of the stack from the former second entry, and pushes the result.
1481     case DW_OP_minus:
1482       if (stack.size() < 2) {
1483         if (error_ptr)
1484           error_ptr->SetErrorString(
1485               "Expression stack needs at least 2 items for DW_OP_minus.");
1486         return false;
1487       } else {
1488         tmp = stack.back();
1489         stack.pop_back();
1490         stack.back().ResolveValue(exe_ctx) =
1491             stack.back().ResolveValue(exe_ctx) - tmp.ResolveValue(exe_ctx);
1492       }
1493       break;
1494 
1495     // OPCODE: DW_OP_mod
1496     // OPERANDS: none
1497     // DESCRIPTION: pops the top two stack values and pushes the result of
1498     // the calculation: former second stack entry modulo the former top of the
1499     // stack.
1500     case DW_OP_mod:
1501       if (stack.size() < 2) {
1502         if (error_ptr)
1503           error_ptr->SetErrorString(
1504               "Expression stack needs at least 2 items for DW_OP_mod.");
1505         return false;
1506       } else {
1507         tmp = stack.back();
1508         stack.pop_back();
1509         stack.back().ResolveValue(exe_ctx) =
1510             stack.back().ResolveValue(exe_ctx) % tmp.ResolveValue(exe_ctx);
1511       }
1512       break;
1513 
1514     // OPCODE: DW_OP_mul
1515     // OPERANDS: none
1516     // DESCRIPTION: pops the top two stack entries, multiplies them
1517     // together, and pushes the result.
1518     case DW_OP_mul:
1519       if (stack.size() < 2) {
1520         if (error_ptr)
1521           error_ptr->SetErrorString(
1522               "Expression stack needs at least 2 items for DW_OP_mul.");
1523         return false;
1524       } else {
1525         tmp = stack.back();
1526         stack.pop_back();
1527         stack.back().ResolveValue(exe_ctx) =
1528             stack.back().ResolveValue(exe_ctx) * tmp.ResolveValue(exe_ctx);
1529       }
1530       break;
1531 
1532     // OPCODE: DW_OP_neg
1533     // OPERANDS: none
1534     // DESCRIPTION: pops the top stack entry, and pushes its negation.
1535     case DW_OP_neg:
1536       if (stack.empty()) {
1537         if (error_ptr)
1538           error_ptr->SetErrorString(
1539               "Expression stack needs at least 1 item for DW_OP_neg.");
1540         return false;
1541       } else {
1542         if (!stack.back().ResolveValue(exe_ctx).UnaryNegate()) {
1543           if (error_ptr)
1544             error_ptr->SetErrorString("Unary negate failed.");
1545           return false;
1546         }
1547       }
1548       break;
1549 
1550     // OPCODE: DW_OP_not
1551     // OPERANDS: none
1552     // DESCRIPTION: pops the top stack entry, and pushes its bitwise
1553     // complement
1554     case DW_OP_not:
1555       if (stack.empty()) {
1556         if (error_ptr)
1557           error_ptr->SetErrorString(
1558               "Expression stack needs at least 1 item for DW_OP_not.");
1559         return false;
1560       } else {
1561         if (!stack.back().ResolveValue(exe_ctx).OnesComplement()) {
1562           if (error_ptr)
1563             error_ptr->SetErrorString("Logical NOT failed.");
1564           return false;
1565         }
1566       }
1567       break;
1568 
1569     // OPCODE: DW_OP_or
1570     // OPERANDS: none
1571     // DESCRIPTION: pops the top two stack entries, performs a bitwise or
1572     // operation on the two, and pushes the result.
1573     case DW_OP_or:
1574       if (stack.size() < 2) {
1575         if (error_ptr)
1576           error_ptr->SetErrorString(
1577               "Expression stack needs at least 2 items for DW_OP_or.");
1578         return false;
1579       } else {
1580         tmp = stack.back();
1581         stack.pop_back();
1582         stack.back().ResolveValue(exe_ctx) =
1583             stack.back().ResolveValue(exe_ctx) | tmp.ResolveValue(exe_ctx);
1584       }
1585       break;
1586 
1587     // OPCODE: DW_OP_plus
1588     // OPERANDS: none
1589     // DESCRIPTION: pops the top two stack entries, adds them together, and
1590     // pushes the result.
1591     case DW_OP_plus:
1592       if (stack.size() < 2) {
1593         if (error_ptr)
1594           error_ptr->SetErrorString(
1595               "Expression stack needs at least 2 items for DW_OP_plus.");
1596         return false;
1597       } else {
1598         tmp = stack.back();
1599         stack.pop_back();
1600         stack.back().GetScalar() += tmp.GetScalar();
1601       }
1602       break;
1603 
1604     // OPCODE: DW_OP_plus_uconst
1605     // OPERANDS: none
1606     // DESCRIPTION: pops the top stack entry, adds it to the unsigned LEB128
1607     // constant operand and pushes the result.
1608     case DW_OP_plus_uconst:
1609       if (stack.empty()) {
1610         if (error_ptr)
1611           error_ptr->SetErrorString(
1612               "Expression stack needs at least 1 item for DW_OP_plus_uconst.");
1613         return false;
1614       } else {
1615         const uint64_t uconst_value = opcodes.GetULEB128(&offset);
1616         // Implicit conversion from a UINT to a Scalar...
1617         stack.back().GetScalar() += uconst_value;
1618         if (!stack.back().GetScalar().IsValid()) {
1619           if (error_ptr)
1620             error_ptr->SetErrorString("DW_OP_plus_uconst failed.");
1621           return false;
1622         }
1623       }
1624       break;
1625 
1626     // OPCODE: DW_OP_shl
1627     // OPERANDS: none
1628     // DESCRIPTION:  pops the top two stack entries, shifts the former
1629     // second entry left by the number of bits specified by the former top of
1630     // the stack, and pushes the result.
1631     case DW_OP_shl:
1632       if (stack.size() < 2) {
1633         if (error_ptr)
1634           error_ptr->SetErrorString(
1635               "Expression stack needs at least 2 items for DW_OP_shl.");
1636         return false;
1637       } else {
1638         tmp = stack.back();
1639         stack.pop_back();
1640         stack.back().ResolveValue(exe_ctx) <<= tmp.ResolveValue(exe_ctx);
1641       }
1642       break;
1643 
1644     // OPCODE: DW_OP_shr
1645     // OPERANDS: none
1646     // DESCRIPTION: pops the top two stack entries, shifts the former second
1647     // entry right logically (filling with zero bits) by the number of bits
1648     // specified by the former top of the stack, and pushes the result.
1649     case DW_OP_shr:
1650       if (stack.size() < 2) {
1651         if (error_ptr)
1652           error_ptr->SetErrorString(
1653               "Expression stack needs at least 2 items for DW_OP_shr.");
1654         return false;
1655       } else {
1656         tmp = stack.back();
1657         stack.pop_back();
1658         if (!stack.back().ResolveValue(exe_ctx).ShiftRightLogical(
1659                 tmp.ResolveValue(exe_ctx))) {
1660           if (error_ptr)
1661             error_ptr->SetErrorString("DW_OP_shr failed.");
1662           return false;
1663         }
1664       }
1665       break;
1666 
1667     // OPCODE: DW_OP_shra
1668     // OPERANDS: none
1669     // DESCRIPTION: pops the top two stack entries, shifts the former second
1670     // entry right arithmetically (divide the magnitude by 2, keep the same
1671     // sign for the result) by the number of bits specified by the former top
1672     // of the stack, and pushes the result.
1673     case DW_OP_shra:
1674       if (stack.size() < 2) {
1675         if (error_ptr)
1676           error_ptr->SetErrorString(
1677               "Expression stack needs at least 2 items for DW_OP_shra.");
1678         return false;
1679       } else {
1680         tmp = stack.back();
1681         stack.pop_back();
1682         stack.back().ResolveValue(exe_ctx) >>= tmp.ResolveValue(exe_ctx);
1683       }
1684       break;
1685 
1686     // OPCODE: DW_OP_xor
1687     // OPERANDS: none
1688     // DESCRIPTION: pops the top two stack entries, performs the bitwise
1689     // exclusive-or operation on the two, and pushes the result.
1690     case DW_OP_xor:
1691       if (stack.size() < 2) {
1692         if (error_ptr)
1693           error_ptr->SetErrorString(
1694               "Expression stack needs at least 2 items for DW_OP_xor.");
1695         return false;
1696       } else {
1697         tmp = stack.back();
1698         stack.pop_back();
1699         stack.back().ResolveValue(exe_ctx) =
1700             stack.back().ResolveValue(exe_ctx) ^ tmp.ResolveValue(exe_ctx);
1701       }
1702       break;
1703 
1704     // OPCODE: DW_OP_skip
1705     // OPERANDS: int16_t
1706     // DESCRIPTION:  An unconditional branch. Its single operand is a 2-byte
1707     // signed integer constant. The 2-byte constant is the number of bytes of
1708     // the DWARF expression to skip forward or backward from the current
1709     // operation, beginning after the 2-byte constant.
1710     case DW_OP_skip: {
1711       int16_t skip_offset = (int16_t)opcodes.GetU16(&offset);
1712       lldb::offset_t new_offset = offset + skip_offset;
1713       if (opcodes.ValidOffset(new_offset))
1714         offset = new_offset;
1715       else {
1716         if (error_ptr)
1717           error_ptr->SetErrorString("Invalid opcode offset in DW_OP_skip.");
1718         return false;
1719       }
1720     } break;
1721 
1722     // OPCODE: DW_OP_bra
1723     // OPERANDS: int16_t
1724     // DESCRIPTION: A conditional branch. Its single operand is a 2-byte
1725     // signed integer constant. This operation pops the top of stack. If the
1726     // value popped is not the constant 0, the 2-byte constant operand is the
1727     // number of bytes of the DWARF expression to skip forward or backward from
1728     // the current operation, beginning after the 2-byte constant.
1729     case DW_OP_bra:
1730       if (stack.empty()) {
1731         if (error_ptr)
1732           error_ptr->SetErrorString(
1733               "Expression stack needs at least 1 item for DW_OP_bra.");
1734         return false;
1735       } else {
1736         tmp = stack.back();
1737         stack.pop_back();
1738         int16_t bra_offset = (int16_t)opcodes.GetU16(&offset);
1739         Scalar zero(0);
1740         if (tmp.ResolveValue(exe_ctx) != zero) {
1741           lldb::offset_t new_offset = offset + bra_offset;
1742           if (opcodes.ValidOffset(new_offset))
1743             offset = new_offset;
1744           else {
1745             if (error_ptr)
1746               error_ptr->SetErrorString("Invalid opcode offset in DW_OP_bra.");
1747             return false;
1748           }
1749         }
1750       }
1751       break;
1752 
1753     // OPCODE: DW_OP_eq
1754     // OPERANDS: none
1755     // DESCRIPTION: pops the top two stack values, compares using the
1756     // equals (==) operator.
1757     // STACK RESULT: push the constant value 1 onto the stack if the result
1758     // of the operation is true or the constant value 0 if the result of the
1759     // operation is false.
1760     case DW_OP_eq:
1761       if (stack.size() < 2) {
1762         if (error_ptr)
1763           error_ptr->SetErrorString(
1764               "Expression stack needs at least 2 items for DW_OP_eq.");
1765         return false;
1766       } else {
1767         tmp = stack.back();
1768         stack.pop_back();
1769         stack.back().ResolveValue(exe_ctx) =
1770             stack.back().ResolveValue(exe_ctx) == tmp.ResolveValue(exe_ctx);
1771       }
1772       break;
1773 
1774     // OPCODE: DW_OP_ge
1775     // OPERANDS: none
1776     // DESCRIPTION: pops the top two stack values, compares using the
1777     // greater than or equal to (>=) operator.
1778     // STACK RESULT: push the constant value 1 onto the stack if the result
1779     // of the operation is true or the constant value 0 if the result of the
1780     // operation is false.
1781     case DW_OP_ge:
1782       if (stack.size() < 2) {
1783         if (error_ptr)
1784           error_ptr->SetErrorString(
1785               "Expression stack needs at least 2 items for DW_OP_ge.");
1786         return false;
1787       } else {
1788         tmp = stack.back();
1789         stack.pop_back();
1790         stack.back().ResolveValue(exe_ctx) =
1791             stack.back().ResolveValue(exe_ctx) >= tmp.ResolveValue(exe_ctx);
1792       }
1793       break;
1794 
1795     // OPCODE: DW_OP_gt
1796     // OPERANDS: none
1797     // DESCRIPTION: pops the top two stack values, compares using the
1798     // greater than (>) operator.
1799     // STACK RESULT: push the constant value 1 onto the stack if the result
1800     // of the operation is true or the constant value 0 if the result of the
1801     // operation is false.
1802     case DW_OP_gt:
1803       if (stack.size() < 2) {
1804         if (error_ptr)
1805           error_ptr->SetErrorString(
1806               "Expression stack needs at least 2 items for DW_OP_gt.");
1807         return false;
1808       } else {
1809         tmp = stack.back();
1810         stack.pop_back();
1811         stack.back().ResolveValue(exe_ctx) =
1812             stack.back().ResolveValue(exe_ctx) > tmp.ResolveValue(exe_ctx);
1813       }
1814       break;
1815 
1816     // OPCODE: DW_OP_le
1817     // OPERANDS: none
1818     // DESCRIPTION: pops the top two stack values, compares using the
1819     // less than or equal to (<=) operator.
1820     // STACK RESULT: push the constant value 1 onto the stack if the result
1821     // of the operation is true or the constant value 0 if the result of the
1822     // operation is false.
1823     case DW_OP_le:
1824       if (stack.size() < 2) {
1825         if (error_ptr)
1826           error_ptr->SetErrorString(
1827               "Expression stack needs at least 2 items for DW_OP_le.");
1828         return false;
1829       } else {
1830         tmp = stack.back();
1831         stack.pop_back();
1832         stack.back().ResolveValue(exe_ctx) =
1833             stack.back().ResolveValue(exe_ctx) <= tmp.ResolveValue(exe_ctx);
1834       }
1835       break;
1836 
1837     // OPCODE: DW_OP_lt
1838     // OPERANDS: none
1839     // DESCRIPTION: pops the top two stack values, compares using the
1840     // less than (<) operator.
1841     // STACK RESULT: push the constant value 1 onto the stack if the result
1842     // of the operation is true or the constant value 0 if the result of the
1843     // operation is false.
1844     case DW_OP_lt:
1845       if (stack.size() < 2) {
1846         if (error_ptr)
1847           error_ptr->SetErrorString(
1848               "Expression stack needs at least 2 items for DW_OP_lt.");
1849         return false;
1850       } else {
1851         tmp = stack.back();
1852         stack.pop_back();
1853         stack.back().ResolveValue(exe_ctx) =
1854             stack.back().ResolveValue(exe_ctx) < tmp.ResolveValue(exe_ctx);
1855       }
1856       break;
1857 
1858     // OPCODE: DW_OP_ne
1859     // OPERANDS: none
1860     // DESCRIPTION: pops the top two stack values, compares using the
1861     // not equal (!=) operator.
1862     // STACK RESULT: push the constant value 1 onto the stack if the result
1863     // of the operation is true or the constant value 0 if the result of the
1864     // operation is false.
1865     case DW_OP_ne:
1866       if (stack.size() < 2) {
1867         if (error_ptr)
1868           error_ptr->SetErrorString(
1869               "Expression stack needs at least 2 items for DW_OP_ne.");
1870         return false;
1871       } else {
1872         tmp = stack.back();
1873         stack.pop_back();
1874         stack.back().ResolveValue(exe_ctx) =
1875             stack.back().ResolveValue(exe_ctx) != tmp.ResolveValue(exe_ctx);
1876       }
1877       break;
1878 
1879     // OPCODE: DW_OP_litn
1880     // OPERANDS: none
1881     // DESCRIPTION: encode the unsigned literal values from 0 through 31.
1882     // STACK RESULT: push the unsigned literal constant value onto the top
1883     // of the stack.
1884     case DW_OP_lit0:
1885     case DW_OP_lit1:
1886     case DW_OP_lit2:
1887     case DW_OP_lit3:
1888     case DW_OP_lit4:
1889     case DW_OP_lit5:
1890     case DW_OP_lit6:
1891     case DW_OP_lit7:
1892     case DW_OP_lit8:
1893     case DW_OP_lit9:
1894     case DW_OP_lit10:
1895     case DW_OP_lit11:
1896     case DW_OP_lit12:
1897     case DW_OP_lit13:
1898     case DW_OP_lit14:
1899     case DW_OP_lit15:
1900     case DW_OP_lit16:
1901     case DW_OP_lit17:
1902     case DW_OP_lit18:
1903     case DW_OP_lit19:
1904     case DW_OP_lit20:
1905     case DW_OP_lit21:
1906     case DW_OP_lit22:
1907     case DW_OP_lit23:
1908     case DW_OP_lit24:
1909     case DW_OP_lit25:
1910     case DW_OP_lit26:
1911     case DW_OP_lit27:
1912     case DW_OP_lit28:
1913     case DW_OP_lit29:
1914     case DW_OP_lit30:
1915     case DW_OP_lit31:
1916       stack.push_back(Scalar((uint64_t)(op - DW_OP_lit0)));
1917       break;
1918 
1919     // OPCODE: DW_OP_regN
1920     // OPERANDS: none
1921     // DESCRIPTION: Push the value in register n on the top of the stack.
1922     case DW_OP_reg0:
1923     case DW_OP_reg1:
1924     case DW_OP_reg2:
1925     case DW_OP_reg3:
1926     case DW_OP_reg4:
1927     case DW_OP_reg5:
1928     case DW_OP_reg6:
1929     case DW_OP_reg7:
1930     case DW_OP_reg8:
1931     case DW_OP_reg9:
1932     case DW_OP_reg10:
1933     case DW_OP_reg11:
1934     case DW_OP_reg12:
1935     case DW_OP_reg13:
1936     case DW_OP_reg14:
1937     case DW_OP_reg15:
1938     case DW_OP_reg16:
1939     case DW_OP_reg17:
1940     case DW_OP_reg18:
1941     case DW_OP_reg19:
1942     case DW_OP_reg20:
1943     case DW_OP_reg21:
1944     case DW_OP_reg22:
1945     case DW_OP_reg23:
1946     case DW_OP_reg24:
1947     case DW_OP_reg25:
1948     case DW_OP_reg26:
1949     case DW_OP_reg27:
1950     case DW_OP_reg28:
1951     case DW_OP_reg29:
1952     case DW_OP_reg30:
1953     case DW_OP_reg31: {
1954       reg_num = op - DW_OP_reg0;
1955 
1956       if (ReadRegisterValueAsScalar(reg_ctx, reg_kind, reg_num, error_ptr, tmp))
1957         stack.push_back(tmp);
1958       else
1959         return false;
1960     } break;
1961     // OPCODE: DW_OP_regx
1962     // OPERANDS:
1963     //      ULEB128 literal operand that encodes the register.
1964     // DESCRIPTION: Push the value in register on the top of the stack.
1965     case DW_OP_regx: {
1966       reg_num = opcodes.GetULEB128(&offset);
1967       if (ReadRegisterValueAsScalar(reg_ctx, reg_kind, reg_num, error_ptr, tmp))
1968         stack.push_back(tmp);
1969       else
1970         return false;
1971     } break;
1972 
1973     // OPCODE: DW_OP_bregN
1974     // OPERANDS:
1975     //      SLEB128 offset from register N
1976     // DESCRIPTION: Value is in memory at the address specified by register
1977     // N plus an offset.
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 = op - DW_OP_breg0;
2011 
2012       if (ReadRegisterValueAsScalar(reg_ctx, reg_kind, reg_num, error_ptr,
2013                                     tmp)) {
2014         int64_t breg_offset = opcodes.GetSLEB128(&offset);
2015         tmp.ResolveValue(exe_ctx) += (uint64_t)breg_offset;
2016         tmp.ClearContext();
2017         stack.push_back(tmp);
2018         stack.back().SetValueType(Value::eValueTypeLoadAddress);
2019       } else
2020         return false;
2021     } break;
2022     // OPCODE: DW_OP_bregx
2023     // OPERANDS: 2
2024     //      ULEB128 literal operand that encodes the register.
2025     //      SLEB128 offset from register N
2026     // DESCRIPTION: Value is in memory at the address specified by register
2027     // N plus an offset.
2028     case DW_OP_bregx: {
2029       reg_num = opcodes.GetULEB128(&offset);
2030 
2031       if (ReadRegisterValueAsScalar(reg_ctx, reg_kind, reg_num, error_ptr,
2032                                     tmp)) {
2033         int64_t breg_offset = opcodes.GetSLEB128(&offset);
2034         tmp.ResolveValue(exe_ctx) += (uint64_t)breg_offset;
2035         tmp.ClearContext();
2036         stack.push_back(tmp);
2037         stack.back().SetValueType(Value::eValueTypeLoadAddress);
2038       } else
2039         return false;
2040     } break;
2041 
2042     case DW_OP_fbreg:
2043       if (exe_ctx) {
2044         if (frame) {
2045           Scalar value;
2046           if (frame->GetFrameBaseValue(value, error_ptr)) {
2047             int64_t fbreg_offset = opcodes.GetSLEB128(&offset);
2048             value += fbreg_offset;
2049             stack.push_back(value);
2050             stack.back().SetValueType(Value::eValueTypeLoadAddress);
2051           } else
2052             return false;
2053         } else {
2054           if (error_ptr)
2055             error_ptr->SetErrorString(
2056                 "Invalid stack frame in context for DW_OP_fbreg opcode.");
2057           return false;
2058         }
2059       } else {
2060         if (error_ptr)
2061           error_ptr->SetErrorStringWithFormat(
2062               "NULL execution context for DW_OP_fbreg.\n");
2063         return false;
2064       }
2065 
2066       break;
2067 
2068     // OPCODE: DW_OP_nop
2069     // OPERANDS: none
2070     // DESCRIPTION: A place holder. It has no effect on the location stack
2071     // or any of its values.
2072     case DW_OP_nop:
2073       break;
2074 
2075     // OPCODE: DW_OP_piece
2076     // OPERANDS: 1
2077     //      ULEB128: byte size of the piece
2078     // DESCRIPTION: The operand describes the size in bytes of the piece of
2079     // the object referenced by the DWARF expression whose result is at the top
2080     // of the stack. If the piece is located in a register, but does not occupy
2081     // the entire register, the placement of the piece within that register is
2082     // defined by the ABI.
2083     //
2084     // Many compilers store a single variable in sets of registers, or store a
2085     // variable partially in memory and partially in registers. DW_OP_piece
2086     // provides a way of describing how large a part of a variable a particular
2087     // DWARF expression refers to.
2088     case DW_OP_piece: {
2089       const uint64_t piece_byte_size = opcodes.GetULEB128(&offset);
2090 
2091       if (piece_byte_size > 0) {
2092         Value curr_piece;
2093 
2094         if (stack.empty()) {
2095           // In a multi-piece expression, this means that the current piece is
2096           // not available. Fill with zeros for now by resizing the data and
2097           // appending it
2098           curr_piece.ResizeData(piece_byte_size);
2099           ::memset(curr_piece.GetBuffer().GetBytes(), 0, piece_byte_size);
2100           pieces.AppendDataToHostBuffer(curr_piece);
2101         } else {
2102           Status error;
2103           // Extract the current piece into "curr_piece"
2104           Value curr_piece_source_value(stack.back());
2105           stack.pop_back();
2106 
2107           const Value::ValueType curr_piece_source_value_type =
2108               curr_piece_source_value.GetValueType();
2109           switch (curr_piece_source_value_type) {
2110           case Value::eValueTypeLoadAddress:
2111             if (process) {
2112               if (curr_piece.ResizeData(piece_byte_size) == piece_byte_size) {
2113                 lldb::addr_t load_addr =
2114                     curr_piece_source_value.GetScalar().ULongLong(
2115                         LLDB_INVALID_ADDRESS);
2116                 if (process->ReadMemory(
2117                         load_addr, curr_piece.GetBuffer().GetBytes(),
2118                         piece_byte_size, error) != piece_byte_size) {
2119                   if (error_ptr)
2120                     error_ptr->SetErrorStringWithFormat(
2121                         "failed to read memory DW_OP_piece(%" PRIu64
2122                         ") from 0x%" PRIx64,
2123                         piece_byte_size, load_addr);
2124                   return false;
2125                 }
2126               } else {
2127                 if (error_ptr)
2128                   error_ptr->SetErrorStringWithFormat(
2129                       "failed to resize the piece memory buffer for "
2130                       "DW_OP_piece(%" PRIu64 ")",
2131                       piece_byte_size);
2132                 return false;
2133               }
2134             }
2135             break;
2136 
2137           case Value::eValueTypeFileAddress:
2138           case Value::eValueTypeHostAddress:
2139             if (error_ptr) {
2140               lldb::addr_t addr = curr_piece_source_value.GetScalar().ULongLong(
2141                   LLDB_INVALID_ADDRESS);
2142               error_ptr->SetErrorStringWithFormat(
2143                   "failed to read memory DW_OP_piece(%" PRIu64
2144                   ") from %s address 0x%" PRIx64,
2145                   piece_byte_size, curr_piece_source_value.GetValueType() ==
2146                                            Value::eValueTypeFileAddress
2147                                        ? "file"
2148                                        : "host",
2149                   addr);
2150             }
2151             return false;
2152 
2153           case Value::eValueTypeScalar: {
2154             uint32_t bit_size = piece_byte_size * 8;
2155             uint32_t bit_offset = 0;
2156             if (!curr_piece_source_value.GetScalar().ExtractBitfield(
2157                     bit_size, bit_offset)) {
2158               if (error_ptr)
2159                 error_ptr->SetErrorStringWithFormat(
2160                     "unable to extract %" PRIu64 " bytes from a %" PRIu64
2161                     " byte scalar value.",
2162                     piece_byte_size,
2163                     (uint64_t)curr_piece_source_value.GetScalar()
2164                         .GetByteSize());
2165               return false;
2166             }
2167             curr_piece = curr_piece_source_value;
2168           } break;
2169 
2170           case Value::eValueTypeVector: {
2171             if (curr_piece_source_value.GetVector().length >= piece_byte_size)
2172               curr_piece_source_value.GetVector().length = piece_byte_size;
2173             else {
2174               if (error_ptr)
2175                 error_ptr->SetErrorStringWithFormat(
2176                     "unable to extract %" PRIu64 " bytes from a %" PRIu64
2177                     " byte vector value.",
2178                     piece_byte_size,
2179                     (uint64_t)curr_piece_source_value.GetVector().length);
2180               return false;
2181             }
2182           } break;
2183           }
2184 
2185           // Check if this is the first piece?
2186           if (op_piece_offset == 0) {
2187             // This is the first piece, we should push it back onto the stack
2188             // so subsequent pieces will be able to access this piece and add
2189             // to it
2190             if (pieces.AppendDataToHostBuffer(curr_piece) == 0) {
2191               if (error_ptr)
2192                 error_ptr->SetErrorString("failed to append piece data");
2193               return false;
2194             }
2195           } else {
2196             // If this is the second or later piece there should be a value on
2197             // the stack
2198             if (pieces.GetBuffer().GetByteSize() != op_piece_offset) {
2199               if (error_ptr)
2200                 error_ptr->SetErrorStringWithFormat(
2201                     "DW_OP_piece for offset %" PRIu64
2202                     " but top of stack is of size %" PRIu64,
2203                     op_piece_offset, pieces.GetBuffer().GetByteSize());
2204               return false;
2205             }
2206 
2207             if (pieces.AppendDataToHostBuffer(curr_piece) == 0) {
2208               if (error_ptr)
2209                 error_ptr->SetErrorString("failed to append piece data");
2210               return false;
2211             }
2212           }
2213           op_piece_offset += piece_byte_size;
2214         }
2215       }
2216     } break;
2217 
2218     case DW_OP_bit_piece: // 0x9d ULEB128 bit size, ULEB128 bit offset (DWARF3);
2219       if (stack.size() < 1) {
2220         if (error_ptr)
2221           error_ptr->SetErrorString(
2222               "Expression stack needs at least 1 item for DW_OP_bit_piece.");
2223         return false;
2224       } else {
2225         const uint64_t piece_bit_size = opcodes.GetULEB128(&offset);
2226         const uint64_t piece_bit_offset = opcodes.GetULEB128(&offset);
2227         switch (stack.back().GetValueType()) {
2228         case Value::eValueTypeScalar: {
2229           if (!stack.back().GetScalar().ExtractBitfield(piece_bit_size,
2230                                                         piece_bit_offset)) {
2231             if (error_ptr)
2232               error_ptr->SetErrorStringWithFormat(
2233                   "unable to extract %" PRIu64 " bit value with %" PRIu64
2234                   " bit offset from a %" PRIu64 " bit scalar value.",
2235                   piece_bit_size, piece_bit_offset,
2236                   (uint64_t)(stack.back().GetScalar().GetByteSize() * 8));
2237             return false;
2238           }
2239         } break;
2240 
2241         case Value::eValueTypeFileAddress:
2242         case Value::eValueTypeLoadAddress:
2243         case Value::eValueTypeHostAddress:
2244           if (error_ptr) {
2245             error_ptr->SetErrorStringWithFormat(
2246                 "unable to extract DW_OP_bit_piece(bit_size = %" PRIu64
2247                 ", bit_offset = %" PRIu64 ") from an address value.",
2248                 piece_bit_size, piece_bit_offset);
2249           }
2250           return false;
2251 
2252         case Value::eValueTypeVector:
2253           if (error_ptr) {
2254             error_ptr->SetErrorStringWithFormat(
2255                 "unable to extract DW_OP_bit_piece(bit_size = %" PRIu64
2256                 ", bit_offset = %" PRIu64 ") from a vector value.",
2257                 piece_bit_size, piece_bit_offset);
2258           }
2259           return false;
2260         }
2261       }
2262       break;
2263 
2264     // OPCODE: DW_OP_push_object_address
2265     // OPERANDS: none
2266     // DESCRIPTION: Pushes the address of the object currently being
2267     // evaluated as part of evaluation of a user presented expression. This
2268     // object may correspond to an independent variable described by its own
2269     // DIE or it may be a component of an array, structure, or class whose
2270     // address has been dynamically determined by an earlier step during user
2271     // expression evaluation.
2272     case DW_OP_push_object_address:
2273       if (object_address_ptr)
2274         stack.push_back(*object_address_ptr);
2275       else {
2276         if (error_ptr)
2277           error_ptr->SetErrorString("DW_OP_push_object_address used without "
2278                                     "specifying an object address");
2279         return false;
2280       }
2281       break;
2282 
2283     // OPCODE: DW_OP_call2
2284     // OPERANDS:
2285     //      uint16_t compile unit relative offset of a DIE
2286     // DESCRIPTION: Performs subroutine calls during evaluation
2287     // of a DWARF expression. The operand is the 2-byte unsigned offset of a
2288     // debugging information entry in the current compilation unit.
2289     //
2290     // Operand interpretation is exactly like that for DW_FORM_ref2.
2291     //
2292     // This operation transfers control of DWARF expression evaluation to the
2293     // DW_AT_location attribute of the referenced DIE. If there is no such
2294     // attribute, then there is no effect. Execution of the DWARF expression of
2295     // a DW_AT_location attribute may add to and/or remove from values on the
2296     // stack. Execution returns to the point following the call when the end of
2297     // the attribute is reached. Values on the stack at the time of the call
2298     // may be used as parameters by the called expression and values left on
2299     // the stack by the called expression may be used as return values by prior
2300     // agreement between the calling and called expressions.
2301     case DW_OP_call2:
2302       if (error_ptr)
2303         error_ptr->SetErrorString("Unimplemented opcode DW_OP_call2.");
2304       return false;
2305     // OPCODE: DW_OP_call4
2306     // OPERANDS: 1
2307     //      uint32_t compile unit relative offset of a DIE
2308     // DESCRIPTION: Performs a subroutine call during evaluation of a DWARF
2309     // expression. For DW_OP_call4, the operand is a 4-byte unsigned offset of
2310     // a debugging information entry in  the current compilation unit.
2311     //
2312     // Operand interpretation DW_OP_call4 is exactly like that for
2313     // DW_FORM_ref4.
2314     //
2315     // This operation transfers control of DWARF expression evaluation to the
2316     // DW_AT_location attribute of the referenced DIE. If there is no such
2317     // attribute, then there is no effect. Execution of the DWARF expression of
2318     // a DW_AT_location attribute may add to and/or remove from values on the
2319     // stack. Execution returns to the point following the call when the end of
2320     // the attribute is reached. Values on the stack at the time of the call
2321     // may be used as parameters by the called expression and values left on
2322     // the stack by the called expression may be used as return values by prior
2323     // agreement between the calling and called expressions.
2324     case DW_OP_call4:
2325       if (error_ptr)
2326         error_ptr->SetErrorString("Unimplemented opcode DW_OP_call4.");
2327       return false;
2328 
2329     // OPCODE: DW_OP_stack_value
2330     // OPERANDS: None
2331     // DESCRIPTION: Specifies that the object does not exist in memory but
2332     // rather is a constant value.  The value from the top of the stack is the
2333     // value to be used.  This is the actual object value and not the location.
2334     case DW_OP_stack_value:
2335       stack.back().SetValueType(Value::eValueTypeScalar);
2336       break;
2337 
2338     // OPCODE: DW_OP_convert
2339     // OPERANDS: 1
2340     //      A ULEB128 that is either a DIE offset of a
2341     //      DW_TAG_base_type or 0 for the generic (pointer-sized) type.
2342     //
2343     // DESCRIPTION: Pop the top stack element, convert it to a
2344     // different type, and push the result.
2345     case DW_OP_convert: {
2346       if (stack.size() < 1) {
2347         if (error_ptr)
2348           error_ptr->SetErrorString(
2349               "Expression stack needs at least 1 item for DW_OP_convert.");
2350         return false;
2351       }
2352       const uint64_t die_offset = opcodes.GetULEB128(&offset);
2353       Scalar::Type type = Scalar::e_void;
2354       uint64_t bit_size;
2355       if (die_offset == 0) {
2356         // The generic type has the size of an address on the target
2357         // machine and an unspecified signedness. Scalar has no
2358         // "unspecified signedness", so we use unsigned types.
2359         if (!module_sp) {
2360           if (error_ptr)
2361             error_ptr->SetErrorString("No module");
2362           return false;
2363         }
2364         bit_size = module_sp->GetArchitecture().GetAddressByteSize() * 8;
2365         if (!bit_size) {
2366           if (error_ptr)
2367             error_ptr->SetErrorString("unspecified architecture");
2368           return false;
2369         }
2370         type = Scalar::GetBestTypeForBitSize(bit_size, false);
2371       } else {
2372         // Retrieve the type DIE that the value is being converted to.
2373         // FIXME: the constness has annoying ripple effects.
2374         DWARFDIE die = const_cast<DWARFUnit *>(dwarf_cu)->GetDIE(die_offset);
2375         if (!die) {
2376           if (error_ptr)
2377             error_ptr->SetErrorString("Cannot resolve DW_OP_convert type DIE");
2378           return false;
2379         }
2380         uint64_t encoding =
2381             die.GetAttributeValueAsUnsigned(DW_AT_encoding, DW_ATE_hi_user);
2382         bit_size = die.GetAttributeValueAsUnsigned(DW_AT_byte_size, 0) * 8;
2383         if (!bit_size)
2384           bit_size = die.GetAttributeValueAsUnsigned(DW_AT_bit_size, 0);
2385         if (!bit_size) {
2386           if (error_ptr)
2387             error_ptr->SetErrorString("Unsupported type size in DW_OP_convert");
2388           return false;
2389         }
2390         switch (encoding) {
2391         case DW_ATE_signed:
2392         case DW_ATE_signed_char:
2393           type = Scalar::GetBestTypeForBitSize(bit_size, true);
2394           break;
2395         case DW_ATE_unsigned:
2396         case DW_ATE_unsigned_char:
2397           type = Scalar::GetBestTypeForBitSize(bit_size, false);
2398           break;
2399         default:
2400           if (error_ptr)
2401             error_ptr->SetErrorString("Unsupported encoding in DW_OP_convert");
2402           return false;
2403         }
2404       }
2405       if (type == Scalar::e_void) {
2406         if (error_ptr)
2407           error_ptr->SetErrorString("Unsupported pointer size");
2408         return false;
2409       }
2410       Scalar &top = stack.back().ResolveValue(exe_ctx);
2411       top.TruncOrExtendTo(type, bit_size);
2412       break;
2413     }
2414 
2415     // OPCODE: DW_OP_call_frame_cfa
2416     // OPERANDS: None
2417     // DESCRIPTION: Specifies a DWARF expression that pushes the value of
2418     // the canonical frame address consistent with the call frame information
2419     // located in .debug_frame (or in the FDEs of the eh_frame section).
2420     case DW_OP_call_frame_cfa:
2421       if (frame) {
2422         // Note that we don't have to parse FDEs because this DWARF expression
2423         // is commonly evaluated with a valid stack frame.
2424         StackID id = frame->GetStackID();
2425         addr_t cfa = id.GetCallFrameAddress();
2426         if (cfa != LLDB_INVALID_ADDRESS) {
2427           stack.push_back(Scalar(cfa));
2428           stack.back().SetValueType(Value::eValueTypeLoadAddress);
2429         } else if (error_ptr)
2430           error_ptr->SetErrorString("Stack frame does not include a canonical "
2431                                     "frame address for DW_OP_call_frame_cfa "
2432                                     "opcode.");
2433       } else {
2434         if (error_ptr)
2435           error_ptr->SetErrorString("Invalid stack frame in context for "
2436                                     "DW_OP_call_frame_cfa opcode.");
2437         return false;
2438       }
2439       break;
2440 
2441     // OPCODE: DW_OP_form_tls_address (or the old pre-DWARFv3 vendor extension
2442     // opcode, DW_OP_GNU_push_tls_address)
2443     // OPERANDS: none
2444     // DESCRIPTION: Pops a TLS offset from the stack, converts it to
2445     // an address in the current thread's thread-local storage block, and
2446     // pushes it on the stack.
2447     case DW_OP_form_tls_address:
2448     case DW_OP_GNU_push_tls_address: {
2449       if (stack.size() < 1) {
2450         if (error_ptr) {
2451           if (op == DW_OP_form_tls_address)
2452             error_ptr->SetErrorString(
2453                 "DW_OP_form_tls_address needs an argument.");
2454           else
2455             error_ptr->SetErrorString(
2456                 "DW_OP_GNU_push_tls_address needs an argument.");
2457         }
2458         return false;
2459       }
2460 
2461       if (!exe_ctx || !module_sp) {
2462         if (error_ptr)
2463           error_ptr->SetErrorString("No context to evaluate TLS within.");
2464         return false;
2465       }
2466 
2467       Thread *thread = exe_ctx->GetThreadPtr();
2468       if (!thread) {
2469         if (error_ptr)
2470           error_ptr->SetErrorString("No thread to evaluate TLS within.");
2471         return false;
2472       }
2473 
2474       // Lookup the TLS block address for this thread and module.
2475       const addr_t tls_file_addr =
2476           stack.back().GetScalar().ULongLong(LLDB_INVALID_ADDRESS);
2477       const addr_t tls_load_addr =
2478           thread->GetThreadLocalData(module_sp, tls_file_addr);
2479 
2480       if (tls_load_addr == LLDB_INVALID_ADDRESS) {
2481         if (error_ptr)
2482           error_ptr->SetErrorString(
2483               "No TLS data currently exists for this thread.");
2484         return false;
2485       }
2486 
2487       stack.back().GetScalar() = tls_load_addr;
2488       stack.back().SetValueType(Value::eValueTypeLoadAddress);
2489     } break;
2490 
2491     // OPCODE: DW_OP_addrx (DW_OP_GNU_addr_index is the legacy name.)
2492     // OPERANDS: 1
2493     //      ULEB128: index to the .debug_addr section
2494     // DESCRIPTION: Pushes an address to the stack from the .debug_addr
2495     // section with the base address specified by the DW_AT_addr_base attribute
2496     // and the 0 based index is the ULEB128 encoded index.
2497     case DW_OP_addrx:
2498     case DW_OP_GNU_addr_index: {
2499       if (!dwarf_cu) {
2500         if (error_ptr)
2501           error_ptr->SetErrorString("DW_OP_GNU_addr_index found without a "
2502                                     "compile unit being specified");
2503         return false;
2504       }
2505       uint64_t index = opcodes.GetULEB128(&offset);
2506       lldb::addr_t value = ReadAddressFromDebugAddrSection(dwarf_cu, index);
2507       stack.push_back(Scalar(value));
2508       stack.back().SetValueType(Value::eValueTypeFileAddress);
2509     } break;
2510 
2511     // OPCODE: DW_OP_GNU_const_index
2512     // OPERANDS: 1
2513     //      ULEB128: index to the .debug_addr section
2514     // DESCRIPTION: Pushes an constant with the size of a machine address to
2515     // the stack from the .debug_addr section with the base address specified
2516     // by the DW_AT_addr_base attribute and the 0 based index is the ULEB128
2517     // encoded index.
2518     case DW_OP_GNU_const_index: {
2519       if (!dwarf_cu) {
2520         if (error_ptr)
2521           error_ptr->SetErrorString("DW_OP_GNU_const_index found without a "
2522                                     "compile unit being specified");
2523         return false;
2524       }
2525       uint64_t index = opcodes.GetULEB128(&offset);
2526       lldb::addr_t value = ReadAddressFromDebugAddrSection(dwarf_cu, index);
2527       stack.push_back(Scalar(value));
2528     } break;
2529 
2530     case DW_OP_entry_value: {
2531       if (!Evaluate_DW_OP_entry_value(stack, exe_ctx, reg_ctx, opcodes, offset,
2532                                       error_ptr, log)) {
2533         LLDB_ERRORF(error_ptr, "Could not evaluate %s.",
2534                     DW_OP_value_to_name(op));
2535         return false;
2536       }
2537       break;
2538     }
2539 
2540     default:
2541       LLDB_LOGF(log, "Unhandled opcode %s in DWARFExpression.",
2542                 DW_OP_value_to_name(op));
2543       break;
2544     }
2545   }
2546 
2547   if (stack.empty()) {
2548     // Nothing on the stack, check if we created a piece value from DW_OP_piece
2549     // or DW_OP_bit_piece opcodes
2550     if (pieces.GetBuffer().GetByteSize()) {
2551       result = pieces;
2552     } else {
2553       if (error_ptr)
2554         error_ptr->SetErrorString("Stack empty after evaluation.");
2555       return false;
2556     }
2557   } else {
2558     if (log && log->GetVerbose()) {
2559       size_t count = stack.size();
2560       LLDB_LOGF(log, "Stack after operation has %" PRIu64 " values:",
2561                 (uint64_t)count);
2562       for (size_t i = 0; i < count; ++i) {
2563         StreamString new_value;
2564         new_value.Printf("[%" PRIu64 "]", (uint64_t)i);
2565         stack[i].Dump(&new_value);
2566         LLDB_LOGF(log, "  %s", new_value.GetData());
2567       }
2568     }
2569     result = stack.back();
2570   }
2571   return true; // Return true on success
2572 }
2573 
2574 static bool print_dwarf_exp_op(Stream &s, const DataExtractor &data,
2575                                lldb::offset_t *offset_ptr, int address_size,
2576                                int dwarf_ref_size) {
2577   uint8_t opcode = data.GetU8(offset_ptr);
2578   DRC_class opcode_class;
2579   uint64_t uint;
2580   int64_t sint;
2581 
2582   int size;
2583 
2584   opcode_class = DW_OP_value_to_class(opcode) & (~DRC_DWARFv3);
2585 
2586   s.Printf("%s ", DW_OP_value_to_name(opcode));
2587 
2588   /* Does this take zero parameters?  If so we can shortcut this function.  */
2589   if (opcode_class == DRC_ZEROOPERANDS)
2590     return true;
2591 
2592   if (opcode_class == DRC_TWOOPERANDS && opcode == DW_OP_bregx) {
2593     uint = data.GetULEB128(offset_ptr);
2594     sint = data.GetSLEB128(offset_ptr);
2595     s.Printf("%" PRIu64 " %" PRIi64, uint, sint);
2596     return true;
2597   }
2598   if (opcode_class == DRC_TWOOPERANDS && opcode == DW_OP_entry_value) {
2599     uint = data.GetULEB128(offset_ptr);
2600     s.Printf("%" PRIu64 " ", uint);
2601     return true;
2602   }
2603   if (opcode_class != DRC_ONEOPERAND) {
2604     s.Printf("UNKNOWN OP %u", opcode);
2605     return false;
2606   }
2607 
2608   switch (opcode) {
2609   case DW_OP_addr:
2610     size = address_size;
2611     break;
2612   case DW_OP_const1u:
2613     size = 1;
2614     break;
2615   case DW_OP_const1s:
2616     size = -1;
2617     break;
2618   case DW_OP_const2u:
2619     size = 2;
2620     break;
2621   case DW_OP_const2s:
2622     size = -2;
2623     break;
2624   case DW_OP_const4u:
2625     size = 4;
2626     break;
2627   case DW_OP_const4s:
2628     size = -4;
2629     break;
2630   case DW_OP_const8u:
2631     size = 8;
2632     break;
2633   case DW_OP_const8s:
2634     size = -8;
2635     break;
2636   case DW_OP_constu:
2637     size = 128;
2638     break;
2639   case DW_OP_consts:
2640     size = -128;
2641     break;
2642   case DW_OP_fbreg:
2643     size = -128;
2644     break;
2645   case DW_OP_breg0:
2646   case DW_OP_breg1:
2647   case DW_OP_breg2:
2648   case DW_OP_breg3:
2649   case DW_OP_breg4:
2650   case DW_OP_breg5:
2651   case DW_OP_breg6:
2652   case DW_OP_breg7:
2653   case DW_OP_breg8:
2654   case DW_OP_breg9:
2655   case DW_OP_breg10:
2656   case DW_OP_breg11:
2657   case DW_OP_breg12:
2658   case DW_OP_breg13:
2659   case DW_OP_breg14:
2660   case DW_OP_breg15:
2661   case DW_OP_breg16:
2662   case DW_OP_breg17:
2663   case DW_OP_breg18:
2664   case DW_OP_breg19:
2665   case DW_OP_breg20:
2666   case DW_OP_breg21:
2667   case DW_OP_breg22:
2668   case DW_OP_breg23:
2669   case DW_OP_breg24:
2670   case DW_OP_breg25:
2671   case DW_OP_breg26:
2672   case DW_OP_breg27:
2673   case DW_OP_breg28:
2674   case DW_OP_breg29:
2675   case DW_OP_breg30:
2676   case DW_OP_breg31:
2677     size = -128;
2678     break;
2679   case DW_OP_pick:
2680   case DW_OP_deref_size:
2681   case DW_OP_xderef_size:
2682     size = 1;
2683     break;
2684   case DW_OP_skip:
2685   case DW_OP_bra:
2686     size = -2;
2687     break;
2688   case DW_OP_call2:
2689     size = 2;
2690     break;
2691   case DW_OP_call4:
2692     size = 4;
2693     break;
2694   case DW_OP_call_ref:
2695     size = dwarf_ref_size;
2696     break;
2697   case DW_OP_addrx:
2698   case DW_OP_piece:
2699   case DW_OP_plus_uconst:
2700   case DW_OP_regx:
2701   case DW_OP_GNU_addr_index:
2702   case DW_OP_GNU_const_index:
2703   case DW_OP_entry_value:
2704     size = 128;
2705     break;
2706   default:
2707     s.Printf("UNKNOWN ONE-OPERAND OPCODE, #%u", opcode);
2708     return false;
2709   }
2710 
2711   switch (size) {
2712   case -1:
2713     sint = (int8_t)data.GetU8(offset_ptr);
2714     s.Printf("%+" PRIi64, sint);
2715     break;
2716   case -2:
2717     sint = (int16_t)data.GetU16(offset_ptr);
2718     s.Printf("%+" PRIi64, sint);
2719     break;
2720   case -4:
2721     sint = (int32_t)data.GetU32(offset_ptr);
2722     s.Printf("%+" PRIi64, sint);
2723     break;
2724   case -8:
2725     sint = (int64_t)data.GetU64(offset_ptr);
2726     s.Printf("%+" PRIi64, sint);
2727     break;
2728   case -128:
2729     sint = data.GetSLEB128(offset_ptr);
2730     s.Printf("%+" PRIi64, sint);
2731     break;
2732   case 1:
2733     uint = data.GetU8(offset_ptr);
2734     s.Printf("0x%2.2" PRIx64, uint);
2735     break;
2736   case 2:
2737     uint = data.GetU16(offset_ptr);
2738     s.Printf("0x%4.4" PRIx64, uint);
2739     break;
2740   case 4:
2741     uint = data.GetU32(offset_ptr);
2742     s.Printf("0x%8.8" PRIx64, uint);
2743     break;
2744   case 8:
2745     uint = data.GetU64(offset_ptr);
2746     s.Printf("0x%16.16" PRIx64, uint);
2747     break;
2748   case 128:
2749     uint = data.GetULEB128(offset_ptr);
2750     s.Printf("0x%" PRIx64, uint);
2751     break;
2752   }
2753 
2754   return true;
2755 }
2756 
2757 bool DWARFExpression::PrintDWARFExpression(Stream &s, const DataExtractor &data,
2758                                            int address_size, int dwarf_ref_size,
2759                                            bool location_expression) {
2760   int op_count = 0;
2761   lldb::offset_t offset = 0;
2762   while (data.ValidOffset(offset)) {
2763     if (location_expression && op_count > 0)
2764       return false;
2765     if (op_count > 0)
2766       s.PutCString(", ");
2767     if (!print_dwarf_exp_op(s, data, &offset, address_size, dwarf_ref_size))
2768       return false;
2769     op_count++;
2770   }
2771 
2772   return true;
2773 }
2774 
2775 void DWARFExpression::PrintDWARFLocationList(
2776     Stream &s, const DWARFUnit *cu, const DataExtractor &debug_loc_data,
2777     lldb::offset_t offset) {
2778   uint64_t start_addr, end_addr;
2779   uint32_t addr_size = DWARFUnit::GetAddressByteSize(cu);
2780   s.SetAddressByteSize(DWARFUnit::GetAddressByteSize(cu));
2781   dw_addr_t base_addr = cu ? cu->GetBaseAddress() : 0;
2782   while (debug_loc_data.ValidOffset(offset)) {
2783     start_addr = debug_loc_data.GetMaxU64(&offset, addr_size);
2784     end_addr = debug_loc_data.GetMaxU64(&offset, addr_size);
2785 
2786     if (start_addr == 0 && end_addr == 0)
2787       break;
2788 
2789     s.PutCString("\n            ");
2790     s.Indent();
2791     if (cu)
2792       DumpAddressRange(s.AsRawOstream(), start_addr + base_addr,
2793                        end_addr + base_addr, cu->GetAddressByteSize(), nullptr,
2794                        ": ");
2795     uint32_t loc_length = debug_loc_data.GetU16(&offset);
2796 
2797     DataExtractor locationData(debug_loc_data, offset, loc_length);
2798     PrintDWARFExpression(s, locationData, addr_size, 4, false);
2799     offset += loc_length;
2800   }
2801 }
2802 
2803 static DataExtractor ToDataExtractor(const llvm::DWARFLocationExpression &loc,
2804                                      ByteOrder byte_order, uint32_t addr_size) {
2805   auto buffer_sp =
2806       std::make_shared<DataBufferHeap>(loc.Expr.data(), loc.Expr.size());
2807   return DataExtractor(buffer_sp, byte_order, addr_size);
2808 }
2809 
2810 llvm::Optional<DataExtractor>
2811 DWARFExpression::GetLocationExpression(addr_t load_function_start,
2812                                        addr_t addr) const {
2813   Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS);
2814 
2815   std::unique_ptr<llvm::DWARFLocationTable> loctable_up = GetLocationTable(
2816       m_dwarf_cu->GetSymbolFileDWARF().GetLocationListFormat(), m_data);
2817   if (!loctable_up)
2818     return llvm::None;
2819   llvm::Optional<DataExtractor> result;
2820   uint64_t offset = 0;
2821   auto lookup_addr =
2822       [&](uint32_t index) -> llvm::Optional<llvm::object::SectionedAddress> {
2823     addr_t address = ReadAddressFromDebugAddrSection(m_dwarf_cu, index);
2824     if (address == LLDB_INVALID_ADDRESS)
2825       return llvm::None;
2826     return llvm::object::SectionedAddress{address};
2827   };
2828   auto process_list = [&](llvm::Expected<llvm::DWARFLocationExpression> loc) {
2829     if (!loc) {
2830       LLDB_LOG_ERROR(log, loc.takeError(), "{0}");
2831       return true;
2832     }
2833     if (loc->Range) {
2834       // This relocates low_pc and high_pc by adding the difference between the
2835       // function file address, and the actual address it is loaded in memory.
2836       addr_t slide = load_function_start - m_loclist_addresses->func_file_addr;
2837       loc->Range->LowPC += slide;
2838       loc->Range->HighPC += slide;
2839 
2840       if (loc->Range->LowPC <= addr && addr < loc->Range->HighPC)
2841         result = ToDataExtractor(*loc, m_data.GetByteOrder(),
2842                                  m_data.GetAddressByteSize());
2843     }
2844     return !result;
2845   };
2846   llvm::Error E = loctable_up->visitAbsoluteLocationList(
2847       offset, llvm::object::SectionedAddress{m_loclist_addresses->cu_file_addr},
2848       lookup_addr, process_list);
2849   if (E)
2850     LLDB_LOG_ERROR(log, std::move(E), "{0}");
2851   return result;
2852 }
2853 
2854 bool DWARFExpression::MatchesOperand(StackFrame &frame,
2855                                      const Instruction::Operand &operand) {
2856   using namespace OperandMatchers;
2857 
2858   RegisterContextSP reg_ctx_sp = frame.GetRegisterContext();
2859   if (!reg_ctx_sp) {
2860     return false;
2861   }
2862 
2863   DataExtractor opcodes;
2864   if (IsLocationList()) {
2865     SymbolContext sc = frame.GetSymbolContext(eSymbolContextFunction);
2866     if (!sc.function)
2867       return false;
2868 
2869     addr_t load_function_start =
2870         sc.function->GetAddressRange().GetBaseAddress().GetFileAddress();
2871     if (load_function_start == LLDB_INVALID_ADDRESS)
2872       return false;
2873 
2874     addr_t pc = frame.GetFrameCodeAddress().GetLoadAddress(
2875         frame.CalculateTarget().get());
2876 
2877     if (llvm::Optional<DataExtractor> expr = GetLocationExpression(load_function_start, pc))
2878       opcodes = std::move(*expr);
2879     else
2880       return false;
2881   } else
2882     opcodes = m_data;
2883 
2884 
2885   lldb::offset_t op_offset = 0;
2886   uint8_t opcode = opcodes.GetU8(&op_offset);
2887 
2888   if (opcode == DW_OP_fbreg) {
2889     int64_t offset = opcodes.GetSLEB128(&op_offset);
2890 
2891     DWARFExpression *fb_expr = frame.GetFrameBaseExpression(nullptr);
2892     if (!fb_expr) {
2893       return false;
2894     }
2895 
2896     auto recurse = [&frame, fb_expr](const Instruction::Operand &child) {
2897       return fb_expr->MatchesOperand(frame, child);
2898     };
2899 
2900     if (!offset &&
2901         MatchUnaryOp(MatchOpType(Instruction::Operand::Type::Dereference),
2902                      recurse)(operand)) {
2903       return true;
2904     }
2905 
2906     return MatchUnaryOp(
2907         MatchOpType(Instruction::Operand::Type::Dereference),
2908         MatchBinaryOp(MatchOpType(Instruction::Operand::Type::Sum),
2909                       MatchImmOp(offset), recurse))(operand);
2910   }
2911 
2912   bool dereference = false;
2913   const RegisterInfo *reg = nullptr;
2914   int64_t offset = 0;
2915 
2916   if (opcode >= DW_OP_reg0 && opcode <= DW_OP_reg31) {
2917     reg = reg_ctx_sp->GetRegisterInfo(m_reg_kind, opcode - DW_OP_reg0);
2918   } else if (opcode >= DW_OP_breg0 && opcode <= DW_OP_breg31) {
2919     offset = opcodes.GetSLEB128(&op_offset);
2920     reg = reg_ctx_sp->GetRegisterInfo(m_reg_kind, opcode - DW_OP_breg0);
2921   } else if (opcode == DW_OP_regx) {
2922     uint32_t reg_num = static_cast<uint32_t>(opcodes.GetULEB128(&op_offset));
2923     reg = reg_ctx_sp->GetRegisterInfo(m_reg_kind, reg_num);
2924   } else if (opcode == DW_OP_bregx) {
2925     uint32_t reg_num = static_cast<uint32_t>(opcodes.GetULEB128(&op_offset));
2926     offset = opcodes.GetSLEB128(&op_offset);
2927     reg = reg_ctx_sp->GetRegisterInfo(m_reg_kind, reg_num);
2928   } else {
2929     return false;
2930   }
2931 
2932   if (!reg) {
2933     return false;
2934   }
2935 
2936   if (dereference) {
2937     if (!offset &&
2938         MatchUnaryOp(MatchOpType(Instruction::Operand::Type::Dereference),
2939                      MatchRegOp(*reg))(operand)) {
2940       return true;
2941     }
2942 
2943     return MatchUnaryOp(
2944         MatchOpType(Instruction::Operand::Type::Dereference),
2945         MatchBinaryOp(MatchOpType(Instruction::Operand::Type::Sum),
2946                       MatchRegOp(*reg),
2947                       MatchImmOp(offset)))(operand);
2948   } else {
2949     return MatchRegOp(*reg)(operand);
2950   }
2951 }
2952 
2953