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