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