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