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