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