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