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