1 //===-- DWARFExpressionTest.cpp ----------------------------------*- C++-*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "lldb/Expression/DWARFExpression.h"
10 #include "../../source/Plugins/SymbolFile/DWARF/DWARFUnit.h"
11 #include "../../source/Plugins/SymbolFile/DWARF/SymbolFileDWARF.h"
12 #include "TestingSupport/SubsystemRAII.h"
13 #include "lldb/Core/Module.h"
14 #include "lldb/Core/Section.h"
15 #include "lldb/Core/Value.h"
16 #include "lldb/Core/dwarf.h"
17 #include "lldb/Symbol/ObjectFile.h"
18 #include "lldb/Utility/StreamString.h"
19 #include "llvm/ADT/StringExtras.h"
20 #include "llvm/ObjectYAML/DWARFEmitter.h"
21 #include "llvm/Testing/Support/Error.h"
22 #include "gtest/gtest.h"
23 
24 using namespace lldb_private;
25 
26 static llvm::Expected<Scalar> Evaluate(llvm::ArrayRef<uint8_t> expr,
27                                        lldb::ModuleSP module_sp = {},
28                                        DWARFUnit *unit = nullptr) {
29   DataExtractor extractor(expr.data(), expr.size(), lldb::eByteOrderLittle,
30                           /*addr_size*/ 4);
31   Value result;
32   Status status;
33   if (!DWARFExpression::Evaluate(
34           /*exe_ctx*/ nullptr, /*reg_ctx*/ nullptr, module_sp, extractor, unit,
35           lldb::eRegisterKindLLDB,
36           /*initial_value_ptr*/ nullptr,
37           /*object_address_ptr*/ nullptr, result, &status))
38     return status.ToError();
39 
40   return result.GetScalar();
41 }
42 
43 /// A mock module holding an object file parsed from YAML.
44 class YAMLModule : public lldb_private::Module {
45 public:
46   YAMLModule(ArchSpec &arch) : Module(FileSpec("test"), arch) {}
47   void SetObjectFile(lldb::ObjectFileSP obj_file) { m_objfile_sp = obj_file; }
48   ObjectFile *GetObjectFile() override { return m_objfile_sp.get(); }
49 };
50 
51 /// A mock object file that can be parsed from YAML.
52 class YAMLObjectFile : public lldb_private::ObjectFile {
53   const lldb::ModuleSP m_module_sp;
54   llvm::StringMap<std::unique_ptr<llvm::MemoryBuffer>> &m_section_map;
55   /// Because there is only one DataExtractor in the ObjectFile
56   /// interface, all sections are copied into a contiguous buffer.
57   std::vector<char> m_buffer;
58 
59 public:
60   YAMLObjectFile(const lldb::ModuleSP &module_sp,
61                  llvm::StringMap<std::unique_ptr<llvm::MemoryBuffer>> &map)
62       : ObjectFile(module_sp, &module_sp->GetFileSpec(), /*file_offset*/ 0,
63                    /*length*/ 0, /*data_sp*/ nullptr, /*data_offset*/ 0),
64         m_module_sp(module_sp), m_section_map(map) {}
65 
66   /// Callback for initializing the module's list of sections.
67   void CreateSections(SectionList &unified_section_list) override {
68     lldb::offset_t total_bytes = 0;
69     for (auto &entry : m_section_map)
70       total_bytes += entry.getValue()->getBufferSize();
71     m_buffer.reserve(total_bytes);
72     m_data =
73         DataExtractor(m_buffer.data(), total_bytes, lldb::eByteOrderLittle, 4);
74 
75     lldb::user_id_t sect_id = 1;
76     for (auto &entry : m_section_map) {
77       llvm::StringRef name = entry.getKey();
78       lldb::SectionType sect_type =
79           llvm::StringSwitch<lldb::SectionType>(name)
80               .Case("debug_info", lldb::eSectionTypeDWARFDebugInfo)
81               .Case("debug_abbrev", lldb::eSectionTypeDWARFDebugAbbrev);
82       auto &membuf = entry.getValue();
83       lldb::addr_t file_vm_addr = 0;
84       lldb::addr_t vm_size = 0;
85       lldb::offset_t file_offset = m_buffer.size();
86       lldb::offset_t file_size = membuf->getBufferSize();
87       m_buffer.resize(file_offset + file_size);
88       memcpy(m_buffer.data() + file_offset, membuf->getBufferStart(),
89              file_size);
90       uint32_t log2align = 0;
91       uint32_t flags = 0;
92       auto section_sp = std::make_shared<lldb_private::Section>(
93           m_module_sp, this, sect_id++, ConstString(name), sect_type,
94           file_vm_addr, vm_size, file_offset, file_size, log2align, flags);
95       unified_section_list.AddSection(section_sp);
96     }
97   }
98 
99   /// \{
100   /// Stub methods that aren't needed here.
101   ConstString GetPluginName() override { return ConstString("YAMLObjectFile"); }
102   uint32_t GetPluginVersion() override { return 0; }
103   void Dump(Stream *s) override {}
104   uint32_t GetAddressByteSize() const override { return 8; }
105   uint32_t GetDependentModules(FileSpecList &file_list) override { return 0; }
106   bool IsExecutable() const override { return 0; }
107   ArchSpec GetArchitecture() override { return {}; }
108   Symtab *GetSymtab() override { return nullptr; }
109   bool IsStripped() override { return false; }
110   UUID GetUUID() override { return {}; }
111   lldb::ByteOrder GetByteOrder() const override {
112     return lldb::eByteOrderLittle;
113   }
114   bool ParseHeader() override { return false; }
115   Type CalculateType() override { return {}; }
116   Strata CalculateStrata() override { return {}; }
117   /// \}
118 };
119 
120 /// Helper class that can construct a module from YAML and evaluate
121 /// DWARF expressions on it.
122 class YAMLModuleTester {
123   SubsystemRAII<FileSystem> subsystems;
124   llvm::StringMap<std::unique_ptr<llvm::MemoryBuffer>> m_sections_map;
125   lldb::ModuleSP m_module_sp;
126   lldb::ObjectFileSP m_objfile_sp;
127   DWARFUnitSP m_dwarf_unit;
128   std::unique_ptr<SymbolFileDWARF> m_symfile_dwarf;
129 
130 public:
131   /// Parse the debug info sections from the YAML description.
132   YAMLModuleTester(llvm::StringRef yaml_data, llvm::StringRef triple) {
133     auto sections_map = llvm::DWARFYAML::EmitDebugSections(yaml_data, true);
134     if (!sections_map)
135       return;
136     m_sections_map = std::move(*sections_map);
137     ArchSpec arch(triple);
138     m_module_sp = std::make_shared<YAMLModule>(arch);
139     m_objfile_sp = std::make_shared<YAMLObjectFile>(m_module_sp, m_sections_map);
140     static_cast<YAMLModule *>(m_module_sp.get())->SetObjectFile(m_objfile_sp);
141 
142     lldb::user_id_t uid = 0;
143     llvm::StringRef raw_debug_info = m_sections_map["debug_info"]->getBuffer();
144     lldb_private::DataExtractor debug_info(
145         raw_debug_info.data(), raw_debug_info.size(),
146         m_objfile_sp->GetByteOrder(), m_objfile_sp->GetAddressByteSize());
147     lldb::offset_t offset_ptr = 0;
148     m_symfile_dwarf = std::make_unique<SymbolFileDWARF>(m_objfile_sp, nullptr);
149     llvm::Expected<DWARFUnitSP> dwarf_unit = DWARFUnit::extract(
150         *m_symfile_dwarf, uid,
151         *static_cast<lldb_private::DWARFDataExtractor *>(&debug_info),
152         DIERef::DebugInfo, &offset_ptr);
153     if (dwarf_unit)
154       m_dwarf_unit = dwarf_unit.get();
155   }
156   DWARFUnitSP GetDwarfUnit() { return m_dwarf_unit; }
157 
158   // Evaluate a raw DWARF expression.
159   llvm::Expected<Scalar> Eval(llvm::ArrayRef<uint8_t> expr) {
160     return ::Evaluate(expr, m_module_sp, m_dwarf_unit.get());
161   }
162 };
163 
164 /// Unfortunately Scalar's operator==() is really picky.
165 static Scalar GetScalar(unsigned bits, uint64_t value, bool sign) {
166   Scalar scalar;
167   auto type = Scalar::GetBestTypeForBitSize(bits, sign);
168   switch (type) {
169   case Scalar::e_sint:
170     scalar = Scalar((int)value);
171     break;
172   case Scalar::e_slong:
173     scalar = Scalar((long)value);
174     break;
175   case Scalar::e_slonglong:
176     scalar = Scalar((long long)value);
177     break;
178   case Scalar::e_uint:
179     scalar = Scalar((unsigned int)value);
180     break;
181   case Scalar::e_ulong:
182     scalar = Scalar((unsigned long)value);
183     break;
184   case Scalar::e_ulonglong:
185     scalar = Scalar((unsigned long long)value);
186     break;
187   default:
188     llvm_unreachable("not implemented");
189   }
190   scalar.TruncOrExtendTo(type, bits);
191   if (sign)
192     scalar.MakeSigned();
193   else
194     scalar.MakeUnsigned();
195   return scalar;
196 }
197 
198 TEST(DWARFExpression, DW_OP_pick) {
199   EXPECT_THAT_EXPECTED(Evaluate({DW_OP_lit1, DW_OP_lit0, DW_OP_pick, 0}),
200                        llvm::HasValue(0));
201   EXPECT_THAT_EXPECTED(Evaluate({DW_OP_lit1, DW_OP_lit0, DW_OP_pick, 1}),
202                        llvm::HasValue(1));
203   EXPECT_THAT_EXPECTED(Evaluate({DW_OP_lit1, DW_OP_lit0, DW_OP_pick, 2}),
204                        llvm::Failed());
205 }
206 
207 TEST(DWARFExpression, DW_OP_convert) {
208   /// Auxiliary debug info.
209   const char *yamldata =
210       "debug_abbrev:\n"
211       "  - Code:            0x00000001\n"
212       "    Tag:             DW_TAG_compile_unit\n"
213       "    Children:        DW_CHILDREN_yes\n"
214       "    Attributes:\n"
215       "      - Attribute:       DW_AT_language\n"
216       "        Form:            DW_FORM_data2\n"
217       "  - Code:            0x00000002\n"
218       "    Tag:             DW_TAG_base_type\n"
219       "    Children:        DW_CHILDREN_no\n"
220       "    Attributes:\n"
221       "      - Attribute:       DW_AT_encoding\n"
222       "        Form:            DW_FORM_data1\n"
223       "      - Attribute:       DW_AT_byte_size\n"
224       "        Form:            DW_FORM_data1\n"
225       "debug_info:\n"
226       "  - Length:\n"
227       "      TotalLength:     0\n"
228       "    Version:         4\n"
229       "    AbbrOffset:      0\n"
230       "    AddrSize:        8\n"
231       "    Entries:\n"
232       "      - AbbrCode:        0x00000001\n"
233       "        Values:\n"
234       "          - Value:           0x000000000000000C\n"
235       // 0x0000000e:
236       "      - AbbrCode:        0x00000002\n"
237       "        Values:\n"
238       "          - Value:           0x0000000000000007\n" // DW_ATE_unsigned
239       "          - Value:           0x0000000000000004\n"
240       // 0x00000011:
241       "      - AbbrCode:        0x00000002\n"
242       "        Values:\n"
243       "          - Value:           0x0000000000000007\n" // DW_ATE_unsigned
244       "          - Value:           0x0000000000000008\n"
245       // 0x00000014:
246       "      - AbbrCode:        0x00000002\n"
247       "        Values:\n"
248       "          - Value:           0x0000000000000005\n" // DW_ATE_signed
249       "          - Value:           0x0000000000000008\n"
250       // 0x00000017:
251       "      - AbbrCode:        0x00000002\n"
252       "        Values:\n"
253       "          - Value:           0x0000000000000008\n" // DW_ATE_unsigned_char
254       "          - Value:           0x0000000000000001\n"
255       // 0x0000001a:
256       "      - AbbrCode:        0x00000002\n"
257       "        Values:\n"
258       "          - Value:           0x0000000000000006\n" // DW_ATE_signed_char
259       "          - Value:           0x0000000000000001\n"
260       // 0x0000001d:
261       "      - AbbrCode:        0x00000002\n"
262       "        Values:\n"
263       "          - Value:           0x000000000000000b\n" // DW_ATE_numeric_string
264       "          - Value:           0x0000000000000001\n"
265       ""
266       "      - AbbrCode:        0x00000000\n"
267       "        Values:          []\n";
268   uint8_t offs_uint32_t = 0x0000000e;
269   uint8_t offs_uint64_t = 0x00000011;
270   uint8_t offs_sint64_t = 0x00000014;
271   uint8_t offs_uchar = 0x00000017;
272   uint8_t offs_schar = 0x0000001a;
273 
274   YAMLModuleTester t(yamldata, "i386-unknown-linux");
275   ASSERT_TRUE((bool)t.GetDwarfUnit());
276 
277   // Constant is given as little-endian.
278   bool is_signed = true;
279   bool not_signed = false;
280 
281   //
282   // Positive tests.
283   //
284 
285   // Truncate to default unspecified (pointer-sized) type.
286   EXPECT_THAT_EXPECTED(
287       t.Eval({DW_OP_const8u, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, //
288               DW_OP_convert, 0x00}),
289       llvm::HasValue(GetScalar(32, 0x44332211, not_signed)));
290   // Truncate to 32 bits.
291   EXPECT_THAT_EXPECTED(t.Eval({DW_OP_const8u, //
292                                0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88,//
293                                DW_OP_convert, offs_uint32_t}),
294                        llvm::HasValue(GetScalar(32, 0x44332211, not_signed)));
295 
296   // Leave as is.
297   EXPECT_THAT_EXPECTED(
298       t.Eval({DW_OP_const8u, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, //
299               DW_OP_convert, offs_uint64_t}),
300       llvm::HasValue(GetScalar(64, 0x8877665544332211, not_signed)));
301 
302   // Sign-extend to 64 bits.
303   EXPECT_THAT_EXPECTED(
304       t.Eval({DW_OP_const4s, 0xcc, 0xdd, 0xee, 0xff, //
305               DW_OP_convert, offs_sint64_t}),
306       llvm::HasValue(GetScalar(64, 0xffffffffffeeddcc, is_signed)));
307 
308   // Truncate to 8 bits.
309   EXPECT_THAT_EXPECTED(t.Eval({DW_OP_const4s, 'A', 'B', 'C', 'D', 0xee, 0xff, //
310                                DW_OP_convert, offs_uchar}),
311                        llvm::HasValue(GetScalar(8, 'A', not_signed)));
312 
313   // Also truncate to 8 bits.
314   EXPECT_THAT_EXPECTED(t.Eval({DW_OP_const4s, 'A', 'B', 'C', 'D', 0xee, 0xff, //
315                                DW_OP_convert, offs_schar}),
316                        llvm::HasValue(GetScalar(8, 'A', is_signed)));
317 
318   //
319   // Errors.
320   //
321 
322   // No Module.
323   EXPECT_THAT_ERROR(Evaluate({DW_OP_const1s, 'X', DW_OP_convert, 0x00}, nullptr,
324                              t.GetDwarfUnit().get())
325                         .takeError(),
326                     llvm::Failed());
327 
328   // No DIE.
329   EXPECT_THAT_ERROR(
330       t.Eval({DW_OP_const1s, 'X', DW_OP_convert, 0x01}).takeError(),
331       llvm::Failed());
332 
333   // Unsupported.
334   EXPECT_THAT_ERROR(
335       t.Eval({DW_OP_const1s, 'X', DW_OP_convert, 0x1d}).takeError(),
336       llvm::Failed());
337 }
338