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