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