1 //===- llvm/unittest/DebugInfo/DWARFDebugInfoTest.cpp ---------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "DwarfGenerator.h"
11 #include "DwarfUtils.h"
12 #include "llvm/ADT/ArrayRef.h"
13 #include "llvm/ADT/Optional.h"
14 #include "llvm/ADT/SmallString.h"
15 #include "llvm/ADT/StringRef.h"
16 #include "llvm/ADT/Triple.h"
17 #include "llvm/BinaryFormat/Dwarf.h"
18 #include "llvm/CodeGen/AsmPrinter.h"
19 #include "llvm/DebugInfo/DWARF/DWARFCompileUnit.h"
20 #include "llvm/DebugInfo/DWARF/DWARFContext.h"
21 #include "llvm/DebugInfo/DWARF/DWARFDie.h"
22 #include "llvm/DebugInfo/DWARF/DWARFFormValue.h"
23 #include "llvm/DebugInfo/DWARF/DWARFVerifier.h"
24 #include "llvm/MC/MCContext.h"
25 #include "llvm/MC/MCSectionELF.h"
26 #include "llvm/MC/MCStreamer.h"
27 #include "llvm/Object/ObjectFile.h"
28 #include "llvm/ObjectYAML/DWARFEmitter.h"
29 #include "llvm/Support/Error.h"
30 #include "llvm/Support/MemoryBuffer.h"
31 #include "llvm/Support/TargetRegistry.h"
32 #include "llvm/Support/TargetSelect.h"
33 #include "llvm/Testing/Support/Error.h"
34 #include "gtest/gtest.h"
35 #include <string>
36 
37 using namespace llvm;
38 using namespace dwarf;
39 using namespace utils;
40 
41 namespace {
42 
43 template <uint16_t Version, class AddrType, class RefAddrType>
TestAllForms()44 void TestAllForms() {
45   Triple Triple = getHostTripleForAddrSize(sizeof(AddrType));
46   if (!isConfigurationSupported(Triple))
47     return;
48 
49   // Test that we can decode all DW_FORM values correctly.
50   const AddrType AddrValue = (AddrType)0x0123456789abcdefULL;
51   const uint8_t BlockData[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
52   const uint32_t BlockSize = sizeof(BlockData);
53   const RefAddrType RefAddr = 0x12345678;
54   const uint8_t Data1 = 0x01U;
55   const uint16_t Data2 = 0x2345U;
56   const uint32_t Data4 = 0x6789abcdU;
57   const uint64_t Data8 = 0x0011223344556677ULL;
58   const uint64_t Data8_2 = 0xAABBCCDDEEFF0011ULL;
59   const uint8_t Data16[16] = {1, 2,  3,  4,  5,  6,  7,  8,
60                               9, 10, 11, 12, 13, 14, 15, 16};
61   const int64_t SData = INT64_MIN;
62   const int64_t ICSData = INT64_MAX; // DW_FORM_implicit_const SData
63   const uint64_t UData[] = {UINT64_MAX - 1, UINT64_MAX - 2, UINT64_MAX - 3,
64                             UINT64_MAX - 4, UINT64_MAX - 5, UINT64_MAX - 6,
65                             UINT64_MAX - 7, UINT64_MAX - 8, UINT64_MAX - 9};
66 #define UDATA_1 18446744073709551614ULL
67   const uint32_t Dwarf32Values[] = {1, 2, 3, 4, 5, 6, 7, 8};
68   const char *StringValue = "Hello";
69   const char *StrpValue = "World";
70   const char *StrxValue = "Indexed";
71   const char *Strx1Value = "Indexed1";
72   const char *Strx2Value = "Indexed2";
73   const char *Strx3Value = "Indexed3";
74   const char *Strx4Value = "Indexed4";
75 
76   auto ExpectedDG = dwarfgen::Generator::create(Triple, Version);
77   ASSERT_THAT_EXPECTED(ExpectedDG, Succeeded());
78   dwarfgen::Generator *DG = ExpectedDG.get().get();
79   dwarfgen::CompileUnit &CU = DG->addCompileUnit();
80   dwarfgen::DIE CUDie = CU.getUnitDIE();
81 
82   if (Version >= 5)
83     CUDie.addStrOffsetsBaseAttribute();
84 
85   uint16_t Attr = DW_AT_lo_user;
86 
87   //----------------------------------------------------------------------
88   // Test address forms
89   //----------------------------------------------------------------------
90   const auto Attr_DW_FORM_addr = static_cast<dwarf::Attribute>(Attr++);
91   CUDie.addAttribute(Attr_DW_FORM_addr, DW_FORM_addr, AddrValue);
92 
93   //----------------------------------------------------------------------
94   // Test block forms
95   //----------------------------------------------------------------------
96   const auto Attr_DW_FORM_block = static_cast<dwarf::Attribute>(Attr++);
97   CUDie.addAttribute(Attr_DW_FORM_block, DW_FORM_block, BlockData, BlockSize);
98 
99   const auto Attr_DW_FORM_block1 = static_cast<dwarf::Attribute>(Attr++);
100   CUDie.addAttribute(Attr_DW_FORM_block1, DW_FORM_block1, BlockData, BlockSize);
101 
102   const auto Attr_DW_FORM_block2 = static_cast<dwarf::Attribute>(Attr++);
103   CUDie.addAttribute(Attr_DW_FORM_block2, DW_FORM_block2, BlockData, BlockSize);
104 
105   const auto Attr_DW_FORM_block4 = static_cast<dwarf::Attribute>(Attr++);
106   CUDie.addAttribute(Attr_DW_FORM_block4, DW_FORM_block4, BlockData, BlockSize);
107 
108   // We handle data16 as a block form.
109   const auto Attr_DW_FORM_data16 = static_cast<dwarf::Attribute>(Attr++);
110   if (Version >= 5)
111     CUDie.addAttribute(Attr_DW_FORM_data16, DW_FORM_data16, Data16, 16);
112 
113   //----------------------------------------------------------------------
114   // Test data forms
115   //----------------------------------------------------------------------
116   const auto Attr_DW_FORM_data1 = static_cast<dwarf::Attribute>(Attr++);
117   CUDie.addAttribute(Attr_DW_FORM_data1, DW_FORM_data1, Data1);
118 
119   const auto Attr_DW_FORM_data2 = static_cast<dwarf::Attribute>(Attr++);
120   CUDie.addAttribute(Attr_DW_FORM_data2, DW_FORM_data2, Data2);
121 
122   const auto Attr_DW_FORM_data4 = static_cast<dwarf::Attribute>(Attr++);
123   CUDie.addAttribute(Attr_DW_FORM_data4, DW_FORM_data4, Data4);
124 
125   const auto Attr_DW_FORM_data8 = static_cast<dwarf::Attribute>(Attr++);
126   CUDie.addAttribute(Attr_DW_FORM_data8, DW_FORM_data8, Data8);
127 
128   //----------------------------------------------------------------------
129   // Test string forms
130   //----------------------------------------------------------------------
131   const auto Attr_DW_FORM_string = static_cast<dwarf::Attribute>(Attr++);
132   CUDie.addAttribute(Attr_DW_FORM_string, DW_FORM_string, StringValue);
133 
134   const auto Attr_DW_FORM_strx = static_cast<dwarf::Attribute>(Attr++);
135   const auto Attr_DW_FORM_strx1 = static_cast<dwarf::Attribute>(Attr++);
136   const auto Attr_DW_FORM_strx2 = static_cast<dwarf::Attribute>(Attr++);
137   const auto Attr_DW_FORM_strx3 = static_cast<dwarf::Attribute>(Attr++);
138   const auto Attr_DW_FORM_strx4 = static_cast<dwarf::Attribute>(Attr++);
139   if (Version >= 5) {
140     CUDie.addAttribute(Attr_DW_FORM_strx, DW_FORM_strx, StrxValue);
141     CUDie.addAttribute(Attr_DW_FORM_strx1, DW_FORM_strx1, Strx1Value);
142     CUDie.addAttribute(Attr_DW_FORM_strx2, DW_FORM_strx2, Strx2Value);
143     CUDie.addAttribute(Attr_DW_FORM_strx3, DW_FORM_strx3, Strx3Value);
144     CUDie.addAttribute(Attr_DW_FORM_strx4, DW_FORM_strx4, Strx4Value);
145   }
146 
147   const auto Attr_DW_FORM_strp = static_cast<dwarf::Attribute>(Attr++);
148   CUDie.addAttribute(Attr_DW_FORM_strp, DW_FORM_strp, StrpValue);
149 
150   //----------------------------------------------------------------------
151   // Test reference forms
152   //----------------------------------------------------------------------
153   const auto Attr_DW_FORM_ref_addr = static_cast<dwarf::Attribute>(Attr++);
154   CUDie.addAttribute(Attr_DW_FORM_ref_addr, DW_FORM_ref_addr, RefAddr);
155 
156   const auto Attr_DW_FORM_ref1 = static_cast<dwarf::Attribute>(Attr++);
157   CUDie.addAttribute(Attr_DW_FORM_ref1, DW_FORM_ref1, Data1);
158 
159   const auto Attr_DW_FORM_ref2 = static_cast<dwarf::Attribute>(Attr++);
160   CUDie.addAttribute(Attr_DW_FORM_ref2, DW_FORM_ref2, Data2);
161 
162   const auto Attr_DW_FORM_ref4 = static_cast<dwarf::Attribute>(Attr++);
163   CUDie.addAttribute(Attr_DW_FORM_ref4, DW_FORM_ref4, Data4);
164 
165   const auto Attr_DW_FORM_ref8 = static_cast<dwarf::Attribute>(Attr++);
166   CUDie.addAttribute(Attr_DW_FORM_ref8, DW_FORM_ref8, Data8);
167 
168   const auto Attr_DW_FORM_ref_sig8 = static_cast<dwarf::Attribute>(Attr++);
169   if (Version >= 4)
170     CUDie.addAttribute(Attr_DW_FORM_ref_sig8, DW_FORM_ref_sig8, Data8_2);
171 
172   const auto Attr_DW_FORM_ref_udata = static_cast<dwarf::Attribute>(Attr++);
173   CUDie.addAttribute(Attr_DW_FORM_ref_udata, DW_FORM_ref_udata, UData[0]);
174 
175   //----------------------------------------------------------------------
176   // Test flag forms
177   //----------------------------------------------------------------------
178   const auto Attr_DW_FORM_flag_true = static_cast<dwarf::Attribute>(Attr++);
179   CUDie.addAttribute(Attr_DW_FORM_flag_true, DW_FORM_flag, true);
180 
181   const auto Attr_DW_FORM_flag_false = static_cast<dwarf::Attribute>(Attr++);
182   CUDie.addAttribute(Attr_DW_FORM_flag_false, DW_FORM_flag, false);
183 
184   const auto Attr_DW_FORM_flag_present = static_cast<dwarf::Attribute>(Attr++);
185   if (Version >= 4)
186     CUDie.addAttribute(Attr_DW_FORM_flag_present, DW_FORM_flag_present);
187 
188   //----------------------------------------------------------------------
189   // Test SLEB128 based forms
190   //----------------------------------------------------------------------
191   const auto Attr_DW_FORM_sdata = static_cast<dwarf::Attribute>(Attr++);
192   CUDie.addAttribute(Attr_DW_FORM_sdata, DW_FORM_sdata, SData);
193 
194   const auto Attr_DW_FORM_implicit_const =
195     static_cast<dwarf::Attribute>(Attr++);
196   if (Version >= 5)
197     CUDie.addAttribute(Attr_DW_FORM_implicit_const, DW_FORM_implicit_const,
198                        ICSData);
199 
200   //----------------------------------------------------------------------
201   // Test ULEB128 based forms
202   //----------------------------------------------------------------------
203   const auto Attr_DW_FORM_udata = static_cast<dwarf::Attribute>(Attr++);
204   CUDie.addAttribute(Attr_DW_FORM_udata, DW_FORM_udata, UData[0]);
205 
206   //----------------------------------------------------------------------
207   // Test DWARF32/DWARF64 forms
208   //----------------------------------------------------------------------
209   const auto Attr_DW_FORM_GNU_ref_alt = static_cast<dwarf::Attribute>(Attr++);
210   CUDie.addAttribute(Attr_DW_FORM_GNU_ref_alt, DW_FORM_GNU_ref_alt,
211                      Dwarf32Values[0]);
212 
213   const auto Attr_DW_FORM_sec_offset = static_cast<dwarf::Attribute>(Attr++);
214   if (Version >= 4)
215     CUDie.addAttribute(Attr_DW_FORM_sec_offset, DW_FORM_sec_offset,
216                        Dwarf32Values[1]);
217 
218   //----------------------------------------------------------------------
219   // Add an address at the end to make sure we can decode this value
220   //----------------------------------------------------------------------
221   const auto Attr_Last = static_cast<dwarf::Attribute>(Attr++);
222   CUDie.addAttribute(Attr_Last, DW_FORM_addr, AddrValue);
223 
224   //----------------------------------------------------------------------
225   // Generate the DWARF
226   //----------------------------------------------------------------------
227   StringRef FileBytes = DG->generate();
228   MemoryBufferRef FileBuffer(FileBytes, "dwarf");
229   auto Obj = object::ObjectFile::createObjectFile(FileBuffer);
230   EXPECT_TRUE((bool)Obj);
231   std::unique_ptr<DWARFContext> DwarfContext = DWARFContext::create(**Obj);
232   uint32_t NumCUs = DwarfContext->getNumCompileUnits();
233   EXPECT_EQ(NumCUs, 1u);
234   DWARFCompileUnit *U = DwarfContext->getCompileUnitAtIndex(0);
235   auto DieDG = U->getUnitDIE(false);
236   EXPECT_TRUE(DieDG.isValid());
237 
238   //----------------------------------------------------------------------
239   // Test address forms
240   //----------------------------------------------------------------------
241   EXPECT_EQ(AddrValue, toAddress(DieDG.find(Attr_DW_FORM_addr), 0));
242 
243   //----------------------------------------------------------------------
244   // Test block forms
245   //----------------------------------------------------------------------
246   Optional<DWARFFormValue> FormValue;
247   ArrayRef<uint8_t> ExtractedBlockData;
248   Optional<ArrayRef<uint8_t>> BlockDataOpt;
249 
250   FormValue = DieDG.find(Attr_DW_FORM_block);
251   EXPECT_TRUE((bool)FormValue);
252   BlockDataOpt = FormValue->getAsBlock();
253   EXPECT_TRUE(BlockDataOpt.hasValue());
254   ExtractedBlockData = BlockDataOpt.getValue();
255   EXPECT_EQ(ExtractedBlockData.size(), BlockSize);
256   EXPECT_TRUE(memcmp(ExtractedBlockData.data(), BlockData, BlockSize) == 0);
257 
258   FormValue = DieDG.find(Attr_DW_FORM_block1);
259   EXPECT_TRUE((bool)FormValue);
260   BlockDataOpt = FormValue->getAsBlock();
261   EXPECT_TRUE(BlockDataOpt.hasValue());
262   ExtractedBlockData = BlockDataOpt.getValue();
263   EXPECT_EQ(ExtractedBlockData.size(), BlockSize);
264   EXPECT_TRUE(memcmp(ExtractedBlockData.data(), BlockData, BlockSize) == 0);
265 
266   FormValue = DieDG.find(Attr_DW_FORM_block2);
267   EXPECT_TRUE((bool)FormValue);
268   BlockDataOpt = FormValue->getAsBlock();
269   EXPECT_TRUE(BlockDataOpt.hasValue());
270   ExtractedBlockData = BlockDataOpt.getValue();
271   EXPECT_EQ(ExtractedBlockData.size(), BlockSize);
272   EXPECT_TRUE(memcmp(ExtractedBlockData.data(), BlockData, BlockSize) == 0);
273 
274   FormValue = DieDG.find(Attr_DW_FORM_block4);
275   EXPECT_TRUE((bool)FormValue);
276   BlockDataOpt = FormValue->getAsBlock();
277   EXPECT_TRUE(BlockDataOpt.hasValue());
278   ExtractedBlockData = BlockDataOpt.getValue();
279   EXPECT_EQ(ExtractedBlockData.size(), BlockSize);
280   EXPECT_TRUE(memcmp(ExtractedBlockData.data(), BlockData, BlockSize) == 0);
281 
282   // Data16 is handled like a block.
283   if (Version >= 5) {
284     FormValue = DieDG.find(Attr_DW_FORM_data16);
285     EXPECT_TRUE((bool)FormValue);
286     BlockDataOpt = FormValue->getAsBlock();
287     EXPECT_TRUE(BlockDataOpt.hasValue());
288     ExtractedBlockData = BlockDataOpt.getValue();
289     EXPECT_EQ(ExtractedBlockData.size(), 16u);
290     EXPECT_TRUE(memcmp(ExtractedBlockData.data(), Data16, 16) == 0);
291   }
292 
293   //----------------------------------------------------------------------
294   // Test data forms
295   //----------------------------------------------------------------------
296   EXPECT_EQ(Data1, toUnsigned(DieDG.find(Attr_DW_FORM_data1), 0));
297   EXPECT_EQ(Data2, toUnsigned(DieDG.find(Attr_DW_FORM_data2), 0));
298   EXPECT_EQ(Data4, toUnsigned(DieDG.find(Attr_DW_FORM_data4), 0));
299   EXPECT_EQ(Data8, toUnsigned(DieDG.find(Attr_DW_FORM_data8), 0));
300 
301   //----------------------------------------------------------------------
302   // Test string forms
303   //----------------------------------------------------------------------
304   auto ExtractedStringValue = toString(DieDG.find(Attr_DW_FORM_string));
305   EXPECT_TRUE((bool)ExtractedStringValue);
306   EXPECT_STREQ(StringValue, *ExtractedStringValue);
307 
308   if (Version >= 5) {
309     auto ExtractedStrxValue = toString(DieDG.find(Attr_DW_FORM_strx));
310     EXPECT_TRUE((bool)ExtractedStrxValue);
311     EXPECT_STREQ(StrxValue, *ExtractedStrxValue);
312 
313     auto ExtractedStrx1Value = toString(DieDG.find(Attr_DW_FORM_strx1));
314     EXPECT_TRUE((bool)ExtractedStrx1Value);
315     EXPECT_STREQ(Strx1Value, *ExtractedStrx1Value);
316 
317     auto ExtractedStrx2Value = toString(DieDG.find(Attr_DW_FORM_strx2));
318     EXPECT_TRUE((bool)ExtractedStrx2Value);
319     EXPECT_STREQ(Strx2Value, *ExtractedStrx2Value);
320 
321     auto ExtractedStrx3Value = toString(DieDG.find(Attr_DW_FORM_strx3));
322     EXPECT_TRUE((bool)ExtractedStrx3Value);
323     EXPECT_STREQ(Strx3Value, *ExtractedStrx3Value);
324 
325     auto ExtractedStrx4Value = toString(DieDG.find(Attr_DW_FORM_strx4));
326     EXPECT_TRUE((bool)ExtractedStrx4Value);
327     EXPECT_STREQ(Strx4Value, *ExtractedStrx4Value);
328   }
329 
330   auto ExtractedStrpValue = toString(DieDG.find(Attr_DW_FORM_strp));
331   EXPECT_TRUE((bool)ExtractedStrpValue);
332   EXPECT_STREQ(StrpValue, *ExtractedStrpValue);
333 
334   //----------------------------------------------------------------------
335   // Test reference forms
336   //----------------------------------------------------------------------
337   EXPECT_EQ(RefAddr, toReference(DieDG.find(Attr_DW_FORM_ref_addr), 0));
338   EXPECT_EQ(Data1, toReference(DieDG.find(Attr_DW_FORM_ref1), 0));
339   EXPECT_EQ(Data2, toReference(DieDG.find(Attr_DW_FORM_ref2), 0));
340   EXPECT_EQ(Data4, toReference(DieDG.find(Attr_DW_FORM_ref4), 0));
341   EXPECT_EQ(Data8, toReference(DieDG.find(Attr_DW_FORM_ref8), 0));
342   if (Version >= 4) {
343     EXPECT_EQ(Data8_2, toReference(DieDG.find(Attr_DW_FORM_ref_sig8), 0));
344   }
345   EXPECT_EQ(UData[0], toReference(DieDG.find(Attr_DW_FORM_ref_udata), 0));
346 
347   //----------------------------------------------------------------------
348   // Test flag forms
349   //----------------------------------------------------------------------
350   EXPECT_EQ(1ULL, toUnsigned(DieDG.find(Attr_DW_FORM_flag_true), 0));
351   EXPECT_EQ(0ULL, toUnsigned(DieDG.find(Attr_DW_FORM_flag_false), 1));
352   if (Version >= 4) {
353     EXPECT_EQ(1ULL, toUnsigned(DieDG.find(Attr_DW_FORM_flag_present), 0));
354   }
355 
356   //----------------------------------------------------------------------
357   // Test SLEB128 based forms
358   //----------------------------------------------------------------------
359   EXPECT_EQ(SData, toSigned(DieDG.find(Attr_DW_FORM_sdata), 0));
360   if (Version >= 5) {
361     EXPECT_EQ(ICSData, toSigned(DieDG.find(Attr_DW_FORM_implicit_const), 0));
362   }
363 
364   //----------------------------------------------------------------------
365   // Test ULEB128 based forms
366   //----------------------------------------------------------------------
367   EXPECT_EQ(UData[0], toUnsigned(DieDG.find(Attr_DW_FORM_udata), 0));
368 
369   //----------------------------------------------------------------------
370   // Test DWARF32/DWARF64 forms
371   //----------------------------------------------------------------------
372   EXPECT_EQ(Dwarf32Values[0],
373             toReference(DieDG.find(Attr_DW_FORM_GNU_ref_alt), 0));
374   if (Version >= 4) {
375     EXPECT_EQ(Dwarf32Values[1],
376               toSectionOffset(DieDG.find(Attr_DW_FORM_sec_offset), 0));
377   }
378 
379   //----------------------------------------------------------------------
380   // Add an address at the end to make sure we can decode this value
381   //----------------------------------------------------------------------
382   EXPECT_EQ(AddrValue, toAddress(DieDG.find(Attr_Last), 0));
383 }
384 
TEST(DWARFDebugInfo,TestDWARF32Version2Addr4AllForms)385 TEST(DWARFDebugInfo, TestDWARF32Version2Addr4AllForms) {
386   // Test that we can decode all forms for DWARF32, version 2, with 4 byte
387   // addresses.
388   typedef uint32_t AddrType;
389   // DW_FORM_ref_addr are the same as the address type in DWARF32 version 2.
390   typedef AddrType RefAddrType;
391   TestAllForms<2, AddrType, RefAddrType>();
392 }
393 
TEST(DWARFDebugInfo,TestDWARF32Version2Addr8AllForms)394 TEST(DWARFDebugInfo, TestDWARF32Version2Addr8AllForms) {
395   // Test that we can decode all forms for DWARF32, version 2, with 4 byte
396   // addresses.
397   typedef uint64_t AddrType;
398   // DW_FORM_ref_addr are the same as the address type in DWARF32 version 2.
399   typedef AddrType RefAddrType;
400   TestAllForms<2, AddrType, RefAddrType>();
401 }
402 
TEST(DWARFDebugInfo,TestDWARF32Version3Addr4AllForms)403 TEST(DWARFDebugInfo, TestDWARF32Version3Addr4AllForms) {
404   // Test that we can decode all forms for DWARF32, version 3, with 4 byte
405   // addresses.
406   typedef uint32_t AddrType;
407   // DW_FORM_ref_addr are 4 bytes in DWARF32 for version 3 and later.
408   typedef uint32_t RefAddrType;
409   TestAllForms<3, AddrType, RefAddrType>();
410 }
411 
TEST(DWARFDebugInfo,TestDWARF32Version3Addr8AllForms)412 TEST(DWARFDebugInfo, TestDWARF32Version3Addr8AllForms) {
413   // Test that we can decode all forms for DWARF32, version 3, with 8 byte
414   // addresses.
415   typedef uint64_t AddrType;
416   // DW_FORM_ref_addr are 4 bytes in DWARF32 for version 3 and later
417   typedef uint32_t RefAddrType;
418   TestAllForms<3, AddrType, RefAddrType>();
419 }
420 
TEST(DWARFDebugInfo,TestDWARF32Version4Addr4AllForms)421 TEST(DWARFDebugInfo, TestDWARF32Version4Addr4AllForms) {
422   // Test that we can decode all forms for DWARF32, version 4, with 4 byte
423   // addresses.
424   typedef uint32_t AddrType;
425   // DW_FORM_ref_addr are 4 bytes in DWARF32 for version 3 and later
426   typedef uint32_t RefAddrType;
427   TestAllForms<4, AddrType, RefAddrType>();
428 }
429 
TEST(DWARFDebugInfo,TestDWARF32Version4Addr8AllForms)430 TEST(DWARFDebugInfo, TestDWARF32Version4Addr8AllForms) {
431   // Test that we can decode all forms for DWARF32, version 4, with 8 byte
432   // addresses.
433   typedef uint64_t AddrType;
434   // DW_FORM_ref_addr are 4 bytes in DWARF32 for version 3 and later
435   typedef uint32_t RefAddrType;
436   TestAllForms<4, AddrType, RefAddrType>();
437 }
438 
TEST(DWARFDebugInfo,TestDWARF32Version5Addr4AllForms)439 TEST(DWARFDebugInfo, TestDWARF32Version5Addr4AllForms) {
440   // Test that we can decode all forms for DWARF32, version 5, with 4 byte
441   // addresses.
442   typedef uint32_t AddrType;
443   // DW_FORM_ref_addr are 4 bytes in DWARF32 for version 3 and later
444   typedef uint32_t RefAddrType;
445   TestAllForms<5, AddrType, RefAddrType>();
446 }
447 
TEST(DWARFDebugInfo,TestDWARF32Version5Addr8AllForms)448 TEST(DWARFDebugInfo, TestDWARF32Version5Addr8AllForms) {
449   // Test that we can decode all forms for DWARF32, version 5, with 8 byte
450   // addresses.
451   typedef uint64_t AddrType;
452   // DW_FORM_ref_addr are 4 bytes in DWARF32 for version 3 and later
453   typedef uint32_t RefAddrType;
454   TestAllForms<5, AddrType, RefAddrType>();
455 }
456 
TestChildren()457 template <uint16_t Version, class AddrType> void TestChildren() {
458   Triple Triple = getHostTripleForAddrSize(sizeof(AddrType));
459   if (!isConfigurationSupported(Triple))
460     return;
461 
462   // Test that we can decode DW_FORM_ref_addr values correctly in DWARF 2 with
463   // 4 byte addresses. DW_FORM_ref_addr values should be 4 bytes when using
464   // 8 byte addresses.
465 
466   auto ExpectedDG = dwarfgen::Generator::create(Triple, Version);
467   ASSERT_THAT_EXPECTED(ExpectedDG, Succeeded());
468   dwarfgen::Generator *DG = ExpectedDG.get().get();
469   dwarfgen::CompileUnit &CU = DG->addCompileUnit();
470   dwarfgen::DIE CUDie = CU.getUnitDIE();
471 
472   CUDie.addAttribute(DW_AT_name, DW_FORM_strp, "/tmp/main.c");
473   CUDie.addAttribute(DW_AT_language, DW_FORM_data2, DW_LANG_C);
474 
475   dwarfgen::DIE SubprogramDie = CUDie.addChild(DW_TAG_subprogram);
476   SubprogramDie.addAttribute(DW_AT_name, DW_FORM_strp, "main");
477   SubprogramDie.addAttribute(DW_AT_low_pc, DW_FORM_addr, 0x1000U);
478   SubprogramDie.addAttribute(DW_AT_high_pc, DW_FORM_addr, 0x2000U);
479 
480   dwarfgen::DIE IntDie = CUDie.addChild(DW_TAG_base_type);
481   IntDie.addAttribute(DW_AT_name, DW_FORM_strp, "int");
482   IntDie.addAttribute(DW_AT_encoding, DW_FORM_data1, DW_ATE_signed);
483   IntDie.addAttribute(DW_AT_byte_size, DW_FORM_data1, 4);
484 
485   dwarfgen::DIE ArgcDie = SubprogramDie.addChild(DW_TAG_formal_parameter);
486   ArgcDie.addAttribute(DW_AT_name, DW_FORM_strp, "argc");
487   // ArgcDie.addAttribute(DW_AT_type, DW_FORM_ref4, IntDie);
488   ArgcDie.addAttribute(DW_AT_type, DW_FORM_ref_addr, IntDie);
489 
490   StringRef FileBytes = DG->generate();
491   MemoryBufferRef FileBuffer(FileBytes, "dwarf");
492   auto Obj = object::ObjectFile::createObjectFile(FileBuffer);
493   EXPECT_TRUE((bool)Obj);
494   std::unique_ptr<DWARFContext> DwarfContext = DWARFContext::create(**Obj);
495 
496   // Verify the number of compile units is correct.
497   uint32_t NumCUs = DwarfContext->getNumCompileUnits();
498   EXPECT_EQ(NumCUs, 1u);
499   DWARFCompileUnit *U = DwarfContext->getCompileUnitAtIndex(0);
500 
501   // Get the compile unit DIE is valid.
502   auto DieDG = U->getUnitDIE(false);
503   EXPECT_TRUE(DieDG.isValid());
504 
505   // Verify the first child of the compile unit DIE is our subprogram.
506   auto SubprogramDieDG = DieDG.getFirstChild();
507   EXPECT_TRUE(SubprogramDieDG.isValid());
508   EXPECT_EQ(SubprogramDieDG.getTag(), DW_TAG_subprogram);
509 
510   // Verify the first child of the subprogram is our formal parameter.
511   auto ArgcDieDG = SubprogramDieDG.getFirstChild();
512   EXPECT_TRUE(ArgcDieDG.isValid());
513   EXPECT_EQ(ArgcDieDG.getTag(), DW_TAG_formal_parameter);
514 
515   // Verify our formal parameter has a NULL tag sibling.
516   auto NullDieDG = ArgcDieDG.getSibling();
517   EXPECT_TRUE(NullDieDG.isValid());
518   if (NullDieDG) {
519     EXPECT_EQ(NullDieDG.getTag(), DW_TAG_null);
520     EXPECT_TRUE(!NullDieDG.getSibling().isValid());
521     EXPECT_TRUE(!NullDieDG.getFirstChild().isValid());
522   }
523 
524   // Verify the sibling of our subprogram is our integer base type.
525   auto IntDieDG = SubprogramDieDG.getSibling();
526   EXPECT_TRUE(IntDieDG.isValid());
527   EXPECT_EQ(IntDieDG.getTag(), DW_TAG_base_type);
528 
529   // Verify the sibling of our subprogram is our integer base is a NULL tag.
530   NullDieDG = IntDieDG.getSibling();
531   EXPECT_TRUE(NullDieDG.isValid());
532   if (NullDieDG) {
533     EXPECT_EQ(NullDieDG.getTag(), DW_TAG_null);
534     EXPECT_TRUE(!NullDieDG.getSibling().isValid());
535     EXPECT_TRUE(!NullDieDG.getFirstChild().isValid());
536   }
537 
538   // Verify the previous sibling of our subprogram is our integer base type.
539   IntDieDG = NullDieDG.getPreviousSibling();
540   EXPECT_TRUE(IntDieDG.isValid());
541   EXPECT_EQ(IntDieDG.getTag(), DW_TAG_base_type);
542 }
543 
TEST(DWARFDebugInfo,TestDWARF32Version2Addr4Children)544 TEST(DWARFDebugInfo, TestDWARF32Version2Addr4Children) {
545   // Test that we can decode all forms for DWARF32, version 2, with 4 byte
546   // addresses.
547   typedef uint32_t AddrType;
548   TestChildren<2, AddrType>();
549 }
550 
TEST(DWARFDebugInfo,TestDWARF32Version2Addr8Children)551 TEST(DWARFDebugInfo, TestDWARF32Version2Addr8Children) {
552   // Test that we can decode all forms for DWARF32, version 2, with 8 byte
553   // addresses.
554   typedef uint64_t AddrType;
555   TestChildren<2, AddrType>();
556 }
557 
TEST(DWARFDebugInfo,TestDWARF32Version3Addr4Children)558 TEST(DWARFDebugInfo, TestDWARF32Version3Addr4Children) {
559   // Test that we can decode all forms for DWARF32, version 3, with 4 byte
560   // addresses.
561   typedef uint32_t AddrType;
562   TestChildren<3, AddrType>();
563 }
564 
TEST(DWARFDebugInfo,TestDWARF32Version3Addr8Children)565 TEST(DWARFDebugInfo, TestDWARF32Version3Addr8Children) {
566   // Test that we can decode all forms for DWARF32, version 3, with 8 byte
567   // addresses.
568   typedef uint64_t AddrType;
569   TestChildren<3, AddrType>();
570 }
571 
TEST(DWARFDebugInfo,TestDWARF32Version4Addr4Children)572 TEST(DWARFDebugInfo, TestDWARF32Version4Addr4Children) {
573   // Test that we can decode all forms for DWARF32, version 4, with 4 byte
574   // addresses.
575   typedef uint32_t AddrType;
576   TestChildren<4, AddrType>();
577 }
578 
TEST(DWARFDebugInfo,TestDWARF32Version4Addr8Children)579 TEST(DWARFDebugInfo, TestDWARF32Version4Addr8Children) {
580   // Test that we can decode all forms for DWARF32, version 4, with 8 byte
581   // addresses.
582   typedef uint64_t AddrType;
583   TestChildren<4, AddrType>();
584 }
585 
TestReferences()586 template <uint16_t Version, class AddrType> void TestReferences() {
587   Triple Triple = getHostTripleForAddrSize(sizeof(AddrType));
588   if (!isConfigurationSupported(Triple))
589     return;
590 
591   // Test that we can decode DW_FORM_refXXX values correctly in DWARF.
592   auto ExpectedDG = dwarfgen::Generator::create(Triple, Version);
593   ASSERT_THAT_EXPECTED(ExpectedDG, Succeeded());
594   dwarfgen::Generator *DG = ExpectedDG.get().get();
595   dwarfgen::CompileUnit &CU1 = DG->addCompileUnit();
596   dwarfgen::CompileUnit &CU2 = DG->addCompileUnit();
597 
598   dwarfgen::DIE CU1Die = CU1.getUnitDIE();
599   CU1Die.addAttribute(DW_AT_name, DW_FORM_strp, "/tmp/main.c");
600   CU1Die.addAttribute(DW_AT_language, DW_FORM_data2, DW_LANG_C);
601 
602   dwarfgen::DIE CU1TypeDie = CU1Die.addChild(DW_TAG_base_type);
603   CU1TypeDie.addAttribute(DW_AT_name, DW_FORM_strp, "int");
604   CU1TypeDie.addAttribute(DW_AT_encoding, DW_FORM_data1, DW_ATE_signed);
605   CU1TypeDie.addAttribute(DW_AT_byte_size, DW_FORM_data1, 4);
606 
607   dwarfgen::DIE CU1Ref1Die = CU1Die.addChild(DW_TAG_variable);
608   CU1Ref1Die.addAttribute(DW_AT_name, DW_FORM_strp, "CU1Ref1");
609   CU1Ref1Die.addAttribute(DW_AT_type, DW_FORM_ref1, CU1TypeDie);
610 
611   dwarfgen::DIE CU1Ref2Die = CU1Die.addChild(DW_TAG_variable);
612   CU1Ref2Die.addAttribute(DW_AT_name, DW_FORM_strp, "CU1Ref2");
613   CU1Ref2Die.addAttribute(DW_AT_type, DW_FORM_ref2, CU1TypeDie);
614 
615   dwarfgen::DIE CU1Ref4Die = CU1Die.addChild(DW_TAG_variable);
616   CU1Ref4Die.addAttribute(DW_AT_name, DW_FORM_strp, "CU1Ref4");
617   CU1Ref4Die.addAttribute(DW_AT_type, DW_FORM_ref4, CU1TypeDie);
618 
619   dwarfgen::DIE CU1Ref8Die = CU1Die.addChild(DW_TAG_variable);
620   CU1Ref8Die.addAttribute(DW_AT_name, DW_FORM_strp, "CU1Ref8");
621   CU1Ref8Die.addAttribute(DW_AT_type, DW_FORM_ref8, CU1TypeDie);
622 
623   dwarfgen::DIE CU1RefAddrDie = CU1Die.addChild(DW_TAG_variable);
624   CU1RefAddrDie.addAttribute(DW_AT_name, DW_FORM_strp, "CU1RefAddr");
625   CU1RefAddrDie.addAttribute(DW_AT_type, DW_FORM_ref_addr, CU1TypeDie);
626 
627   dwarfgen::DIE CU2Die = CU2.getUnitDIE();
628   CU2Die.addAttribute(DW_AT_name, DW_FORM_strp, "/tmp/foo.c");
629   CU2Die.addAttribute(DW_AT_language, DW_FORM_data2, DW_LANG_C);
630 
631   dwarfgen::DIE CU2TypeDie = CU2Die.addChild(DW_TAG_base_type);
632   CU2TypeDie.addAttribute(DW_AT_name, DW_FORM_strp, "float");
633   CU2TypeDie.addAttribute(DW_AT_encoding, DW_FORM_data1, DW_ATE_float);
634   CU2TypeDie.addAttribute(DW_AT_byte_size, DW_FORM_data1, 4);
635 
636   dwarfgen::DIE CU2Ref1Die = CU2Die.addChild(DW_TAG_variable);
637   CU2Ref1Die.addAttribute(DW_AT_name, DW_FORM_strp, "CU2Ref1");
638   CU2Ref1Die.addAttribute(DW_AT_type, DW_FORM_ref1, CU2TypeDie);
639 
640   dwarfgen::DIE CU2Ref2Die = CU2Die.addChild(DW_TAG_variable);
641   CU2Ref2Die.addAttribute(DW_AT_name, DW_FORM_strp, "CU2Ref2");
642   CU2Ref2Die.addAttribute(DW_AT_type, DW_FORM_ref2, CU2TypeDie);
643 
644   dwarfgen::DIE CU2Ref4Die = CU2Die.addChild(DW_TAG_variable);
645   CU2Ref4Die.addAttribute(DW_AT_name, DW_FORM_strp, "CU2Ref4");
646   CU2Ref4Die.addAttribute(DW_AT_type, DW_FORM_ref4, CU2TypeDie);
647 
648   dwarfgen::DIE CU2Ref8Die = CU2Die.addChild(DW_TAG_variable);
649   CU2Ref8Die.addAttribute(DW_AT_name, DW_FORM_strp, "CU2Ref8");
650   CU2Ref8Die.addAttribute(DW_AT_type, DW_FORM_ref8, CU2TypeDie);
651 
652   dwarfgen::DIE CU2RefAddrDie = CU2Die.addChild(DW_TAG_variable);
653   CU2RefAddrDie.addAttribute(DW_AT_name, DW_FORM_strp, "CU2RefAddr");
654   CU2RefAddrDie.addAttribute(DW_AT_type, DW_FORM_ref_addr, CU2TypeDie);
655 
656   // Refer to a type in CU1 from CU2
657   dwarfgen::DIE CU2ToCU1RefAddrDie = CU2Die.addChild(DW_TAG_variable);
658   CU2ToCU1RefAddrDie.addAttribute(DW_AT_name, DW_FORM_strp, "CU2ToCU1RefAddr");
659   CU2ToCU1RefAddrDie.addAttribute(DW_AT_type, DW_FORM_ref_addr, CU1TypeDie);
660 
661   // Refer to a type in CU2 from CU1
662   dwarfgen::DIE CU1ToCU2RefAddrDie = CU1Die.addChild(DW_TAG_variable);
663   CU1ToCU2RefAddrDie.addAttribute(DW_AT_name, DW_FORM_strp, "CU1ToCU2RefAddr");
664   CU1ToCU2RefAddrDie.addAttribute(DW_AT_type, DW_FORM_ref_addr, CU2TypeDie);
665 
666   StringRef FileBytes = DG->generate();
667   MemoryBufferRef FileBuffer(FileBytes, "dwarf");
668   auto Obj = object::ObjectFile::createObjectFile(FileBuffer);
669   EXPECT_TRUE((bool)Obj);
670   std::unique_ptr<DWARFContext> DwarfContext = DWARFContext::create(**Obj);
671 
672   // Verify the number of compile units is correct.
673   uint32_t NumCUs = DwarfContext->getNumCompileUnits();
674   EXPECT_EQ(NumCUs, 2u);
675   DWARFCompileUnit *U1 = DwarfContext->getCompileUnitAtIndex(0);
676   DWARFCompileUnit *U2 = DwarfContext->getCompileUnitAtIndex(1);
677 
678   // Get the compile unit DIE is valid.
679   auto Unit1DieDG = U1->getUnitDIE(false);
680   EXPECT_TRUE(Unit1DieDG.isValid());
681 
682   auto Unit2DieDG = U2->getUnitDIE(false);
683   EXPECT_TRUE(Unit2DieDG.isValid());
684 
685   // Verify the first child of the compile unit 1 DIE is our int base type.
686   auto CU1TypeDieDG = Unit1DieDG.getFirstChild();
687   EXPECT_TRUE(CU1TypeDieDG.isValid());
688   EXPECT_EQ(CU1TypeDieDG.getTag(), DW_TAG_base_type);
689   EXPECT_EQ(DW_ATE_signed, toUnsigned(CU1TypeDieDG.find(DW_AT_encoding), 0));
690 
691   // Verify the first child of the compile unit 2 DIE is our float base type.
692   auto CU2TypeDieDG = Unit2DieDG.getFirstChild();
693   EXPECT_TRUE(CU2TypeDieDG.isValid());
694   EXPECT_EQ(CU2TypeDieDG.getTag(), DW_TAG_base_type);
695   EXPECT_EQ(DW_ATE_float, toUnsigned(CU2TypeDieDG.find(DW_AT_encoding), 0));
696 
697   // Verify the sibling of the base type DIE is our Ref1 DIE and that its
698   // DW_AT_type points to our base type DIE.
699   auto CU1Ref1DieDG = CU1TypeDieDG.getSibling();
700   EXPECT_TRUE(CU1Ref1DieDG.isValid());
701   EXPECT_EQ(CU1Ref1DieDG.getTag(), DW_TAG_variable);
702   EXPECT_EQ(CU1TypeDieDG.getOffset(),
703             toReference(CU1Ref1DieDG.find(DW_AT_type), -1ULL));
704   // Verify the sibling is our Ref2 DIE and that its DW_AT_type points to our
705   // base type DIE in CU1.
706   auto CU1Ref2DieDG = CU1Ref1DieDG.getSibling();
707   EXPECT_TRUE(CU1Ref2DieDG.isValid());
708   EXPECT_EQ(CU1Ref2DieDG.getTag(), DW_TAG_variable);
709   EXPECT_EQ(CU1TypeDieDG.getOffset(),
710             toReference(CU1Ref2DieDG.find(DW_AT_type), -1ULL));
711 
712   // Verify the sibling is our Ref4 DIE and that its DW_AT_type points to our
713   // base type DIE in CU1.
714   auto CU1Ref4DieDG = CU1Ref2DieDG.getSibling();
715   EXPECT_TRUE(CU1Ref4DieDG.isValid());
716   EXPECT_EQ(CU1Ref4DieDG.getTag(), DW_TAG_variable);
717   EXPECT_EQ(CU1TypeDieDG.getOffset(),
718             toReference(CU1Ref4DieDG.find(DW_AT_type), -1ULL));
719 
720   // Verify the sibling is our Ref8 DIE and that its DW_AT_type points to our
721   // base type DIE in CU1.
722   auto CU1Ref8DieDG = CU1Ref4DieDG.getSibling();
723   EXPECT_TRUE(CU1Ref8DieDG.isValid());
724   EXPECT_EQ(CU1Ref8DieDG.getTag(), DW_TAG_variable);
725   EXPECT_EQ(CU1TypeDieDG.getOffset(),
726             toReference(CU1Ref8DieDG.find(DW_AT_type), -1ULL));
727 
728   // Verify the sibling is our RefAddr DIE and that its DW_AT_type points to our
729   // base type DIE in CU1.
730   auto CU1RefAddrDieDG = CU1Ref8DieDG.getSibling();
731   EXPECT_TRUE(CU1RefAddrDieDG.isValid());
732   EXPECT_EQ(CU1RefAddrDieDG.getTag(), DW_TAG_variable);
733   EXPECT_EQ(CU1TypeDieDG.getOffset(),
734             toReference(CU1RefAddrDieDG.find(DW_AT_type), -1ULL));
735 
736   // Verify the sibling of the Ref4 DIE is our RefAddr DIE and that its
737   // DW_AT_type points to our base type DIE.
738   auto CU1ToCU2RefAddrDieDG = CU1RefAddrDieDG.getSibling();
739   EXPECT_TRUE(CU1ToCU2RefAddrDieDG.isValid());
740   EXPECT_EQ(CU1ToCU2RefAddrDieDG.getTag(), DW_TAG_variable);
741   EXPECT_EQ(CU2TypeDieDG.getOffset(),
742             toReference(CU1ToCU2RefAddrDieDG.find(DW_AT_type), -1ULL));
743 
744   // Verify the sibling of the base type DIE is our Ref1 DIE and that its
745   // DW_AT_type points to our base type DIE.
746   auto CU2Ref1DieDG = CU2TypeDieDG.getSibling();
747   EXPECT_TRUE(CU2Ref1DieDG.isValid());
748   EXPECT_EQ(CU2Ref1DieDG.getTag(), DW_TAG_variable);
749   EXPECT_EQ(CU2TypeDieDG.getOffset(),
750             toReference(CU2Ref1DieDG.find(DW_AT_type), -1ULL));
751   // Verify the sibling is our Ref2 DIE and that its DW_AT_type points to our
752   // base type DIE in CU2.
753   auto CU2Ref2DieDG = CU2Ref1DieDG.getSibling();
754   EXPECT_TRUE(CU2Ref2DieDG.isValid());
755   EXPECT_EQ(CU2Ref2DieDG.getTag(), DW_TAG_variable);
756   EXPECT_EQ(CU2TypeDieDG.getOffset(),
757             toReference(CU2Ref2DieDG.find(DW_AT_type), -1ULL));
758 
759   // Verify the sibling is our Ref4 DIE and that its DW_AT_type points to our
760   // base type DIE in CU2.
761   auto CU2Ref4DieDG = CU2Ref2DieDG.getSibling();
762   EXPECT_TRUE(CU2Ref4DieDG.isValid());
763   EXPECT_EQ(CU2Ref4DieDG.getTag(), DW_TAG_variable);
764   EXPECT_EQ(CU2TypeDieDG.getOffset(),
765             toReference(CU2Ref4DieDG.find(DW_AT_type), -1ULL));
766 
767   // Verify the sibling is our Ref8 DIE and that its DW_AT_type points to our
768   // base type DIE in CU2.
769   auto CU2Ref8DieDG = CU2Ref4DieDG.getSibling();
770   EXPECT_TRUE(CU2Ref8DieDG.isValid());
771   EXPECT_EQ(CU2Ref8DieDG.getTag(), DW_TAG_variable);
772   EXPECT_EQ(CU2TypeDieDG.getOffset(),
773             toReference(CU2Ref8DieDG.find(DW_AT_type), -1ULL));
774 
775   // Verify the sibling is our RefAddr DIE and that its DW_AT_type points to our
776   // base type DIE in CU2.
777   auto CU2RefAddrDieDG = CU2Ref8DieDG.getSibling();
778   EXPECT_TRUE(CU2RefAddrDieDG.isValid());
779   EXPECT_EQ(CU2RefAddrDieDG.getTag(), DW_TAG_variable);
780   EXPECT_EQ(CU2TypeDieDG.getOffset(),
781             toReference(CU2RefAddrDieDG.find(DW_AT_type), -1ULL));
782 
783   // Verify the sibling of the Ref4 DIE is our RefAddr DIE and that its
784   // DW_AT_type points to our base type DIE.
785   auto CU2ToCU1RefAddrDieDG = CU2RefAddrDieDG.getSibling();
786   EXPECT_TRUE(CU2ToCU1RefAddrDieDG.isValid());
787   EXPECT_EQ(CU2ToCU1RefAddrDieDG.getTag(), DW_TAG_variable);
788   EXPECT_EQ(CU1TypeDieDG.getOffset(),
789             toReference(CU2ToCU1RefAddrDieDG.find(DW_AT_type), -1ULL));
790 }
791 
TEST(DWARFDebugInfo,TestDWARF32Version2Addr4References)792 TEST(DWARFDebugInfo, TestDWARF32Version2Addr4References) {
793   // Test that we can decode all forms for DWARF32, version 2, with 4 byte
794   // addresses.
795   typedef uint32_t AddrType;
796   TestReferences<2, AddrType>();
797 }
798 
TEST(DWARFDebugInfo,TestDWARF32Version2Addr8References)799 TEST(DWARFDebugInfo, TestDWARF32Version2Addr8References) {
800   // Test that we can decode all forms for DWARF32, version 2, with 8 byte
801   // addresses.
802   typedef uint64_t AddrType;
803   TestReferences<2, AddrType>();
804 }
805 
TEST(DWARFDebugInfo,TestDWARF32Version3Addr4References)806 TEST(DWARFDebugInfo, TestDWARF32Version3Addr4References) {
807   // Test that we can decode all forms for DWARF32, version 3, with 4 byte
808   // addresses.
809   typedef uint32_t AddrType;
810   TestReferences<3, AddrType>();
811 }
812 
TEST(DWARFDebugInfo,TestDWARF32Version3Addr8References)813 TEST(DWARFDebugInfo, TestDWARF32Version3Addr8References) {
814   // Test that we can decode all forms for DWARF32, version 3, with 8 byte
815   // addresses.
816   typedef uint64_t AddrType;
817   TestReferences<3, AddrType>();
818 }
819 
TEST(DWARFDebugInfo,TestDWARF32Version4Addr4References)820 TEST(DWARFDebugInfo, TestDWARF32Version4Addr4References) {
821   // Test that we can decode all forms for DWARF32, version 4, with 4 byte
822   // addresses.
823   typedef uint32_t AddrType;
824   TestReferences<4, AddrType>();
825 }
826 
TEST(DWARFDebugInfo,TestDWARF32Version4Addr8References)827 TEST(DWARFDebugInfo, TestDWARF32Version4Addr8References) {
828   // Test that we can decode all forms for DWARF32, version 4, with 8 byte
829   // addresses.
830   typedef uint64_t AddrType;
831   TestReferences<4, AddrType>();
832 }
833 
TestAddresses()834 template <uint16_t Version, class AddrType> void TestAddresses() {
835   Triple Triple = getHostTripleForAddrSize(sizeof(AddrType));
836   if (!isConfigurationSupported(Triple))
837     return;
838 
839   // Test the DWARF APIs related to accessing the DW_AT_low_pc and
840   // DW_AT_high_pc.
841   const bool SupportsHighPCAsOffset = Version >= 4;
842   auto ExpectedDG = dwarfgen::Generator::create(Triple, Version);
843   ASSERT_THAT_EXPECTED(ExpectedDG, Succeeded());
844   dwarfgen::Generator *DG = ExpectedDG.get().get();
845   dwarfgen::CompileUnit &CU = DG->addCompileUnit();
846   dwarfgen::DIE CUDie = CU.getUnitDIE();
847 
848   CUDie.addAttribute(DW_AT_name, DW_FORM_strp, "/tmp/main.c");
849   CUDie.addAttribute(DW_AT_language, DW_FORM_data2, DW_LANG_C);
850 
851   // Create a subprogram DIE with no low or high PC.
852   dwarfgen::DIE SubprogramNoPC = CUDie.addChild(DW_TAG_subprogram);
853   SubprogramNoPC.addAttribute(DW_AT_name, DW_FORM_strp, "no_pc");
854 
855   // Create a subprogram DIE with a low PC only.
856   dwarfgen::DIE SubprogramLowPC = CUDie.addChild(DW_TAG_subprogram);
857   SubprogramLowPC.addAttribute(DW_AT_name, DW_FORM_strp, "low_pc");
858   const uint64_t ActualLowPC = 0x1000;
859   const uint64_t ActualHighPC = 0x2000;
860   const uint64_t ActualHighPCOffset = ActualHighPC - ActualLowPC;
861   SubprogramLowPC.addAttribute(DW_AT_low_pc, DW_FORM_addr, ActualLowPC);
862 
863   // Create a subprogram DIE with a low and high PC.
864   dwarfgen::DIE SubprogramLowHighPC = CUDie.addChild(DW_TAG_subprogram);
865   SubprogramLowHighPC.addAttribute(DW_AT_name, DW_FORM_strp, "low_high_pc");
866   SubprogramLowHighPC.addAttribute(DW_AT_low_pc, DW_FORM_addr, ActualLowPC);
867   // Encode the high PC as an offset from the low PC if supported.
868   if (SupportsHighPCAsOffset)
869     SubprogramLowHighPC.addAttribute(DW_AT_high_pc, DW_FORM_data4,
870                                      ActualHighPCOffset);
871   else
872     SubprogramLowHighPC.addAttribute(DW_AT_high_pc, DW_FORM_addr, ActualHighPC);
873 
874   StringRef FileBytes = DG->generate();
875   MemoryBufferRef FileBuffer(FileBytes, "dwarf");
876   auto Obj = object::ObjectFile::createObjectFile(FileBuffer);
877   EXPECT_TRUE((bool)Obj);
878   std::unique_ptr<DWARFContext> DwarfContext = DWARFContext::create(**Obj);
879 
880   // Verify the number of compile units is correct.
881   uint32_t NumCUs = DwarfContext->getNumCompileUnits();
882   EXPECT_EQ(NumCUs, 1u);
883   DWARFCompileUnit *U = DwarfContext->getCompileUnitAtIndex(0);
884 
885   // Get the compile unit DIE is valid.
886   auto DieDG = U->getUnitDIE(false);
887   EXPECT_TRUE(DieDG.isValid());
888 
889   uint64_t LowPC, HighPC, SectionIndex;
890   Optional<uint64_t> OptU64;
891   // Verify the that our subprogram with no PC value fails appropriately when
892   // asked for any PC values.
893   auto SubprogramDieNoPC = DieDG.getFirstChild();
894   EXPECT_TRUE(SubprogramDieNoPC.isValid());
895   EXPECT_EQ(SubprogramDieNoPC.getTag(), DW_TAG_subprogram);
896   OptU64 = toAddress(SubprogramDieNoPC.find(DW_AT_low_pc));
897   EXPECT_FALSE((bool)OptU64);
898   OptU64 = toAddress(SubprogramDieNoPC.find(DW_AT_high_pc));
899   EXPECT_FALSE((bool)OptU64);
900   EXPECT_FALSE(SubprogramDieNoPC.getLowAndHighPC(LowPC, HighPC, SectionIndex));
901   OptU64 = toAddress(SubprogramDieNoPC.find(DW_AT_high_pc));
902   EXPECT_FALSE((bool)OptU64);
903   OptU64 = toUnsigned(SubprogramDieNoPC.find(DW_AT_high_pc));
904   EXPECT_FALSE((bool)OptU64);
905   OptU64 = SubprogramDieNoPC.getHighPC(ActualLowPC);
906   EXPECT_FALSE((bool)OptU64);
907   EXPECT_FALSE(SubprogramDieNoPC.getLowAndHighPC(LowPC, HighPC, SectionIndex));
908 
909   // Verify the that our subprogram with only a low PC value succeeds when
910   // we ask for the Low PC, but fails appropriately when asked for the high PC
911   // or both low and high PC values.
912   auto SubprogramDieLowPC = SubprogramDieNoPC.getSibling();
913   EXPECT_TRUE(SubprogramDieLowPC.isValid());
914   EXPECT_EQ(SubprogramDieLowPC.getTag(), DW_TAG_subprogram);
915   OptU64 = toAddress(SubprogramDieLowPC.find(DW_AT_low_pc));
916   EXPECT_TRUE((bool)OptU64);
917   EXPECT_EQ(OptU64.getValue(), ActualLowPC);
918   OptU64 = toAddress(SubprogramDieLowPC.find(DW_AT_high_pc));
919   EXPECT_FALSE((bool)OptU64);
920   OptU64 = toUnsigned(SubprogramDieLowPC.find(DW_AT_high_pc));
921   EXPECT_FALSE((bool)OptU64);
922   OptU64 = SubprogramDieLowPC.getHighPC(ActualLowPC);
923   EXPECT_FALSE((bool)OptU64);
924   EXPECT_FALSE(SubprogramDieLowPC.getLowAndHighPC(LowPC, HighPC, SectionIndex));
925 
926   // Verify the that our subprogram with only a low PC value succeeds when
927   // we ask for the Low PC, but fails appropriately when asked for the high PC
928   // or both low and high PC values.
929   auto SubprogramDieLowHighPC = SubprogramDieLowPC.getSibling();
930   EXPECT_TRUE(SubprogramDieLowHighPC.isValid());
931   EXPECT_EQ(SubprogramDieLowHighPC.getTag(), DW_TAG_subprogram);
932   OptU64 = toAddress(SubprogramDieLowHighPC.find(DW_AT_low_pc));
933   EXPECT_TRUE((bool)OptU64);
934   EXPECT_EQ(OptU64.getValue(), ActualLowPC);
935   // Get the high PC as an address. This should succeed if the high PC was
936   // encoded as an address and fail if the high PC was encoded as an offset.
937   OptU64 = toAddress(SubprogramDieLowHighPC.find(DW_AT_high_pc));
938   if (SupportsHighPCAsOffset) {
939     EXPECT_FALSE((bool)OptU64);
940   } else {
941     EXPECT_TRUE((bool)OptU64);
942     EXPECT_EQ(OptU64.getValue(), ActualHighPC);
943   }
944   // Get the high PC as an unsigned constant. This should succeed if the high PC
945   // was encoded as an offset and fail if the high PC was encoded as an address.
946   OptU64 = toUnsigned(SubprogramDieLowHighPC.find(DW_AT_high_pc));
947   if (SupportsHighPCAsOffset) {
948     EXPECT_TRUE((bool)OptU64);
949     EXPECT_EQ(OptU64.getValue(), ActualHighPCOffset);
950   } else {
951     EXPECT_FALSE((bool)OptU64);
952   }
953 
954   OptU64 = SubprogramDieLowHighPC.getHighPC(ActualLowPC);
955   EXPECT_TRUE((bool)OptU64);
956   EXPECT_EQ(OptU64.getValue(), ActualHighPC);
957 
958   EXPECT_TRUE(SubprogramDieLowHighPC.getLowAndHighPC(LowPC, HighPC, SectionIndex));
959   EXPECT_EQ(LowPC, ActualLowPC);
960   EXPECT_EQ(HighPC, ActualHighPC);
961 }
962 
TEST(DWARFDebugInfo,TestDWARF32Version2Addr4Addresses)963 TEST(DWARFDebugInfo, TestDWARF32Version2Addr4Addresses) {
964   // Test that we can decode address values in DWARF32, version 2, with 4 byte
965   // addresses.
966   typedef uint32_t AddrType;
967   TestAddresses<2, AddrType>();
968 }
969 
TEST(DWARFDebugInfo,TestDWARF32Version2Addr8Addresses)970 TEST(DWARFDebugInfo, TestDWARF32Version2Addr8Addresses) {
971   // Test that we can decode address values in DWARF32, version 2, with 8 byte
972   // addresses.
973   typedef uint64_t AddrType;
974   TestAddresses<2, AddrType>();
975 }
976 
TEST(DWARFDebugInfo,TestDWARF32Version3Addr4Addresses)977 TEST(DWARFDebugInfo, TestDWARF32Version3Addr4Addresses) {
978   // Test that we can decode address values in DWARF32, version 3, with 4 byte
979   // addresses.
980   typedef uint32_t AddrType;
981   TestAddresses<3, AddrType>();
982 }
983 
TEST(DWARFDebugInfo,TestDWARF32Version3Addr8Addresses)984 TEST(DWARFDebugInfo, TestDWARF32Version3Addr8Addresses) {
985   // Test that we can decode address values in DWARF32, version 3, with 8 byte
986   // addresses.
987   typedef uint64_t AddrType;
988   TestAddresses<3, AddrType>();
989 }
990 
TEST(DWARFDebugInfo,TestDWARF32Version4Addr4Addresses)991 TEST(DWARFDebugInfo, TestDWARF32Version4Addr4Addresses) {
992   // Test that we can decode address values in DWARF32, version 4, with 4 byte
993   // addresses.
994   typedef uint32_t AddrType;
995   TestAddresses<4, AddrType>();
996 }
997 
TEST(DWARFDebugInfo,TestDWARF32Version4Addr8Addresses)998 TEST(DWARFDebugInfo, TestDWARF32Version4Addr8Addresses) {
999   // Test that we can decode address values in DWARF32, version 4, with 8 byte
1000   // addresses.
1001   typedef uint64_t AddrType;
1002   TestAddresses<4, AddrType>();
1003 }
1004 
TEST(DWARFDebugInfo,TestRelations)1005 TEST(DWARFDebugInfo, TestRelations) {
1006   Triple Triple = getHostTripleForAddrSize(sizeof(void *));
1007   if (!isConfigurationSupported(Triple))
1008     return;
1009 
1010   // Test the DWARF APIs related to accessing the DW_AT_low_pc and
1011   // DW_AT_high_pc.
1012   uint16_t Version = 4;
1013   auto ExpectedDG = dwarfgen::Generator::create(Triple, Version);
1014   ASSERT_THAT_EXPECTED(ExpectedDG, Succeeded());
1015   dwarfgen::Generator *DG = ExpectedDG.get().get();
1016   dwarfgen::CompileUnit &CU = DG->addCompileUnit();
1017 
1018   enum class Tag: uint16_t  {
1019     A = dwarf::DW_TAG_lo_user,
1020     B,
1021     C,
1022     C1,
1023     C2,
1024     D,
1025     D1
1026   };
1027 
1028   // Scope to allow us to re-use the same DIE names
1029   {
1030     // Create DWARF tree that looks like:
1031     //
1032     // CU
1033     //   A
1034     //     B
1035     //     C
1036     //       C1
1037     //       C2
1038     //     D
1039     //       D1
1040     dwarfgen::DIE CUDie = CU.getUnitDIE();
1041     dwarfgen::DIE A = CUDie.addChild((dwarf::Tag)Tag::A);
1042     A.addChild((dwarf::Tag)Tag::B);
1043     dwarfgen::DIE C = A.addChild((dwarf::Tag)Tag::C);
1044     dwarfgen::DIE D = A.addChild((dwarf::Tag)Tag::D);
1045     C.addChild((dwarf::Tag)Tag::C1);
1046     C.addChild((dwarf::Tag)Tag::C2);
1047     D.addChild((dwarf::Tag)Tag::D1);
1048   }
1049 
1050   MemoryBufferRef FileBuffer(DG->generate(), "dwarf");
1051   auto Obj = object::ObjectFile::createObjectFile(FileBuffer);
1052   EXPECT_TRUE((bool)Obj);
1053   std::unique_ptr<DWARFContext> DwarfContext = DWARFContext::create(**Obj);
1054 
1055   // Verify the number of compile units is correct.
1056   uint32_t NumCUs = DwarfContext->getNumCompileUnits();
1057   EXPECT_EQ(NumCUs, 1u);
1058   DWARFCompileUnit *U = DwarfContext->getCompileUnitAtIndex(0);
1059 
1060   // Get the compile unit DIE is valid.
1061   auto CUDie = U->getUnitDIE(false);
1062   EXPECT_TRUE(CUDie.isValid());
1063 
1064   // The compile unit doesn't have a parent or a sibling.
1065   auto ParentDie = CUDie.getParent();
1066   EXPECT_FALSE(ParentDie.isValid());
1067   auto SiblingDie = CUDie.getSibling();
1068   EXPECT_FALSE(SiblingDie.isValid());
1069 
1070   // Get the children of the compile unit
1071   auto A = CUDie.getFirstChild();
1072   auto B = A.getFirstChild();
1073   auto C = B.getSibling();
1074   auto D = C.getSibling();
1075   auto Null = D.getSibling();
1076 
1077   // Verify NULL Die is NULL and has no children or siblings
1078   EXPECT_TRUE(Null.isNULL());
1079   EXPECT_FALSE(Null.getSibling().isValid());
1080   EXPECT_FALSE(Null.getFirstChild().isValid());
1081 
1082   // Verify all children of the compile unit DIE are correct.
1083   EXPECT_EQ(A.getTag(), (dwarf::Tag)Tag::A);
1084   EXPECT_EQ(B.getTag(), (dwarf::Tag)Tag::B);
1085   EXPECT_EQ(C.getTag(), (dwarf::Tag)Tag::C);
1086   EXPECT_EQ(D.getTag(), (dwarf::Tag)Tag::D);
1087 
1088   // Verify who has children
1089   EXPECT_TRUE(A.hasChildren());
1090   EXPECT_FALSE(B.hasChildren());
1091   EXPECT_TRUE(C.hasChildren());
1092   EXPECT_TRUE(D.hasChildren());
1093 
1094   // Make sure the parent of all the children of the compile unit are the
1095   // compile unit.
1096   EXPECT_EQ(A.getParent(), CUDie);
1097 
1098   // Make sure the parent of all the children of A are the A.
1099   // B is the first child in A, so we need to verify we can get the previous
1100   // DIE as the parent.
1101   EXPECT_EQ(B.getParent(), A);
1102   // C is the second child in A, so we need to make sure we can backup across
1103   // other DIE (B) at the same level to get the correct parent.
1104   EXPECT_EQ(C.getParent(), A);
1105   // D is the third child of A. We need to verify we can backup across other DIE
1106   // (B and C) including DIE that have children (D) to get the correct parent.
1107   EXPECT_EQ(D.getParent(), A);
1108 
1109   // Verify that a DIE with no children returns an invalid DWARFDie.
1110   EXPECT_FALSE(B.getFirstChild().isValid());
1111 
1112   // Verify the children of the B DIE
1113   auto C1 = C.getFirstChild();
1114   auto C2 = C1.getSibling();
1115   EXPECT_TRUE(C2.getSibling().isNULL());
1116 
1117   // Verify all children of the B DIE correctly valid or invalid.
1118   EXPECT_EQ(C1.getTag(), (dwarf::Tag)Tag::C1);
1119   EXPECT_EQ(C2.getTag(), (dwarf::Tag)Tag::C2);
1120 
1121   // Make sure the parent of all the children of the B are the B.
1122   EXPECT_EQ(C1.getParent(), C);
1123   EXPECT_EQ(C2.getParent(), C);
1124 
1125   // Make sure iterators work as expected.
1126   EXPECT_THAT(std::vector<DWARFDie>(A.begin(), A.end()),
1127               testing::ElementsAre(B, C, D));
1128   EXPECT_THAT(std::vector<DWARFDie>(A.rbegin(), A.rend()),
1129               testing::ElementsAre(D, C, B));
1130 
1131   // Make sure iterator is bidirectional.
1132   {
1133     auto Begin = A.begin();
1134     auto End = A.end();
1135     auto It = A.begin();
1136 
1137     EXPECT_EQ(It, Begin);
1138     EXPECT_EQ(*It, B);
1139     ++It;
1140     EXPECT_EQ(*It, C);
1141     ++It;
1142     EXPECT_EQ(*It, D);
1143     ++It;
1144     EXPECT_EQ(It, End);
1145     --It;
1146     EXPECT_EQ(*It, D);
1147     --It;
1148     EXPECT_EQ(*It, C);
1149     --It;
1150     EXPECT_EQ(*It, B);
1151     EXPECT_EQ(It, Begin);
1152   }
1153 
1154   // Make sure reverse iterator is bidirectional.
1155   {
1156     auto Begin = A.rbegin();
1157     auto End = A.rend();
1158     auto It = A.rbegin();
1159 
1160     EXPECT_EQ(It, Begin);
1161     EXPECT_EQ(*It, D);
1162     ++It;
1163     EXPECT_EQ(*It, C);
1164     ++It;
1165     EXPECT_EQ(*It, B);
1166     ++It;
1167     EXPECT_EQ(It, End);
1168     --It;
1169     EXPECT_EQ(*It, B);
1170     --It;
1171     EXPECT_EQ(*It, C);
1172     --It;
1173     EXPECT_EQ(*It, D);
1174     EXPECT_EQ(It, Begin);
1175   }
1176 }
1177 
TEST(DWARFDebugInfo,TestDWARFDie)1178 TEST(DWARFDebugInfo, TestDWARFDie) {
1179   // Make sure a default constructed DWARFDie doesn't have any parent, sibling
1180   // or child;
1181   DWARFDie DefaultDie;
1182   EXPECT_FALSE(DefaultDie.getParent().isValid());
1183   EXPECT_FALSE(DefaultDie.getFirstChild().isValid());
1184   EXPECT_FALSE(DefaultDie.getSibling().isValid());
1185 }
1186 
TEST(DWARFDebugInfo,TestChildIterators)1187 TEST(DWARFDebugInfo, TestChildIterators) {
1188   Triple Triple = getHostTripleForAddrSize(sizeof(void *));
1189   if (!isConfigurationSupported(Triple))
1190     return;
1191 
1192   // Test the DWARF APIs related to iterating across the children of a DIE using
1193   // the DWARFDie::iterator class.
1194   uint16_t Version = 4;
1195   auto ExpectedDG = dwarfgen::Generator::create(Triple, Version);
1196   ASSERT_THAT_EXPECTED(ExpectedDG, Succeeded());
1197   dwarfgen::Generator *DG = ExpectedDG.get().get();
1198   dwarfgen::CompileUnit &CU = DG->addCompileUnit();
1199 
1200   enum class Tag: uint16_t  {
1201     A = dwarf::DW_TAG_lo_user,
1202     B,
1203   };
1204 
1205   // Scope to allow us to re-use the same DIE names
1206   {
1207     // Create DWARF tree that looks like:
1208     //
1209     // CU
1210     //   A
1211     //   B
1212     auto CUDie = CU.getUnitDIE();
1213     CUDie.addChild((dwarf::Tag)Tag::A);
1214     CUDie.addChild((dwarf::Tag)Tag::B);
1215   }
1216 
1217   MemoryBufferRef FileBuffer(DG->generate(), "dwarf");
1218   auto Obj = object::ObjectFile::createObjectFile(FileBuffer);
1219   EXPECT_TRUE((bool)Obj);
1220   std::unique_ptr<DWARFContext> DwarfContext = DWARFContext::create(**Obj);
1221 
1222   // Verify the number of compile units is correct.
1223   uint32_t NumCUs = DwarfContext->getNumCompileUnits();
1224   EXPECT_EQ(NumCUs, 1u);
1225   DWARFCompileUnit *U = DwarfContext->getCompileUnitAtIndex(0);
1226 
1227   // Get the compile unit DIE is valid.
1228   auto CUDie = U->getUnitDIE(false);
1229   EXPECT_TRUE(CUDie.isValid());
1230   uint32_t Index;
1231   DWARFDie A;
1232   DWARFDie B;
1233 
1234   // Verify the compile unit DIE's children.
1235   Index = 0;
1236   for (auto Die : CUDie.children()) {
1237     switch (Index++) {
1238       case 0: A = Die; break;
1239       case 1: B = Die; break;
1240     }
1241   }
1242 
1243   EXPECT_EQ(A.getTag(), (dwarf::Tag)Tag::A);
1244   EXPECT_EQ(B.getTag(), (dwarf::Tag)Tag::B);
1245 
1246   // Verify that A has no children by verifying that the begin and end contain
1247   // invalid DIEs and also that the iterators are equal.
1248   EXPECT_EQ(A.begin(), A.end());
1249 }
1250 
TEST(DWARFDebugInfo,TestChildIteratorsOnInvalidDie)1251 TEST(DWARFDebugInfo, TestChildIteratorsOnInvalidDie) {
1252   // Verify that an invalid DIE has no children.
1253   DWARFDie Invalid;
1254   auto begin = Invalid.begin();
1255   auto end = Invalid.end();
1256   EXPECT_FALSE(begin->isValid());
1257   EXPECT_FALSE(end->isValid());
1258   EXPECT_EQ(begin, end);
1259 }
1260 
TEST(DWARFDebugInfo,TestEmptyChildren)1261 TEST(DWARFDebugInfo, TestEmptyChildren) {
1262   const char *yamldata = "debug_abbrev:\n"
1263                          "  - Code:            0x00000001\n"
1264                          "    Tag:             DW_TAG_compile_unit\n"
1265                          "    Children:        DW_CHILDREN_yes\n"
1266                          "    Attributes:\n"
1267                          "debug_info:\n"
1268                          "  - Length:\n"
1269                          "      TotalLength:          0\n"
1270                          "    Version:         4\n"
1271                          "    AbbrOffset:      0\n"
1272                          "    AddrSize:        8\n"
1273                          "    Entries:\n"
1274                          "      - AbbrCode:        0x00000001\n"
1275                          "        Values:\n"
1276                          "      - AbbrCode:        0x00000000\n"
1277                          "        Values:\n";
1278 
1279   auto ErrOrSections = DWARFYAML::EmitDebugSections(StringRef(yamldata), true);
1280   ASSERT_TRUE((bool)ErrOrSections);
1281   std::unique_ptr<DWARFContext> DwarfContext =
1282       DWARFContext::create(*ErrOrSections, 8);
1283 
1284   // Verify the number of compile units is correct.
1285   uint32_t NumCUs = DwarfContext->getNumCompileUnits();
1286   EXPECT_EQ(NumCUs, 1u);
1287   DWARFCompileUnit *U = DwarfContext->getCompileUnitAtIndex(0);
1288 
1289   // Get the compile unit DIE is valid.
1290   auto CUDie = U->getUnitDIE(false);
1291   EXPECT_TRUE(CUDie.isValid());
1292 
1293   // Verify that the CU Die that says it has children, but doesn't, actually
1294   // has begin and end iterators that are equal. We want to make sure we don't
1295   // see the Null DIEs during iteration.
1296   EXPECT_EQ(CUDie.begin(), CUDie.end());
1297 }
1298 
TEST(DWARFDebugInfo,TestAttributeIterators)1299 TEST(DWARFDebugInfo, TestAttributeIterators) {
1300   Triple Triple = getHostTripleForAddrSize(sizeof(void *));
1301   if (!isConfigurationSupported(Triple))
1302     return;
1303 
1304   // Test the DWARF APIs related to iterating across all attribute values in a
1305   // a DWARFDie.
1306   uint16_t Version = 4;
1307   auto ExpectedDG = dwarfgen::Generator::create(Triple, Version);
1308   ASSERT_THAT_EXPECTED(ExpectedDG, Succeeded());
1309   dwarfgen::Generator *DG = ExpectedDG.get().get();
1310   dwarfgen::CompileUnit &CU = DG->addCompileUnit();
1311   const uint64_t CULowPC = 0x1000;
1312   StringRef CUPath("/tmp/main.c");
1313 
1314   // Scope to allow us to re-use the same DIE names
1315   {
1316     auto CUDie = CU.getUnitDIE();
1317     // Encode an attribute value before an attribute with no data.
1318     CUDie.addAttribute(DW_AT_name, DW_FORM_strp, CUPath.data());
1319     // Encode an attribute value with no data in .debug_info/types to ensure
1320     // the iteration works correctly.
1321     CUDie.addAttribute(DW_AT_declaration, DW_FORM_flag_present);
1322     // Encode an attribute value after an attribute with no data.
1323     CUDie.addAttribute(DW_AT_low_pc, DW_FORM_addr, CULowPC);
1324   }
1325 
1326   MemoryBufferRef FileBuffer(DG->generate(), "dwarf");
1327   auto Obj = object::ObjectFile::createObjectFile(FileBuffer);
1328   EXPECT_TRUE((bool)Obj);
1329   std::unique_ptr<DWARFContext> DwarfContext = DWARFContext::create(**Obj);
1330 
1331   // Verify the number of compile units is correct.
1332   uint32_t NumCUs = DwarfContext->getNumCompileUnits();
1333   EXPECT_EQ(NumCUs, 1u);
1334   DWARFCompileUnit *U = DwarfContext->getCompileUnitAtIndex(0);
1335 
1336   // Get the compile unit DIE is valid.
1337   auto CUDie = U->getUnitDIE(false);
1338   EXPECT_TRUE(CUDie.isValid());
1339 
1340   auto R = CUDie.attributes();
1341   auto I = R.begin();
1342   auto E = R.end();
1343 
1344   ASSERT_NE(E, I);
1345   EXPECT_EQ(I->Attr, DW_AT_name);
1346   auto ActualCUPath = I->Value.getAsCString();
1347   EXPECT_EQ(CUPath, *ActualCUPath);
1348 
1349   ASSERT_NE(E, ++I);
1350   EXPECT_EQ(I->Attr, DW_AT_declaration);
1351   EXPECT_EQ(1ull, *I->Value.getAsUnsignedConstant());
1352 
1353   ASSERT_NE(E, ++I);
1354   EXPECT_EQ(I->Attr, DW_AT_low_pc);
1355   EXPECT_EQ(CULowPC, *I->Value.getAsAddress());
1356 
1357   EXPECT_EQ(E, ++I);
1358 }
1359 
TEST(DWARFDebugInfo,TestFindRecurse)1360 TEST(DWARFDebugInfo, TestFindRecurse) {
1361   Triple Triple = getHostTripleForAddrSize(sizeof(void *));
1362   if (!isConfigurationSupported(Triple))
1363     return;
1364 
1365   uint16_t Version = 4;
1366   auto ExpectedDG = dwarfgen::Generator::create(Triple, Version);
1367   ASSERT_THAT_EXPECTED(ExpectedDG, Succeeded());
1368   dwarfgen::Generator *DG = ExpectedDG.get().get();
1369   dwarfgen::CompileUnit &CU = DG->addCompileUnit();
1370 
1371   StringRef SpecDieName = "spec";
1372   StringRef SpecLinkageName = "spec_linkage";
1373   StringRef AbsDieName = "abs";
1374   // Scope to allow us to re-use the same DIE names
1375   {
1376     auto CUDie = CU.getUnitDIE();
1377     auto FuncSpecDie = CUDie.addChild(DW_TAG_subprogram);
1378     auto FuncAbsDie = CUDie.addChild(DW_TAG_subprogram);
1379     // Put the linkage name in a second abstract origin DIE to ensure we
1380     // recurse through more than just one DIE when looking for attributes.
1381     auto FuncAbsDie2 = CUDie.addChild(DW_TAG_subprogram);
1382     auto FuncDie = CUDie.addChild(DW_TAG_subprogram);
1383     auto VarAbsDie = CUDie.addChild(DW_TAG_variable);
1384     auto VarDie = CUDie.addChild(DW_TAG_variable);
1385     FuncSpecDie.addAttribute(DW_AT_name, DW_FORM_strp, SpecDieName);
1386     FuncAbsDie2.addAttribute(DW_AT_linkage_name, DW_FORM_strp, SpecLinkageName);
1387     FuncAbsDie.addAttribute(DW_AT_specification, DW_FORM_ref4, FuncSpecDie);
1388     FuncAbsDie.addAttribute(DW_AT_abstract_origin, DW_FORM_ref4, FuncAbsDie2);
1389     FuncDie.addAttribute(DW_AT_abstract_origin, DW_FORM_ref4, FuncAbsDie);
1390     VarAbsDie.addAttribute(DW_AT_name, DW_FORM_strp, AbsDieName);
1391     VarDie.addAttribute(DW_AT_abstract_origin, DW_FORM_ref4, VarAbsDie);
1392   }
1393 
1394   MemoryBufferRef FileBuffer(DG->generate(), "dwarf");
1395   auto Obj = object::ObjectFile::createObjectFile(FileBuffer);
1396   EXPECT_TRUE((bool)Obj);
1397   std::unique_ptr<DWARFContext> DwarfContext = DWARFContext::create(**Obj);
1398 
1399   // Verify the number of compile units is correct.
1400   uint32_t NumCUs = DwarfContext->getNumCompileUnits();
1401   EXPECT_EQ(NumCUs, 1u);
1402   DWARFCompileUnit *U = DwarfContext->getCompileUnitAtIndex(0);
1403 
1404   // Get the compile unit DIE is valid.
1405   auto CUDie = U->getUnitDIE(false);
1406   EXPECT_TRUE(CUDie.isValid());
1407 
1408   auto FuncSpecDie = CUDie.getFirstChild();
1409   auto FuncAbsDie = FuncSpecDie.getSibling();
1410   auto FuncAbsDie2 = FuncAbsDie.getSibling();
1411   auto FuncDie = FuncAbsDie2.getSibling();
1412   auto VarAbsDie = FuncDie.getSibling();
1413   auto VarDie = VarAbsDie.getSibling();
1414 
1415   // Make sure we can't extract the name from the specification die when using
1416   // DWARFDie::find() since it won't check the DW_AT_specification DIE.
1417   EXPECT_FALSE(FuncDie.find(DW_AT_name));
1418 
1419   // Make sure we can extract the name from the specification die when using
1420   // DWARFDie::findRecursively() since it should recurse through the
1421   // DW_AT_specification DIE.
1422   auto NameOpt = FuncDie.findRecursively(DW_AT_name);
1423   EXPECT_TRUE(NameOpt);
1424   // Test the dwarf::toString() helper function.
1425   auto StringOpt = toString(NameOpt);
1426   EXPECT_TRUE(StringOpt);
1427   EXPECT_EQ(SpecDieName, StringOpt.getValueOr(nullptr));
1428   // Test the dwarf::toString() helper function with a default value specified.
1429   EXPECT_EQ(SpecDieName, toString(NameOpt, nullptr));
1430 
1431   auto LinkageNameOpt = FuncDie.findRecursively(DW_AT_linkage_name);
1432   EXPECT_EQ(SpecLinkageName, toString(LinkageNameOpt).getValueOr(nullptr));
1433 
1434   // Make sure we can't extract the name from the abstract origin die when using
1435   // DWARFDie::find() since it won't check the DW_AT_abstract_origin DIE.
1436   EXPECT_FALSE(VarDie.find(DW_AT_name));
1437 
1438   // Make sure we can extract the name from the abstract origin die when using
1439   // DWARFDie::findRecursively() since it should recurse through the
1440   // DW_AT_abstract_origin DIE.
1441   NameOpt = VarDie.findRecursively(DW_AT_name);
1442   EXPECT_TRUE(NameOpt);
1443   // Test the dwarf::toString() helper function.
1444   StringOpt = toString(NameOpt);
1445   EXPECT_TRUE(StringOpt);
1446   EXPECT_EQ(AbsDieName, StringOpt.getValueOr(nullptr));
1447 }
1448 
TEST(DWARFDebugInfo,TestDwarfToFunctions)1449 TEST(DWARFDebugInfo, TestDwarfToFunctions) {
1450   // Test all of the dwarf::toXXX functions that take a
1451   // Optional<DWARFFormValue> and extract the values from it.
1452   DWARFFormValue FormVal;
1453   uint64_t InvalidU64 = 0xBADBADBADBADBADB;
1454   int64_t InvalidS64 = 0xBADBADBADBADBADB;
1455   // First test that we don't get valid values back when using an optional with
1456   // no value.
1457   Optional<DWARFFormValue> FormValOpt;
1458   EXPECT_FALSE(toString(FormValOpt).hasValue());
1459   EXPECT_FALSE(toUnsigned(FormValOpt).hasValue());
1460   EXPECT_FALSE(toReference(FormValOpt).hasValue());
1461   EXPECT_FALSE(toSigned(FormValOpt).hasValue());
1462   EXPECT_FALSE(toAddress(FormValOpt).hasValue());
1463   EXPECT_FALSE(toSectionOffset(FormValOpt).hasValue());
1464   EXPECT_FALSE(toBlock(FormValOpt).hasValue());
1465   EXPECT_EQ(nullptr, toString(FormValOpt, nullptr));
1466   EXPECT_EQ(InvalidU64, toUnsigned(FormValOpt, InvalidU64));
1467   EXPECT_EQ(InvalidU64, toReference(FormValOpt, InvalidU64));
1468   EXPECT_EQ(InvalidU64, toAddress(FormValOpt, InvalidU64));
1469   EXPECT_EQ(InvalidU64, toSectionOffset(FormValOpt, InvalidU64));
1470   EXPECT_EQ(InvalidS64, toSigned(FormValOpt, InvalidS64));
1471 
1472   // Test successful and unsuccessful address decoding.
1473   uint64_t Address = 0x100000000ULL;
1474   FormVal.setForm(DW_FORM_addr);
1475   FormVal.setUValue(Address);
1476   FormValOpt = FormVal;
1477 
1478   EXPECT_FALSE(toString(FormValOpt).hasValue());
1479   EXPECT_FALSE(toUnsigned(FormValOpt).hasValue());
1480   EXPECT_FALSE(toReference(FormValOpt).hasValue());
1481   EXPECT_FALSE(toSigned(FormValOpt).hasValue());
1482   EXPECT_TRUE(toAddress(FormValOpt).hasValue());
1483   EXPECT_FALSE(toSectionOffset(FormValOpt).hasValue());
1484   EXPECT_FALSE(toBlock(FormValOpt).hasValue());
1485   EXPECT_EQ(nullptr, toString(FormValOpt, nullptr));
1486   EXPECT_EQ(InvalidU64, toUnsigned(FormValOpt, InvalidU64));
1487   EXPECT_EQ(InvalidU64, toReference(FormValOpt, InvalidU64));
1488   EXPECT_EQ(Address, toAddress(FormValOpt, InvalidU64));
1489   EXPECT_EQ(InvalidU64, toSectionOffset(FormValOpt, InvalidU64));
1490   EXPECT_EQ(InvalidS64, toSigned(FormValOpt, InvalidU64));
1491 
1492   // Test successful and unsuccessful unsigned constant decoding.
1493   uint64_t UData8 = 0x1020304050607080ULL;
1494   FormVal.setForm(DW_FORM_udata);
1495   FormVal.setUValue(UData8);
1496   FormValOpt = FormVal;
1497 
1498   EXPECT_FALSE(toString(FormValOpt).hasValue());
1499   EXPECT_TRUE(toUnsigned(FormValOpt).hasValue());
1500   EXPECT_FALSE(toReference(FormValOpt).hasValue());
1501   EXPECT_TRUE(toSigned(FormValOpt).hasValue());
1502   EXPECT_FALSE(toAddress(FormValOpt).hasValue());
1503   EXPECT_FALSE(toSectionOffset(FormValOpt).hasValue());
1504   EXPECT_FALSE(toBlock(FormValOpt).hasValue());
1505   EXPECT_EQ(nullptr, toString(FormValOpt, nullptr));
1506   EXPECT_EQ(UData8, toUnsigned(FormValOpt, InvalidU64));
1507   EXPECT_EQ(InvalidU64, toReference(FormValOpt, InvalidU64));
1508   EXPECT_EQ(InvalidU64, toAddress(FormValOpt, InvalidU64));
1509   EXPECT_EQ(InvalidU64, toSectionOffset(FormValOpt, InvalidU64));
1510   EXPECT_EQ((int64_t)UData8, toSigned(FormValOpt, InvalidU64));
1511 
1512   // Test successful and unsuccessful reference decoding.
1513   uint32_t RefData = 0x11223344U;
1514   FormVal.setForm(DW_FORM_ref_addr);
1515   FormVal.setUValue(RefData);
1516   FormValOpt = FormVal;
1517 
1518   EXPECT_FALSE(toString(FormValOpt).hasValue());
1519   EXPECT_FALSE(toUnsigned(FormValOpt).hasValue());
1520   EXPECT_TRUE(toReference(FormValOpt).hasValue());
1521   EXPECT_FALSE(toSigned(FormValOpt).hasValue());
1522   EXPECT_FALSE(toAddress(FormValOpt).hasValue());
1523   EXPECT_FALSE(toSectionOffset(FormValOpt).hasValue());
1524   EXPECT_FALSE(toBlock(FormValOpt).hasValue());
1525   EXPECT_EQ(nullptr, toString(FormValOpt, nullptr));
1526   EXPECT_EQ(InvalidU64, toUnsigned(FormValOpt, InvalidU64));
1527   EXPECT_EQ(RefData, toReference(FormValOpt, InvalidU64));
1528   EXPECT_EQ(InvalidU64, toAddress(FormValOpt, InvalidU64));
1529   EXPECT_EQ(InvalidU64, toSectionOffset(FormValOpt, InvalidU64));
1530   EXPECT_EQ(InvalidS64, toSigned(FormValOpt, InvalidU64));
1531 
1532   // Test successful and unsuccessful signed constant decoding.
1533   int64_t SData8 = 0x1020304050607080ULL;
1534   FormVal.setForm(DW_FORM_udata);
1535   FormVal.setSValue(SData8);
1536   FormValOpt = FormVal;
1537 
1538   EXPECT_FALSE(toString(FormValOpt).hasValue());
1539   EXPECT_TRUE(toUnsigned(FormValOpt).hasValue());
1540   EXPECT_FALSE(toReference(FormValOpt).hasValue());
1541   EXPECT_TRUE(toSigned(FormValOpt).hasValue());
1542   EXPECT_FALSE(toAddress(FormValOpt).hasValue());
1543   EXPECT_FALSE(toSectionOffset(FormValOpt).hasValue());
1544   EXPECT_FALSE(toBlock(FormValOpt).hasValue());
1545   EXPECT_EQ(nullptr, toString(FormValOpt, nullptr));
1546   EXPECT_EQ((uint64_t)SData8, toUnsigned(FormValOpt, InvalidU64));
1547   EXPECT_EQ(InvalidU64, toReference(FormValOpt, InvalidU64));
1548   EXPECT_EQ(InvalidU64, toAddress(FormValOpt, InvalidU64));
1549   EXPECT_EQ(InvalidU64, toSectionOffset(FormValOpt, InvalidU64));
1550   EXPECT_EQ(SData8, toSigned(FormValOpt, InvalidU64));
1551 
1552   // Test successful and unsuccessful block decoding.
1553   uint8_t Data[] = { 2, 3, 4 };
1554   ArrayRef<uint8_t> Array(Data);
1555   FormVal.setForm(DW_FORM_block1);
1556   FormVal.setBlockValue(Array);
1557   FormValOpt = FormVal;
1558 
1559   EXPECT_FALSE(toString(FormValOpt).hasValue());
1560   EXPECT_FALSE(toUnsigned(FormValOpt).hasValue());
1561   EXPECT_FALSE(toReference(FormValOpt).hasValue());
1562   EXPECT_FALSE(toSigned(FormValOpt).hasValue());
1563   EXPECT_FALSE(toAddress(FormValOpt).hasValue());
1564   EXPECT_FALSE(toSectionOffset(FormValOpt).hasValue());
1565   auto BlockOpt = toBlock(FormValOpt);
1566   EXPECT_TRUE(BlockOpt.hasValue());
1567   EXPECT_EQ(*BlockOpt, Array);
1568   EXPECT_EQ(nullptr, toString(FormValOpt, nullptr));
1569   EXPECT_EQ(InvalidU64, toUnsigned(FormValOpt, InvalidU64));
1570   EXPECT_EQ(InvalidU64, toReference(FormValOpt, InvalidU64));
1571   EXPECT_EQ(InvalidU64, toAddress(FormValOpt, InvalidU64));
1572   EXPECT_EQ(InvalidU64, toSectionOffset(FormValOpt, InvalidU64));
1573   EXPECT_EQ(InvalidS64, toSigned(FormValOpt, InvalidU64));
1574 
1575   // Test
1576 }
1577 
TEST(DWARFDebugInfo,TestFindAttrs)1578 TEST(DWARFDebugInfo, TestFindAttrs) {
1579   Triple Triple = getHostTripleForAddrSize(sizeof(void *));
1580   if (!isConfigurationSupported(Triple))
1581     return;
1582 
1583   // Test the DWARFDie::find() and DWARFDie::findRecursively() that take an
1584   // ArrayRef<dwarf::Attribute> value to make sure they work correctly.
1585   uint16_t Version = 4;
1586   auto ExpectedDG = dwarfgen::Generator::create(Triple, Version);
1587   ASSERT_THAT_EXPECTED(ExpectedDG, Succeeded());
1588   dwarfgen::Generator *DG = ExpectedDG.get().get();
1589   dwarfgen::CompileUnit &CU = DG->addCompileUnit();
1590 
1591   StringRef DieMangled("_Z3fooi");
1592   // Scope to allow us to re-use the same DIE names
1593   {
1594     auto CUDie = CU.getUnitDIE();
1595     auto FuncSpecDie = CUDie.addChild(DW_TAG_subprogram);
1596     auto FuncDie = CUDie.addChild(DW_TAG_subprogram);
1597     FuncSpecDie.addAttribute(DW_AT_MIPS_linkage_name, DW_FORM_strp, DieMangled);
1598     FuncDie.addAttribute(DW_AT_specification, DW_FORM_ref4, FuncSpecDie);
1599   }
1600 
1601   MemoryBufferRef FileBuffer(DG->generate(), "dwarf");
1602   auto Obj = object::ObjectFile::createObjectFile(FileBuffer);
1603   EXPECT_TRUE((bool)Obj);
1604   std::unique_ptr<DWARFContext> DwarfContext = DWARFContext::create(**Obj);
1605 
1606   // Verify the number of compile units is correct.
1607   uint32_t NumCUs = DwarfContext->getNumCompileUnits();
1608   EXPECT_EQ(NumCUs, 1u);
1609   DWARFCompileUnit *U = DwarfContext->getCompileUnitAtIndex(0);
1610 
1611   // Get the compile unit DIE is valid.
1612   auto CUDie = U->getUnitDIE(false);
1613   EXPECT_TRUE(CUDie.isValid());
1614 
1615   auto FuncSpecDie = CUDie.getFirstChild();
1616   auto FuncDie = FuncSpecDie.getSibling();
1617 
1618   // Make sure that passing in an empty attribute list behave correctly.
1619   EXPECT_FALSE(FuncDie.find(ArrayRef<dwarf::Attribute>()).hasValue());
1620 
1621   // Make sure that passing in a list of attribute that are not contained
1622   // in the DIE returns nothing.
1623   EXPECT_FALSE(FuncDie.find({DW_AT_low_pc, DW_AT_entry_pc}).hasValue());
1624 
1625   const dwarf::Attribute Attrs[] = {DW_AT_linkage_name,
1626                                     DW_AT_MIPS_linkage_name};
1627 
1628   // Make sure we can't extract the linkage name attributes when using
1629   // DWARFDie::find() since it won't check the DW_AT_specification DIE.
1630   EXPECT_FALSE(FuncDie.find(Attrs).hasValue());
1631 
1632   // Make sure we can extract the name from the specification die when using
1633   // DWARFDie::findRecursively() since it should recurse through the
1634   // DW_AT_specification DIE.
1635   auto NameOpt = FuncDie.findRecursively(Attrs);
1636   EXPECT_TRUE(NameOpt.hasValue());
1637   EXPECT_EQ(DieMangled, toString(NameOpt, ""));
1638 }
1639 
TEST(DWARFDebugInfo,TestImplicitConstAbbrevs)1640 TEST(DWARFDebugInfo, TestImplicitConstAbbrevs) {
1641   Triple Triple = getHostTripleForAddrSize(sizeof(void *));
1642   if (!isConfigurationSupported(Triple))
1643     return;
1644 
1645   uint16_t Version = 5;
1646   auto ExpectedDG = dwarfgen::Generator::create(Triple, Version);
1647   ASSERT_THAT_EXPECTED(ExpectedDG, Succeeded());
1648   dwarfgen::Generator *DG = ExpectedDG.get().get();
1649   dwarfgen::CompileUnit &CU = DG->addCompileUnit();
1650   dwarfgen::DIE CUDie = CU.getUnitDIE();
1651   const dwarf::Attribute Attr = DW_AT_lo_user;
1652   const int64_t Val1 = 42;
1653   const int64_t Val2 = 43;
1654 
1655   auto FirstVal1DIE = CUDie.addChild(DW_TAG_class_type);
1656   FirstVal1DIE.addAttribute(Attr, DW_FORM_implicit_const, Val1);
1657 
1658   auto SecondVal1DIE = CUDie.addChild(DW_TAG_class_type);
1659   SecondVal1DIE.addAttribute(Attr, DW_FORM_implicit_const, Val1);
1660 
1661   auto Val2DIE = CUDie.addChild(DW_TAG_class_type);
1662   Val2DIE.addAttribute(Attr, DW_FORM_implicit_const, Val2);
1663 
1664   MemoryBufferRef FileBuffer(DG->generate(), "dwarf");
1665   auto Obj = object::ObjectFile::createObjectFile(FileBuffer);
1666   EXPECT_TRUE((bool)Obj);
1667   std::unique_ptr<DWARFContext> DwarfContext = DWARFContext::create(**Obj);
1668   DWARFCompileUnit *U = DwarfContext->getCompileUnitAtIndex(0);
1669   EXPECT_TRUE((bool)U);
1670 
1671   const auto *Abbrevs = U->getAbbreviations();
1672   EXPECT_TRUE((bool)Abbrevs);
1673 
1674   // Let's find implicit_const abbrevs and verify,
1675   // that there are exactly two of them and both of them
1676   // can be dumped correctly.
1677   typedef decltype(Abbrevs->begin()) AbbrevIt;
1678   AbbrevIt Val1Abbrev = Abbrevs->end();
1679   AbbrevIt Val2Abbrev = Abbrevs->end();
1680   for(auto it = Abbrevs->begin(); it != Abbrevs->end(); ++it) {
1681     if (it->getNumAttributes() == 0)
1682       continue; // root abbrev for DW_TAG_compile_unit
1683 
1684     auto A = it->getAttrByIndex(0);
1685     EXPECT_EQ(A, Attr);
1686 
1687     auto FormValue = it->getAttributeValue(/* offset */ 0, A, *U);
1688     EXPECT_TRUE((bool)FormValue);
1689     EXPECT_EQ(FormValue->getForm(), dwarf::DW_FORM_implicit_const);
1690 
1691     const auto V = FormValue->getAsSignedConstant();
1692     EXPECT_TRUE((bool)V);
1693 
1694     auto VerifyAbbrevDump = [&V](AbbrevIt it) {
1695       std::string S;
1696       llvm::raw_string_ostream OS(S);
1697       it->dump(OS);
1698       auto FormPos = OS.str().find("DW_FORM_implicit_const");
1699       EXPECT_NE(FormPos, std::string::npos);
1700       auto ValPos = S.find_first_of("-0123456789", FormPos);
1701       EXPECT_NE(ValPos, std::string::npos);
1702       int64_t Val = std::atoll(S.substr(ValPos).c_str());
1703       EXPECT_EQ(Val, *V);
1704     };
1705 
1706     switch(*V) {
1707     case Val1:
1708       EXPECT_EQ(Val1Abbrev, Abbrevs->end());
1709       Val1Abbrev = it;
1710       VerifyAbbrevDump(it);
1711       break;
1712     case Val2:
1713       EXPECT_EQ(Val2Abbrev, Abbrevs->end());
1714       Val2Abbrev = it;
1715       VerifyAbbrevDump(it);
1716       break;
1717     default:
1718       FAIL() << "Unexpected attribute value: " << *V;
1719     }
1720   }
1721 
1722   // Now let's make sure that two Val1-DIEs refer to the same abbrev,
1723   // and Val2-DIE refers to another one.
1724   auto DieDG = U->getUnitDIE(false);
1725   auto it = DieDG.begin();
1726   std::multimap<int64_t, decltype(it->getAbbreviationDeclarationPtr())> DIEs;
1727   const DWARFAbbreviationDeclaration *AbbrevPtrVal1 = nullptr;
1728   const DWARFAbbreviationDeclaration *AbbrevPtrVal2 = nullptr;
1729   for (; it != DieDG.end(); ++it) {
1730     const auto *AbbrevPtr = it->getAbbreviationDeclarationPtr();
1731     EXPECT_TRUE((bool)AbbrevPtr);
1732     auto FormValue = it->find(Attr);
1733     EXPECT_TRUE((bool)FormValue);
1734     const auto V = FormValue->getAsSignedConstant();
1735     EXPECT_TRUE((bool)V);
1736     switch(*V) {
1737     case Val1:
1738       AbbrevPtrVal1 = AbbrevPtr;
1739       break;
1740     case Val2:
1741       AbbrevPtrVal2 = AbbrevPtr;
1742       break;
1743     default:
1744       FAIL() << "Unexpected attribute value: " << *V;
1745     }
1746     DIEs.insert(std::make_pair(*V, AbbrevPtr));
1747   }
1748   EXPECT_EQ(DIEs.count(Val1), 2u);
1749   EXPECT_EQ(DIEs.count(Val2), 1u);
1750   auto Val1Range = DIEs.equal_range(Val1);
1751   for (auto it = Val1Range.first; it != Val1Range.second; ++it)
1752     EXPECT_EQ(it->second, AbbrevPtrVal1);
1753   EXPECT_EQ(DIEs.find(Val2)->second, AbbrevPtrVal2);
1754 }
1755 
VerifyWarning(DWARFContext & DwarfContext,StringRef Error)1756 void VerifyWarning(DWARFContext &DwarfContext, StringRef Error) {
1757   SmallString<1024> Str;
1758   raw_svector_ostream Strm(Str);
1759   EXPECT_TRUE(DwarfContext.verify(Strm));
1760   EXPECT_TRUE(Str.str().contains(Error));
1761 }
1762 
VerifyError(DWARFContext & DwarfContext,StringRef Error)1763 void VerifyError(DWARFContext &DwarfContext, StringRef Error) {
1764   SmallString<1024> Str;
1765   raw_svector_ostream Strm(Str);
1766   EXPECT_FALSE(DwarfContext.verify(Strm));
1767   EXPECT_TRUE(Str.str().contains(Error));
1768 }
1769 
VerifySuccess(DWARFContext & DwarfContext)1770 void VerifySuccess(DWARFContext &DwarfContext) {
1771   SmallString<1024> Str;
1772   raw_svector_ostream Strm(Str);
1773   EXPECT_TRUE(DwarfContext.verify(Strm));
1774 }
1775 
TEST(DWARFDebugInfo,TestDwarfVerifyInvalidCURef)1776 TEST(DWARFDebugInfo, TestDwarfVerifyInvalidCURef) {
1777   // Create a single compile unit with a single function that has a DW_AT_type
1778   // that is CU relative. The CU offset is not valid because it is larger than
1779   // the compile unit itself.
1780 
1781   const char *yamldata = R"(
1782     debug_str:
1783       - ''
1784       - /tmp/main.c
1785       - main
1786     debug_abbrev:
1787       - Code:            0x00000001
1788         Tag:             DW_TAG_compile_unit
1789         Children:        DW_CHILDREN_yes
1790         Attributes:
1791           - Attribute:       DW_AT_name
1792             Form:            DW_FORM_strp
1793       - Code:            0x00000002
1794         Tag:             DW_TAG_subprogram
1795         Children:        DW_CHILDREN_no
1796         Attributes:
1797           - Attribute:       DW_AT_name
1798             Form:            DW_FORM_strp
1799           - Attribute:       DW_AT_type
1800             Form:            DW_FORM_ref4
1801     debug_info:
1802       - Length:
1803           TotalLength:     22
1804         Version:         4
1805         AbbrOffset:      0
1806         AddrSize:        8
1807         Entries:
1808           - AbbrCode:        0x00000001
1809             Values:
1810               - Value:           0x0000000000000001
1811           - AbbrCode:        0x00000002
1812             Values:
1813               - Value:           0x000000000000000D
1814               - Value:           0x0000000000001234
1815           - AbbrCode:        0x00000000
1816             Values:
1817   )";
1818   auto ErrOrSections = DWARFYAML::EmitDebugSections(StringRef(yamldata));
1819   ASSERT_TRUE((bool)ErrOrSections);
1820   std::unique_ptr<DWARFContext> DwarfContext =
1821       DWARFContext::create(*ErrOrSections, 8);
1822   VerifyError(*DwarfContext, "error: DW_FORM_ref4 CU offset 0x00001234 is "
1823                              "invalid (must be less than CU size of "
1824                              "0x0000001a):");
1825 }
1826 
TEST(DWARFDebugInfo,TestDwarfVerifyInvalidRefAddr)1827 TEST(DWARFDebugInfo, TestDwarfVerifyInvalidRefAddr) {
1828   // Create a single compile unit with a single function that has an invalid
1829   // DW_AT_type with an invalid .debug_info offset in its DW_FORM_ref_addr.
1830   const char *yamldata = R"(
1831     debug_str:
1832       - ''
1833       - /tmp/main.c
1834       - main
1835     debug_abbrev:
1836       - Code:            0x00000001
1837         Tag:             DW_TAG_compile_unit
1838         Children:        DW_CHILDREN_yes
1839         Attributes:
1840           - Attribute:       DW_AT_name
1841             Form:            DW_FORM_strp
1842       - Code:            0x00000002
1843         Tag:             DW_TAG_subprogram
1844         Children:        DW_CHILDREN_no
1845         Attributes:
1846           - Attribute:       DW_AT_name
1847             Form:            DW_FORM_strp
1848           - Attribute:       DW_AT_type
1849             Form:            DW_FORM_ref_addr
1850     debug_info:
1851       - Length:
1852           TotalLength:     22
1853         Version:         4
1854         AbbrOffset:      0
1855         AddrSize:        8
1856         Entries:
1857           - AbbrCode:        0x00000001
1858             Values:
1859               - Value:           0x0000000000000001
1860           - AbbrCode:        0x00000002
1861             Values:
1862               - Value:           0x000000000000000D
1863               - Value:           0x0000000000001234
1864           - AbbrCode:        0x00000000
1865             Values:
1866   )";
1867   auto ErrOrSections = DWARFYAML::EmitDebugSections(StringRef(yamldata));
1868   ASSERT_TRUE((bool)ErrOrSections);
1869   std::unique_ptr<DWARFContext> DwarfContext =
1870       DWARFContext::create(*ErrOrSections, 8);
1871   VerifyError(*DwarfContext,
1872               "error: DW_FORM_ref_addr offset beyond .debug_info bounds:");
1873 }
1874 
TEST(DWARFDebugInfo,TestDwarfVerifyInvalidRanges)1875 TEST(DWARFDebugInfo, TestDwarfVerifyInvalidRanges) {
1876   // Create a single compile unit with a DW_AT_ranges whose section offset
1877   // isn't valid.
1878   const char *yamldata = R"(
1879     debug_str:
1880       - ''
1881       - /tmp/main.c
1882     debug_abbrev:
1883       - Code:            0x00000001
1884         Tag:             DW_TAG_compile_unit
1885         Children:        DW_CHILDREN_no
1886         Attributes:
1887           - Attribute:       DW_AT_name
1888             Form:            DW_FORM_strp
1889           - Attribute:       DW_AT_ranges
1890             Form:            DW_FORM_sec_offset
1891     debug_info:
1892       - Length:
1893           TotalLength:     16
1894         Version:         4
1895         AbbrOffset:      0
1896         AddrSize:        8
1897         Entries:
1898           - AbbrCode:        0x00000001
1899             Values:
1900               - Value:           0x0000000000000001
1901               - Value:           0x0000000000001000
1902 
1903   )";
1904   auto ErrOrSections = DWARFYAML::EmitDebugSections(StringRef(yamldata));
1905   ASSERT_TRUE((bool)ErrOrSections);
1906   std::unique_ptr<DWARFContext> DwarfContext =
1907       DWARFContext::create(*ErrOrSections, 8);
1908   VerifyError(*DwarfContext,
1909               "error: DW_AT_ranges offset is beyond .debug_ranges bounds:");
1910 }
1911 
TEST(DWARFDebugInfo,TestDwarfVerifyInvalidStmtList)1912 TEST(DWARFDebugInfo, TestDwarfVerifyInvalidStmtList) {
1913   // Create a single compile unit with a DW_AT_stmt_list whose section offset
1914   // isn't valid.
1915   const char *yamldata = R"(
1916     debug_str:
1917       - ''
1918       - /tmp/main.c
1919     debug_abbrev:
1920       - Code:            0x00000001
1921         Tag:             DW_TAG_compile_unit
1922         Children:        DW_CHILDREN_no
1923         Attributes:
1924           - Attribute:       DW_AT_name
1925             Form:            DW_FORM_strp
1926           - Attribute:       DW_AT_stmt_list
1927             Form:            DW_FORM_sec_offset
1928     debug_info:
1929       - Length:
1930           TotalLength:     16
1931         Version:         4
1932         AbbrOffset:      0
1933         AddrSize:        8
1934         Entries:
1935           - AbbrCode:        0x00000001
1936             Values:
1937               - Value:           0x0000000000000001
1938               - Value:           0x0000000000001000
1939 
1940   )";
1941   auto ErrOrSections = DWARFYAML::EmitDebugSections(StringRef(yamldata));
1942   ASSERT_TRUE((bool)ErrOrSections);
1943   std::unique_ptr<DWARFContext> DwarfContext =
1944       DWARFContext::create(*ErrOrSections, 8);
1945   VerifyError(
1946       *DwarfContext,
1947       "error: DW_AT_stmt_list offset is beyond .debug_line bounds: 0x00001000");
1948 }
1949 
TEST(DWARFDebugInfo,TestDwarfVerifyInvalidStrp)1950 TEST(DWARFDebugInfo, TestDwarfVerifyInvalidStrp) {
1951   // Create a single compile unit with a single function that has an invalid
1952   // DW_FORM_strp for the DW_AT_name.
1953   const char *yamldata = R"(
1954     debug_str:
1955       - ''
1956     debug_abbrev:
1957       - Code:            0x00000001
1958         Tag:             DW_TAG_compile_unit
1959         Children:        DW_CHILDREN_no
1960         Attributes:
1961           - Attribute:       DW_AT_name
1962             Form:            DW_FORM_strp
1963     debug_info:
1964       - Length:
1965           TotalLength:     12
1966         Version:         4
1967         AbbrOffset:      0
1968         AddrSize:        8
1969         Entries:
1970           - AbbrCode:        0x00000001
1971             Values:
1972               - Value:           0x0000000000001234
1973   )";
1974   auto ErrOrSections = DWARFYAML::EmitDebugSections(StringRef(yamldata));
1975   ASSERT_TRUE((bool)ErrOrSections);
1976   std::unique_ptr<DWARFContext> DwarfContext =
1977       DWARFContext::create(*ErrOrSections, 8);
1978   VerifyError(*DwarfContext,
1979               "error: DW_FORM_strp offset beyond .debug_str bounds:");
1980 }
1981 
TEST(DWARFDebugInfo,TestDwarfVerifyInvalidRefAddrBetween)1982 TEST(DWARFDebugInfo, TestDwarfVerifyInvalidRefAddrBetween) {
1983   // Create a single compile unit with a single function that has a DW_AT_type
1984   // with a valid .debug_info offset, but the offset is between two DIEs.
1985   const char *yamldata = R"(
1986     debug_str:
1987       - ''
1988       - /tmp/main.c
1989       - main
1990     debug_abbrev:
1991       - Code:            0x00000001
1992         Tag:             DW_TAG_compile_unit
1993         Children:        DW_CHILDREN_yes
1994         Attributes:
1995           - Attribute:       DW_AT_name
1996             Form:            DW_FORM_strp
1997       - Code:            0x00000002
1998         Tag:             DW_TAG_subprogram
1999         Children:        DW_CHILDREN_no
2000         Attributes:
2001           - Attribute:       DW_AT_name
2002             Form:            DW_FORM_strp
2003           - Attribute:       DW_AT_type
2004             Form:            DW_FORM_ref_addr
2005     debug_info:
2006       - Length:
2007           TotalLength:     22
2008         Version:         4
2009         AbbrOffset:      0
2010         AddrSize:        8
2011         Entries:
2012           - AbbrCode:        0x00000001
2013             Values:
2014               - Value:           0x0000000000000001
2015           - AbbrCode:        0x00000002
2016             Values:
2017               - Value:           0x000000000000000D
2018               - Value:           0x0000000000000011
2019           - AbbrCode:        0x00000000
2020             Values:
2021   )";
2022   auto ErrOrSections = DWARFYAML::EmitDebugSections(StringRef(yamldata));
2023   ASSERT_TRUE((bool)ErrOrSections);
2024   std::unique_ptr<DWARFContext> DwarfContext =
2025       DWARFContext::create(*ErrOrSections, 8);
2026   VerifyError(
2027       *DwarfContext,
2028       "error: invalid DIE reference 0x00000011. Offset is in between DIEs:");
2029 }
2030 
TEST(DWARFDebugInfo,TestDwarfVerifyInvalidLineSequence)2031 TEST(DWARFDebugInfo, TestDwarfVerifyInvalidLineSequence) {
2032   // Create a single compile unit whose line table has a sequence in it where
2033   // the address decreases.
2034   StringRef yamldata = R"(
2035     debug_str:
2036       - ''
2037       - /tmp/main.c
2038     debug_abbrev:
2039       - Code:            0x00000001
2040         Tag:             DW_TAG_compile_unit
2041         Children:        DW_CHILDREN_no
2042         Attributes:
2043           - Attribute:       DW_AT_name
2044             Form:            DW_FORM_strp
2045           - Attribute:       DW_AT_stmt_list
2046             Form:            DW_FORM_sec_offset
2047     debug_info:
2048       - Length:
2049           TotalLength:     16
2050         Version:         4
2051         AbbrOffset:      0
2052         AddrSize:        8
2053         Entries:
2054           - AbbrCode:        0x00000001
2055             Values:
2056               - Value:           0x0000000000000001
2057               - Value:           0x0000000000000000
2058     debug_line:
2059       - Length:
2060           TotalLength:     68
2061         Version:         2
2062         PrologueLength:  34
2063         MinInstLength:   1
2064         DefaultIsStmt:   1
2065         LineBase:        251
2066         LineRange:       14
2067         OpcodeBase:      13
2068         StandardOpcodeLengths: [ 0, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 1 ]
2069         IncludeDirs:
2070           - /tmp
2071         Files:
2072           - Name:            main.c
2073             DirIdx:          1
2074             ModTime:         0
2075             Length:          0
2076         Opcodes:
2077           - Opcode:          DW_LNS_extended_op
2078             ExtLen:          9
2079             SubOpcode:       DW_LNE_set_address
2080             Data:            4112
2081           - Opcode:          DW_LNS_advance_line
2082             SData:           9
2083             Data:            4112
2084           - Opcode:          DW_LNS_copy
2085             Data:            4112
2086           - Opcode:          DW_LNS_advance_pc
2087             Data:            18446744073709551600
2088           - Opcode:          DW_LNS_extended_op
2089             ExtLen:          1
2090             SubOpcode:       DW_LNE_end_sequence
2091             Data:            18446744073709551600
2092   )";
2093   auto ErrOrSections = DWARFYAML::EmitDebugSections(yamldata);
2094   ASSERT_TRUE((bool)ErrOrSections);
2095   std::unique_ptr<DWARFContext> DwarfContext =
2096       DWARFContext::create(*ErrOrSections, 8);
2097   VerifyError(*DwarfContext, "error: .debug_line[0x00000000] row[1] decreases "
2098                              "in address from previous row:");
2099 }
2100 
TEST(DWARFDebugInfo,TestDwarfVerifyInvalidLineFileIndex)2101 TEST(DWARFDebugInfo, TestDwarfVerifyInvalidLineFileIndex) {
2102   // Create a single compile unit whose line table has a line table row with
2103   // an invalid file index.
2104   StringRef yamldata = R"(
2105     debug_str:
2106       - ''
2107       - /tmp/main.c
2108     debug_abbrev:
2109       - Code:            0x00000001
2110         Tag:             DW_TAG_compile_unit
2111         Children:        DW_CHILDREN_no
2112         Attributes:
2113           - Attribute:       DW_AT_name
2114             Form:            DW_FORM_strp
2115           - Attribute:       DW_AT_stmt_list
2116             Form:            DW_FORM_sec_offset
2117     debug_info:
2118       - Length:
2119           TotalLength:     16
2120         Version:         4
2121         AbbrOffset:      0
2122         AddrSize:        8
2123         Entries:
2124           - AbbrCode:        0x00000001
2125             Values:
2126               - Value:           0x0000000000000001
2127               - Value:           0x0000000000000000
2128     debug_line:
2129       - Length:
2130           TotalLength:     61
2131         Version:         2
2132         PrologueLength:  34
2133         MinInstLength:   1
2134         DefaultIsStmt:   1
2135         LineBase:        251
2136         LineRange:       14
2137         OpcodeBase:      13
2138         StandardOpcodeLengths: [ 0, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 1 ]
2139         IncludeDirs:
2140           - /tmp
2141         Files:
2142           - Name:            main.c
2143             DirIdx:          1
2144             ModTime:         0
2145             Length:          0
2146         Opcodes:
2147           - Opcode:          DW_LNS_extended_op
2148             ExtLen:          9
2149             SubOpcode:       DW_LNE_set_address
2150             Data:            4096
2151           - Opcode:          DW_LNS_advance_line
2152             SData:           9
2153             Data:            4096
2154           - Opcode:          DW_LNS_copy
2155             Data:            4096
2156           - Opcode:          DW_LNS_advance_pc
2157             Data:            16
2158           - Opcode:          DW_LNS_set_file
2159             Data:            5
2160           - Opcode:          DW_LNS_extended_op
2161             ExtLen:          1
2162             SubOpcode:       DW_LNE_end_sequence
2163             Data:            5
2164   )";
2165   auto ErrOrSections = DWARFYAML::EmitDebugSections(yamldata);
2166   ASSERT_TRUE((bool)ErrOrSections);
2167   std::unique_ptr<DWARFContext> DwarfContext =
2168       DWARFContext::create(*ErrOrSections, 8);
2169   VerifyError(*DwarfContext, "error: .debug_line[0x00000000][1] has invalid "
2170                              "file index 5 (valid values are [1,1]):");
2171 }
2172 
TEST(DWARFDebugInfo,TestDwarfVerifyInvalidLineTablePorlogueDirIndex)2173 TEST(DWARFDebugInfo, TestDwarfVerifyInvalidLineTablePorlogueDirIndex) {
2174   // Create a single compile unit whose line table has a prologue with an
2175   // invalid dir index.
2176   StringRef yamldata = R"(
2177     debug_str:
2178       - ''
2179       - /tmp/main.c
2180     debug_abbrev:
2181       - Code:            0x00000001
2182         Tag:             DW_TAG_compile_unit
2183         Children:        DW_CHILDREN_no
2184         Attributes:
2185           - Attribute:       DW_AT_name
2186             Form:            DW_FORM_strp
2187           - Attribute:       DW_AT_stmt_list
2188             Form:            DW_FORM_sec_offset
2189     debug_info:
2190       - Length:
2191           TotalLength:     16
2192         Version:         4
2193         AbbrOffset:      0
2194         AddrSize:        8
2195         Entries:
2196           - AbbrCode:        0x00000001
2197             Values:
2198               - Value:           0x0000000000000001
2199               - Value:           0x0000000000000000
2200     debug_line:
2201       - Length:
2202           TotalLength:     61
2203         Version:         2
2204         PrologueLength:  34
2205         MinInstLength:   1
2206         DefaultIsStmt:   1
2207         LineBase:        251
2208         LineRange:       14
2209         OpcodeBase:      13
2210         StandardOpcodeLengths: [ 0, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 1 ]
2211         IncludeDirs:
2212           - /tmp
2213         Files:
2214           - Name:            main.c
2215             DirIdx:          2
2216             ModTime:         0
2217             Length:          0
2218         Opcodes:
2219           - Opcode:          DW_LNS_extended_op
2220             ExtLen:          9
2221             SubOpcode:       DW_LNE_set_address
2222             Data:            4096
2223           - Opcode:          DW_LNS_advance_line
2224             SData:           9
2225             Data:            4096
2226           - Opcode:          DW_LNS_copy
2227             Data:            4096
2228           - Opcode:          DW_LNS_advance_pc
2229             Data:            16
2230           - Opcode:          DW_LNS_set_file
2231             Data:            1
2232           - Opcode:          DW_LNS_extended_op
2233             ExtLen:          1
2234             SubOpcode:       DW_LNE_end_sequence
2235             Data:            1
2236   )";
2237   auto ErrOrSections = DWARFYAML::EmitDebugSections(yamldata);
2238   ASSERT_TRUE((bool)ErrOrSections);
2239   std::unique_ptr<DWARFContext> DwarfContext =
2240       DWARFContext::create(*ErrOrSections, 8);
2241   VerifyError(*DwarfContext,
2242               "error: .debug_line[0x00000000].prologue."
2243               "file_names[1].dir_idx contains an invalid index: 2");
2244 }
2245 
TEST(DWARFDebugInfo,TestDwarfVerifyDuplicateFileWarning)2246 TEST(DWARFDebugInfo, TestDwarfVerifyDuplicateFileWarning) {
2247   // Create a single compile unit whose line table has a prologue with an
2248   // invalid dir index.
2249   StringRef yamldata = R"(
2250     debug_str:
2251       - ''
2252       - /tmp/main.c
2253     debug_abbrev:
2254       - Code:            0x00000001
2255         Tag:             DW_TAG_compile_unit
2256         Children:        DW_CHILDREN_no
2257         Attributes:
2258           - Attribute:       DW_AT_name
2259             Form:            DW_FORM_strp
2260           - Attribute:       DW_AT_stmt_list
2261             Form:            DW_FORM_sec_offset
2262     debug_info:
2263       - Length:
2264           TotalLength:     16
2265         Version:         4
2266         AbbrOffset:      0
2267         AddrSize:        8
2268         Entries:
2269           - AbbrCode:        0x00000001
2270             Values:
2271               - Value:           0x0000000000000001
2272               - Value:           0x0000000000000000
2273     debug_line:
2274       - Length:
2275           TotalLength:     71
2276         Version:         2
2277         PrologueLength:  44
2278         MinInstLength:   1
2279         DefaultIsStmt:   1
2280         LineBase:        251
2281         LineRange:       14
2282         OpcodeBase:      13
2283         StandardOpcodeLengths: [ 0, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 1 ]
2284         IncludeDirs:
2285           - /tmp
2286         Files:
2287           - Name:            main.c
2288             DirIdx:          1
2289             ModTime:         0
2290             Length:          0
2291           - Name:            main.c
2292             DirIdx:          1
2293             ModTime:         0
2294             Length:          0
2295         Opcodes:
2296           - Opcode:          DW_LNS_extended_op
2297             ExtLen:          9
2298             SubOpcode:       DW_LNE_set_address
2299             Data:            4096
2300           - Opcode:          DW_LNS_advance_line
2301             SData:           9
2302             Data:            4096
2303           - Opcode:          DW_LNS_copy
2304             Data:            4096
2305           - Opcode:          DW_LNS_advance_pc
2306             Data:            16
2307           - Opcode:          DW_LNS_set_file
2308             Data:            1
2309           - Opcode:          DW_LNS_extended_op
2310             ExtLen:          1
2311             SubOpcode:       DW_LNE_end_sequence
2312             Data:            2
2313   )";
2314   auto ErrOrSections = DWARFYAML::EmitDebugSections(yamldata);
2315   ASSERT_TRUE((bool)ErrOrSections);
2316   std::unique_ptr<DWARFContext> DwarfContext =
2317       DWARFContext::create(*ErrOrSections, 8);
2318   VerifyWarning(*DwarfContext,
2319                 "warning: .debug_line[0x00000000].prologue.file_names[2] is "
2320                 "a duplicate of file_names[1]");
2321 }
2322 
TEST(DWARFDebugInfo,TestDwarfVerifyCUDontShareLineTable)2323 TEST(DWARFDebugInfo, TestDwarfVerifyCUDontShareLineTable) {
2324   // Create a two compile units where both compile units share the same
2325   // DW_AT_stmt_list value and verify we report the error correctly.
2326   StringRef yamldata = R"(
2327     debug_str:
2328       - ''
2329       - /tmp/main.c
2330       - /tmp/foo.c
2331     debug_abbrev:
2332       - Code:            0x00000001
2333         Tag:             DW_TAG_compile_unit
2334         Children:        DW_CHILDREN_no
2335         Attributes:
2336           - Attribute:       DW_AT_name
2337             Form:            DW_FORM_strp
2338           - Attribute:       DW_AT_stmt_list
2339             Form:            DW_FORM_sec_offset
2340     debug_info:
2341       - Length:
2342           TotalLength:     16
2343         Version:         4
2344         AbbrOffset:      0
2345         AddrSize:        8
2346         Entries:
2347           - AbbrCode:        0x00000001
2348             Values:
2349               - Value:           0x0000000000000001
2350               - Value:           0x0000000000000000
2351       - Length:
2352           TotalLength:     16
2353         Version:         4
2354         AbbrOffset:      0
2355         AddrSize:        8
2356         Entries:
2357           - AbbrCode:        0x00000001
2358             Values:
2359               - Value:           0x000000000000000D
2360               - Value:           0x0000000000000000
2361     debug_line:
2362       - Length:
2363           TotalLength:     60
2364         Version:         2
2365         PrologueLength:  34
2366         MinInstLength:   1
2367         DefaultIsStmt:   1
2368         LineBase:        251
2369         LineRange:       14
2370         OpcodeBase:      13
2371         StandardOpcodeLengths: [ 0, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 1 ]
2372         IncludeDirs:
2373           - /tmp
2374         Files:
2375           - Name:            main.c
2376             DirIdx:          1
2377             ModTime:         0
2378             Length:          0
2379         Opcodes:
2380           - Opcode:          DW_LNS_extended_op
2381             ExtLen:          9
2382             SubOpcode:       DW_LNE_set_address
2383             Data:            4096
2384           - Opcode:          DW_LNS_advance_line
2385             SData:           9
2386             Data:            4096
2387           - Opcode:          DW_LNS_copy
2388             Data:            4096
2389           - Opcode:          DW_LNS_advance_pc
2390             Data:            256
2391           - Opcode:          DW_LNS_extended_op
2392             ExtLen:          1
2393             SubOpcode:       DW_LNE_end_sequence
2394             Data:            256
2395   )";
2396   auto ErrOrSections = DWARFYAML::EmitDebugSections(yamldata);
2397   ASSERT_TRUE((bool)ErrOrSections);
2398   std::unique_ptr<DWARFContext> DwarfContext =
2399       DWARFContext::create(*ErrOrSections, 8);
2400   VerifyError(*DwarfContext,
2401               "error: two compile unit DIEs, 0x0000000b and "
2402               "0x0000001f, have the same DW_AT_stmt_list section "
2403               "offset:");
2404 }
2405 
TEST(DWARFDebugInfo,TestErrorReportingPolicy)2406 TEST(DWARFDebugInfo, TestErrorReportingPolicy) {
2407   Triple Triple("x86_64-pc-linux");
2408   if (!isConfigurationSupported(Triple))
2409       return;
2410 
2411   auto ExpectedDG = dwarfgen::Generator::create(Triple, 4 /*DwarfVersion*/);
2412   ASSERT_THAT_EXPECTED(ExpectedDG, Succeeded());
2413   dwarfgen::Generator *DG = ExpectedDG.get().get();
2414   AsmPrinter *AP = DG->getAsmPrinter();
2415   MCContext *MC = DG->getMCContext();
2416 
2417   // Emit two compressed sections with broken headers.
2418   AP->OutStreamer->SwitchSection(
2419       MC->getELFSection(".zdebug_foo", 0 /*Type*/, 0 /*Flags*/));
2420   AP->OutStreamer->EmitBytes("0");
2421   AP->OutStreamer->SwitchSection(
2422       MC->getELFSection(".zdebug_bar", 0 /*Type*/, 0 /*Flags*/));
2423   AP->OutStreamer->EmitBytes("0");
2424 
2425   MemoryBufferRef FileBuffer(DG->generate(), "dwarf");
2426   auto Obj = object::ObjectFile::createObjectFile(FileBuffer);
2427   EXPECT_TRUE((bool)Obj);
2428 
2429   // Case 1: error handler handles all errors. That allows
2430   // DWARFContext to parse whole file and find both two errors we know about.
2431   int Errors = 0;
2432   std::unique_ptr<DWARFContext> Ctx1 =
2433       DWARFContext::create(**Obj, nullptr, [&](Error E) {
2434         ++Errors;
2435         consumeError(std::move(E));
2436         return ErrorPolicy::Continue;
2437       });
2438   EXPECT_TRUE(Errors == 2);
2439 
2440   // Case 2: error handler stops parsing of object after first error.
2441   Errors = 0;
2442   std::unique_ptr<DWARFContext> Ctx2 =
2443       DWARFContext::create(**Obj, nullptr, [&](Error E) {
2444         ++Errors;
2445         consumeError(std::move(E));
2446         return ErrorPolicy::Halt;
2447       });
2448   EXPECT_TRUE(Errors == 1);
2449 }
2450 
TEST(DWARFDebugInfo,TestDwarfVerifyCURangesIncomplete)2451 TEST(DWARFDebugInfo, TestDwarfVerifyCURangesIncomplete) {
2452   // Create a single compile unit with a single function. The compile
2453   // unit has a DW_AT_ranges attribute that doesn't fully contain the
2454   // address range of the function. The verification should fail due to
2455   // the CU ranges not containing all of the address ranges of all of the
2456   // functions.
2457   StringRef yamldata = R"(
2458     debug_str:
2459       - ''
2460       - /tmp/main.c
2461     debug_abbrev:
2462       - Code:            0x00000001
2463         Tag:             DW_TAG_compile_unit
2464         Children:        DW_CHILDREN_yes
2465         Attributes:
2466           - Attribute:       DW_AT_low_pc
2467             Form:            DW_FORM_addr
2468           - Attribute:       DW_AT_high_pc
2469             Form:            DW_FORM_addr
2470           - Attribute:       DW_AT_name
2471             Form:            DW_FORM_strp
2472       - Code:            0x00000002
2473         Tag:             DW_TAG_subprogram
2474         Children:        DW_CHILDREN_no
2475         Attributes:
2476           - Attribute:       DW_AT_low_pc
2477             Form:            DW_FORM_addr
2478           - Attribute:       DW_AT_high_pc
2479             Form:            DW_FORM_addr
2480     debug_info:
2481       - Length:
2482           TotalLength:     46
2483         Version:         4
2484         AbbrOffset:      0
2485         AddrSize:        8
2486         Entries:
2487           - AbbrCode:        0x00000001
2488             Values:
2489               - Value:           0x0000000000001000
2490               - Value:           0x0000000000001500
2491               - Value:           0x0000000000000001
2492           - AbbrCode:        0x00000002
2493             Values:
2494               - Value:           0x0000000000001000
2495               - Value:           0x0000000000002000
2496           - AbbrCode:        0x00000000
2497             Values:
2498   )";
2499   auto ErrOrSections = DWARFYAML::EmitDebugSections(yamldata);
2500   ASSERT_TRUE((bool)ErrOrSections);
2501   std::unique_ptr<DWARFContext> DwarfContext =
2502       DWARFContext::create(*ErrOrSections, 8);
2503   VerifyError(*DwarfContext, "error: DIE address ranges are not "
2504                              "contained in its parent's ranges:");
2505 }
2506 
TEST(DWARFDebugInfo,TestDwarfVerifyLexicalBlockRanges)2507 TEST(DWARFDebugInfo, TestDwarfVerifyLexicalBlockRanges) {
2508   // Create a single compile unit with a single function that has a lexical
2509   // block whose address range is not contained in the function address range.
2510   StringRef yamldata = R"(
2511     debug_str:
2512       - ''
2513       - /tmp/main.c
2514       - main
2515     debug_abbrev:
2516       - Code:            0x00000001
2517         Tag:             DW_TAG_compile_unit
2518         Children:        DW_CHILDREN_yes
2519         Attributes:
2520           - Attribute:       DW_AT_name
2521             Form:            DW_FORM_strp
2522       - Code:            0x00000002
2523         Tag:             DW_TAG_subprogram
2524         Children:        DW_CHILDREN_yes
2525         Attributes:
2526           - Attribute:       DW_AT_name
2527             Form:            DW_FORM_strp
2528           - Attribute:       DW_AT_low_pc
2529             Form:            DW_FORM_addr
2530           - Attribute:       DW_AT_high_pc
2531             Form:            DW_FORM_addr
2532       - Code:            0x00000003
2533         Tag:             DW_TAG_lexical_block
2534         Children:        DW_CHILDREN_no
2535         Attributes:
2536           - Attribute:       DW_AT_low_pc
2537             Form:            DW_FORM_addr
2538           - Attribute:       DW_AT_high_pc
2539             Form:            DW_FORM_addr
2540     debug_info:
2541       - Length:
2542           TotalLength:     52
2543         Version:         4
2544         AbbrOffset:      0
2545         AddrSize:        8
2546         Entries:
2547           - AbbrCode:        0x00000001
2548             Values:
2549               - Value:           0x0000000000000001
2550           - AbbrCode:        0x00000002
2551             Values:
2552               - Value:           0x000000000000000D
2553               - Value:           0x0000000000001000
2554               - Value:           0x0000000000002000
2555           - AbbrCode:        0x00000003
2556             Values:
2557               - Value:           0x0000000000001000
2558               - Value:           0x0000000000002001
2559           - AbbrCode:        0x00000000
2560             Values:
2561           - AbbrCode:        0x00000000
2562             Values:
2563   )";
2564   auto ErrOrSections = DWARFYAML::EmitDebugSections(yamldata);
2565   ASSERT_TRUE((bool)ErrOrSections);
2566   std::unique_ptr<DWARFContext> DwarfContext =
2567       DWARFContext::create(*ErrOrSections, 8);
2568   VerifyError(*DwarfContext, "error: DIE address ranges are not "
2569                              "contained in its parent's ranges:");
2570 }
2571 
TEST(DWARFDebugInfo,TestDwarfVerifyOverlappingFunctionRanges)2572 TEST(DWARFDebugInfo, TestDwarfVerifyOverlappingFunctionRanges) {
2573   // Create a single compile unit with a two functions that have overlapping
2574   // address ranges.
2575   StringRef yamldata = R"(
2576     debug_str:
2577       - ''
2578       - /tmp/main.c
2579       - main
2580       - foo
2581     debug_abbrev:
2582       - Code:            0x00000001
2583         Tag:             DW_TAG_compile_unit
2584         Children:        DW_CHILDREN_yes
2585         Attributes:
2586           - Attribute:       DW_AT_name
2587             Form:            DW_FORM_strp
2588       - Code:            0x00000002
2589         Tag:             DW_TAG_subprogram
2590         Children:        DW_CHILDREN_no
2591         Attributes:
2592           - Attribute:       DW_AT_name
2593             Form:            DW_FORM_strp
2594           - Attribute:       DW_AT_low_pc
2595             Form:            DW_FORM_addr
2596           - Attribute:       DW_AT_high_pc
2597             Form:            DW_FORM_addr
2598     debug_info:
2599       - Length:
2600           TotalLength:     55
2601         Version:         4
2602         AbbrOffset:      0
2603         AddrSize:        8
2604         Entries:
2605           - AbbrCode:        0x00000001
2606             Values:
2607               - Value:           0x0000000000000001
2608           - AbbrCode:        0x00000002
2609             Values:
2610               - Value:           0x000000000000000D
2611               - Value:           0x0000000000001000
2612               - Value:           0x0000000000002000
2613           - AbbrCode:        0x00000002
2614             Values:
2615               - Value:           0x0000000000000012
2616               - Value:           0x0000000000001FFF
2617               - Value:           0x0000000000002000
2618           - AbbrCode:        0x00000000
2619             Values:
2620   )";
2621   auto ErrOrSections = DWARFYAML::EmitDebugSections(yamldata);
2622   ASSERT_TRUE((bool)ErrOrSections);
2623   std::unique_ptr<DWARFContext> DwarfContext =
2624       DWARFContext::create(*ErrOrSections, 8);
2625   VerifyError(*DwarfContext, "error: DIEs have overlapping address ranges:");
2626 }
2627 
TEST(DWARFDebugInfo,TestDwarfVerifyOverlappingLexicalBlockRanges)2628 TEST(DWARFDebugInfo, TestDwarfVerifyOverlappingLexicalBlockRanges) {
2629   // Create a single compile unit with a one function that has two lexical
2630   // blocks with overlapping address ranges.
2631   StringRef yamldata = R"(
2632     debug_str:
2633       - ''
2634       - /tmp/main.c
2635       - main
2636     debug_abbrev:
2637       - Code:            0x00000001
2638         Tag:             DW_TAG_compile_unit
2639         Children:        DW_CHILDREN_yes
2640         Attributes:
2641           - Attribute:       DW_AT_low_pc
2642             Form:            DW_FORM_addr
2643           - Attribute:       DW_AT_high_pc
2644             Form:            DW_FORM_addr
2645           - Attribute:       DW_AT_name
2646             Form:            DW_FORM_strp
2647       - Code:            0x00000002
2648         Tag:             DW_TAG_subprogram
2649         Children:        DW_CHILDREN_yes
2650         Attributes:
2651           - Attribute:       DW_AT_name
2652             Form:            DW_FORM_strp
2653           - Attribute:       DW_AT_low_pc
2654             Form:            DW_FORM_addr
2655           - Attribute:       DW_AT_high_pc
2656             Form:            DW_FORM_addr
2657       - Code:            0x00000003
2658         Tag:             DW_TAG_lexical_block
2659         Children:        DW_CHILDREN_no
2660         Attributes:
2661           - Attribute:       DW_AT_low_pc
2662             Form:            DW_FORM_addr
2663           - Attribute:       DW_AT_high_pc
2664             Form:            DW_FORM_addr
2665     debug_info:
2666       - Length:
2667           TotalLength:     85
2668         Version:         4
2669         AbbrOffset:      0
2670         AddrSize:        8
2671         Entries:
2672           - AbbrCode:        0x00000001
2673             Values:
2674               - Value:           0x0000000000001000
2675               - Value:           0x0000000000002000
2676               - Value:           0x0000000000000001
2677           - AbbrCode:        0x00000002
2678             Values:
2679               - Value:           0x000000000000000D
2680               - Value:           0x0000000000001000
2681               - Value:           0x0000000000002000
2682           - AbbrCode:        0x00000003
2683             Values:
2684               - Value:           0x0000000000001100
2685               - Value:           0x0000000000001300
2686           - AbbrCode:        0x00000003
2687             Values:
2688               - Value:           0x00000000000012FF
2689               - Value:           0x0000000000001300
2690           - AbbrCode:        0x00000000
2691             Values:
2692           - AbbrCode:        0x00000000
2693             Values:
2694   )";
2695   auto ErrOrSections = DWARFYAML::EmitDebugSections(yamldata);
2696   ASSERT_TRUE((bool)ErrOrSections);
2697   std::unique_ptr<DWARFContext> DwarfContext =
2698       DWARFContext::create(*ErrOrSections, 8);
2699   VerifyError(*DwarfContext, "error: DIEs have overlapping address ranges:");
2700 }
2701 
TEST(DWARFDebugInfo,TestDwarfVerifyInvalidDIERange)2702 TEST(DWARFDebugInfo, TestDwarfVerifyInvalidDIERange) {
2703   // Create a single compile unit with a single function that has an invalid
2704   // address range where the high PC is smaller than the low PC.
2705   StringRef yamldata = R"(
2706     debug_str:
2707       - ''
2708       - /tmp/main.c
2709       - main
2710     debug_abbrev:
2711       - Code:            0x00000001
2712         Tag:             DW_TAG_compile_unit
2713         Children:        DW_CHILDREN_yes
2714         Attributes:
2715           - Attribute:       DW_AT_name
2716             Form:            DW_FORM_strp
2717       - Code:            0x00000002
2718         Tag:             DW_TAG_subprogram
2719         Children:        DW_CHILDREN_no
2720         Attributes:
2721           - Attribute:       DW_AT_name
2722             Form:            DW_FORM_strp
2723           - Attribute:       DW_AT_low_pc
2724             Form:            DW_FORM_addr
2725           - Attribute:       DW_AT_high_pc
2726             Form:            DW_FORM_addr
2727     debug_info:
2728       - Length:
2729           TotalLength:     34
2730         Version:         4
2731         AbbrOffset:      0
2732         AddrSize:        8
2733         Entries:
2734           - AbbrCode:        0x00000001
2735             Values:
2736               - Value:           0x0000000000000001
2737           - AbbrCode:        0x00000002
2738             Values:
2739               - Value:           0x000000000000000D
2740               - Value:           0x0000000000001000
2741               - Value:           0x0000000000000900
2742           - AbbrCode:        0x00000000
2743             Values:
2744   )";
2745   auto ErrOrSections = DWARFYAML::EmitDebugSections(yamldata);
2746   ASSERT_TRUE((bool)ErrOrSections);
2747   std::unique_ptr<DWARFContext> DwarfContext =
2748       DWARFContext::create(*ErrOrSections, 8);
2749   VerifyError(*DwarfContext, "error: Invalid address range");
2750 }
2751 
TEST(DWARFDebugInfo,TestDwarfVerifyElidedDoesntFail)2752 TEST(DWARFDebugInfo, TestDwarfVerifyElidedDoesntFail) {
2753   // Create a single compile unit with two functions: one that has a valid range
2754   // and one whose low and high PC are the same. When the low and high PC are
2755   // the same, this indicates the function was dead code stripped. We want to
2756   // ensure that verification succeeds.
2757   StringRef yamldata = R"(
2758     debug_str:
2759       - ''
2760       - /tmp/main.c
2761       - main
2762       - elided
2763     debug_abbrev:
2764       - Code:            0x00000001
2765         Tag:             DW_TAG_compile_unit
2766         Children:        DW_CHILDREN_yes
2767         Attributes:
2768           - Attribute:       DW_AT_low_pc
2769             Form:            DW_FORM_addr
2770           - Attribute:       DW_AT_high_pc
2771             Form:            DW_FORM_addr
2772           - Attribute:       DW_AT_name
2773             Form:            DW_FORM_strp
2774       - Code:            0x00000002
2775         Tag:             DW_TAG_subprogram
2776         Children:        DW_CHILDREN_no
2777         Attributes:
2778           - Attribute:       DW_AT_name
2779             Form:            DW_FORM_strp
2780           - Attribute:       DW_AT_low_pc
2781             Form:            DW_FORM_addr
2782           - Attribute:       DW_AT_high_pc
2783             Form:            DW_FORM_addr
2784     debug_info:
2785       - Length:
2786           TotalLength:     71
2787         Version:         4
2788         AbbrOffset:      0
2789         AddrSize:        8
2790         Entries:
2791           - AbbrCode:        0x00000001
2792             Values:
2793               - Value:           0x0000000000001000
2794               - Value:           0x0000000000002000
2795               - Value:           0x0000000000000001
2796           - AbbrCode:        0x00000002
2797             Values:
2798               - Value:           0x000000000000000D
2799               - Value:           0x0000000000001000
2800               - Value:           0x0000000000002000
2801           - AbbrCode:        0x00000002
2802             Values:
2803               - Value:           0x0000000000000012
2804               - Value:           0x0000000000002000
2805               - Value:           0x0000000000002000
2806           - AbbrCode:        0x00000000
2807             Values:
2808   )";
2809   auto ErrOrSections = DWARFYAML::EmitDebugSections(yamldata);
2810   ASSERT_TRUE((bool)ErrOrSections);
2811   std::unique_ptr<DWARFContext> DwarfContext =
2812       DWARFContext::create(*ErrOrSections, 8);
2813   VerifySuccess(*DwarfContext);
2814 }
2815 
TEST(DWARFDebugInfo,TestDwarfVerifyNestedFunctions)2816 TEST(DWARFDebugInfo, TestDwarfVerifyNestedFunctions) {
2817   // Create a single compile unit with a nested function which is not contained
2818   // in its parent. Although LLVM doesn't generate this, it is valid accoridng
2819   // to the DWARF standard.
2820   StringRef yamldata = R"(
2821     debug_str:
2822       - ''
2823       - /tmp/main.c
2824       - main
2825       - nested
2826     debug_abbrev:
2827       - Code:            0x00000001
2828         Tag:             DW_TAG_compile_unit
2829         Children:        DW_CHILDREN_yes
2830         Attributes:
2831           - Attribute:       DW_AT_low_pc
2832             Form:            DW_FORM_addr
2833           - Attribute:       DW_AT_high_pc
2834             Form:            DW_FORM_addr
2835           - Attribute:       DW_AT_name
2836             Form:            DW_FORM_strp
2837       - Code:            0x00000002
2838         Tag:             DW_TAG_subprogram
2839         Children:        DW_CHILDREN_yes
2840         Attributes:
2841           - Attribute:       DW_AT_name
2842             Form:            DW_FORM_strp
2843           - Attribute:       DW_AT_low_pc
2844             Form:            DW_FORM_addr
2845           - Attribute:       DW_AT_high_pc
2846             Form:            DW_FORM_addr
2847     debug_info:
2848       - Length:
2849           TotalLength:     73
2850         Version:         4
2851         AbbrOffset:      0
2852         AddrSize:        8
2853         Entries:
2854           - AbbrCode:        0x00000001
2855             Values:
2856               - Value:           0x0000000000001000
2857               - Value:           0x0000000000002000
2858               - Value:           0x0000000000000001
2859           - AbbrCode:        0x00000002
2860             Values:
2861               - Value:           0x000000000000000D
2862               - Value:           0x0000000000001000
2863               - Value:           0x0000000000001500
2864           - AbbrCode:        0x00000002
2865             Values:
2866               - Value:           0x0000000000000012
2867               - Value:           0x0000000000001500
2868               - Value:           0x0000000000002000
2869           - AbbrCode:        0x00000000
2870             Values:
2871           - AbbrCode:        0x00000000
2872             Values:
2873           - AbbrCode:        0x00000000
2874             Values:
2875   )";
2876   auto ErrOrSections = DWARFYAML::EmitDebugSections(yamldata);
2877   ASSERT_TRUE((bool)ErrOrSections);
2878   std::unique_ptr<DWARFContext> DwarfContext =
2879       DWARFContext::create(*ErrOrSections, 8);
2880   VerifySuccess(*DwarfContext);
2881 }
2882 
TEST(DWARFDebugInfo,TestDwarfRangesContains)2883 TEST(DWARFDebugInfo, TestDwarfRangesContains) {
2884   DWARFAddressRange R(0x10, 0x20);
2885 
2886   //----------------------------------------------------------------------
2887   // Test ranges that start before R...
2888   //----------------------------------------------------------------------
2889   // Other range ends before start of R
2890   ASSERT_FALSE(R.contains({0x0f, 0x10}));
2891   // Other range end address is start of a R
2892   ASSERT_FALSE(R.contains({0x0f, 0x11}));
2893   // Other range end address is at and of R
2894   ASSERT_FALSE(R.contains({0x0f, 0x20}));
2895   // Other range end address is past end of R
2896   ASSERT_FALSE(R.contains({0x0f, 0x40}));
2897 
2898   //----------------------------------------------------------------------
2899   // Test ranges that start at R's start address
2900   //----------------------------------------------------------------------
2901   // Ensure empty ranges matches
2902   ASSERT_TRUE(R.contains({0x10, 0x10}));
2903   // 1 byte of Range
2904   ASSERT_TRUE(R.contains({0x10, 0x11}));
2905   // same as Range
2906   ASSERT_TRUE(R.contains({0x10, 0x20}));
2907   // 1 byte past Range
2908   ASSERT_FALSE(R.contains({0x10, 0x21}));
2909 
2910   //----------------------------------------------------------------------
2911   // Test ranges that start inside Range
2912   //----------------------------------------------------------------------
2913   // empty in range
2914   ASSERT_TRUE(R.contains({0x11, 0x11}));
2915   // all in Range
2916   ASSERT_TRUE(R.contains({0x11, 0x1f}));
2917   // ends at end of Range
2918   ASSERT_TRUE(R.contains({0x11, 0x20}));
2919   // ends past Range
2920   ASSERT_FALSE(R.contains({0x11, 0x21}));
2921 
2922   //----------------------------------------------------------------------
2923   // Test ranges that start at last bytes of Range
2924   //----------------------------------------------------------------------
2925   // ends at end of Range
2926   ASSERT_TRUE(R.contains({0x1f, 0x20}));
2927   // ends past Range
2928   ASSERT_FALSE(R.contains({0x1f, 0x21}));
2929 
2930   //----------------------------------------------------------------------
2931   // Test ranges that start after Range
2932   //----------------------------------------------------------------------
2933   // empty considered in Range
2934   ASSERT_TRUE(R.contains({0x20, 0x20}));
2935   // valid past Range
2936   ASSERT_FALSE(R.contains({0x20, 0x21}));
2937 }
2938 
TEST(DWARFDebugInfo,TestDWARFDieRangeInfoContains)2939 TEST(DWARFDebugInfo, TestDWARFDieRangeInfoContains) {
2940   DWARFVerifier::DieRangeInfo Ranges({{0x10, 0x20}, {0x30, 0x40}});
2941 
2942   ASSERT_FALSE(Ranges.contains({{{0x0f, 0x10}}}));
2943   ASSERT_FALSE(Ranges.contains({{{0x20, 0x30}}}));
2944   ASSERT_FALSE(Ranges.contains({{{0x40, 0x41}}}));
2945   ASSERT_TRUE(Ranges.contains({{{0x10, 0x20}}}));
2946   ASSERT_TRUE(Ranges.contains({{{0x11, 0x12}}}));
2947   ASSERT_TRUE(Ranges.contains({{{0x1f, 0x20}}}));
2948   ASSERT_TRUE(Ranges.contains({{{0x30, 0x40}}}));
2949   ASSERT_TRUE(Ranges.contains({{{0x31, 0x32}}}));
2950   ASSERT_TRUE(Ranges.contains({{{0x3f, 0x40}}}));
2951   ASSERT_TRUE(Ranges.contains({{{0x10, 0x20}, {0x30, 0x40}}}));
2952   ASSERT_TRUE(Ranges.contains({{{0x11, 0x12}, {0x31, 0x32}}}));
2953   ASSERT_TRUE(Ranges.contains(
2954       {{{0x11, 0x12}, {0x12, 0x13}, {0x31, 0x32}, {0x32, 0x33}}}));
2955   ASSERT_FALSE(Ranges.contains({{{0x11, 0x12},
2956                                  {0x12, 0x13},
2957                                  {0x20, 0x21},
2958                                  {0x31, 0x32},
2959                                  {0x32, 0x33}}}));
2960   ASSERT_FALSE(Ranges.contains(
2961       {{{0x11, 0x12}, {0x12, 0x13}, {0x31, 0x32}, {0x32, 0x41}}}));
2962 }
2963 
2964 namespace {
2965 
AssertRangesIntersect(const DWARFAddressRange & LHS,const DWARFAddressRange & RHS)2966 void AssertRangesIntersect(const DWARFAddressRange &LHS,
2967                            const DWARFAddressRange &RHS) {
2968   ASSERT_TRUE(LHS.intersects(RHS));
2969   ASSERT_TRUE(RHS.intersects(LHS));
2970 }
AssertRangesDontIntersect(const DWARFAddressRange & LHS,const DWARFAddressRange & RHS)2971 void AssertRangesDontIntersect(const DWARFAddressRange &LHS,
2972                                const DWARFAddressRange &RHS) {
2973   ASSERT_FALSE(LHS.intersects(RHS));
2974   ASSERT_FALSE(RHS.intersects(LHS));
2975 }
2976 
AssertRangesIntersect(const DWARFVerifier::DieRangeInfo & LHS,const DWARFAddressRangesVector & Ranges)2977 void AssertRangesIntersect(const DWARFVerifier::DieRangeInfo &LHS,
2978                            const DWARFAddressRangesVector &Ranges) {
2979   DWARFVerifier::DieRangeInfo RHS(Ranges);
2980   ASSERT_TRUE(LHS.intersects(RHS));
2981   ASSERT_TRUE(RHS.intersects(LHS));
2982 }
2983 
AssertRangesDontIntersect(const DWARFVerifier::DieRangeInfo & LHS,const DWARFAddressRangesVector & Ranges)2984 void AssertRangesDontIntersect(const DWARFVerifier::DieRangeInfo &LHS,
2985                                const DWARFAddressRangesVector &Ranges) {
2986   DWARFVerifier::DieRangeInfo RHS(Ranges);
2987   ASSERT_FALSE(LHS.intersects(RHS));
2988   ASSERT_FALSE(RHS.intersects(LHS));
2989 }
2990 
2991 } // namespace
TEST(DWARFDebugInfo,TestDwarfRangesIntersect)2992 TEST(DWARFDebugInfo, TestDwarfRangesIntersect) {
2993   DWARFAddressRange R(0x10, 0x20);
2994 
2995   //----------------------------------------------------------------------
2996   // Test ranges that start before R...
2997   //----------------------------------------------------------------------
2998   // Other range ends before start of R
2999   AssertRangesDontIntersect(R, {0x00, 0x10});
3000   // Other range end address is start of a R
3001   AssertRangesIntersect(R, {0x00, 0x11});
3002   // Other range end address is in R
3003   AssertRangesIntersect(R, {0x00, 0x15});
3004   // Other range end address is at and of R
3005   AssertRangesIntersect(R, {0x00, 0x20});
3006   // Other range end address is past end of R
3007   AssertRangesIntersect(R, {0x00, 0x40});
3008 
3009   //----------------------------------------------------------------------
3010   // Test ranges that start at R's start address
3011   //----------------------------------------------------------------------
3012   // Ensure empty ranges doesn't match
3013   AssertRangesDontIntersect(R, {0x10, 0x10});
3014   // 1 byte of Range
3015   AssertRangesIntersect(R, {0x10, 0x11});
3016   // same as Range
3017   AssertRangesIntersect(R, {0x10, 0x20});
3018   // 1 byte past Range
3019   AssertRangesIntersect(R, {0x10, 0x21});
3020 
3021   //----------------------------------------------------------------------
3022   // Test ranges that start inside Range
3023   //----------------------------------------------------------------------
3024   // empty in range
3025   AssertRangesDontIntersect(R, {0x11, 0x11});
3026   // all in Range
3027   AssertRangesIntersect(R, {0x11, 0x1f});
3028   // ends at end of Range
3029   AssertRangesIntersect(R, {0x11, 0x20});
3030   // ends past Range
3031   AssertRangesIntersect(R, {0x11, 0x21});
3032 
3033   //----------------------------------------------------------------------
3034   // Test ranges that start at last bytes of Range
3035   //----------------------------------------------------------------------
3036   // ends at end of Range
3037   AssertRangesIntersect(R, {0x1f, 0x20});
3038   // ends past Range
3039   AssertRangesIntersect(R, {0x1f, 0x21});
3040 
3041   //----------------------------------------------------------------------
3042   // Test ranges that start after Range
3043   //----------------------------------------------------------------------
3044   // empty just past in Range
3045   AssertRangesDontIntersect(R, {0x20, 0x20});
3046   // valid past Range
3047   AssertRangesDontIntersect(R, {0x20, 0x21});
3048 }
3049 
TEST(DWARFDebugInfo,TestDWARFDieRangeInfoIntersects)3050 TEST(DWARFDebugInfo, TestDWARFDieRangeInfoIntersects) {
3051 
3052   DWARFVerifier::DieRangeInfo Ranges({{0x10, 0x20}, {0x30, 0x40}});
3053 
3054   // Test empty range
3055   AssertRangesDontIntersect(Ranges, {});
3056   // Test range that appears before all ranges in Ranges
3057   AssertRangesDontIntersect(Ranges, {{0x00, 0x10}});
3058   // Test range that appears between ranges in Ranges
3059   AssertRangesDontIntersect(Ranges, {{0x20, 0x30}});
3060   // Test range that appears after ranges in Ranges
3061   AssertRangesDontIntersect(Ranges, {{0x40, 0x50}});
3062 
3063   // Test range that start before first range
3064   AssertRangesIntersect(Ranges, {{0x00, 0x11}});
3065   // Test range that start at first range
3066   AssertRangesIntersect(Ranges, {{0x10, 0x11}});
3067   // Test range that start in first range
3068   AssertRangesIntersect(Ranges, {{0x11, 0x12}});
3069   // Test range that start at end of first range
3070   AssertRangesIntersect(Ranges, {{0x1f, 0x20}});
3071   // Test range that starts at end of first range
3072   AssertRangesDontIntersect(Ranges, {{0x20, 0x21}});
3073   // Test range that starts at end of first range
3074   AssertRangesIntersect(Ranges, {{0x20, 0x31}});
3075 
3076   // Test range that start before second range and ends before second
3077   AssertRangesDontIntersect(Ranges, {{0x2f, 0x30}});
3078   // Test range that start before second range and ends in second
3079   AssertRangesIntersect(Ranges, {{0x2f, 0x31}});
3080   // Test range that start at second range
3081   AssertRangesIntersect(Ranges, {{0x30, 0x31}});
3082   // Test range that start in second range
3083   AssertRangesIntersect(Ranges, {{0x31, 0x32}});
3084   // Test range that start at end of second range
3085   AssertRangesIntersect(Ranges, {{0x3f, 0x40}});
3086   // Test range that starts at end of second range
3087   AssertRangesDontIntersect(Ranges, {{0x40, 0x41}});
3088 }
3089 
3090 } // end anonymous namespace
3091