1 //===- llvm/unittest/DebugInfo/DWARFFormValueTest.cpp ---------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "DwarfGenerator.h"
11 #include "llvm/ADT/ArrayRef.h"
12 #include "llvm/ADT/Optional.h"
13 #include "llvm/ADT/SmallString.h"
14 #include "llvm/ADT/StringRef.h"
15 #include "llvm/ADT/Triple.h"
16 #include "llvm/BinaryFormat/Dwarf.h"
17 #include "llvm/Config/llvm-config.h"
18 #include "llvm/CodeGen/AsmPrinter.h"
19 #include "llvm/DebugInfo/DWARF/DWARFCompileUnit.h"
20 #include "llvm/DebugInfo/DWARF/DWARFContext.h"
21 #include "llvm/DebugInfo/DWARF/DWARFDie.h"
22 #include "llvm/DebugInfo/DWARF/DWARFFormValue.h"
23 #include "llvm/MC/MCContext.h"
24 #include "llvm/MC/MCSectionELF.h"
25 #include "llvm/MC/MCStreamer.h"
26 #include "llvm/Object/ObjectFile.h"
27 #include "llvm/ObjectYAML/DWARFEmitter.h"
28 #include "llvm/ObjectYAML/DWARFYAML.h"
29 #include "llvm/Support/Error.h"
30 #include "llvm/Support/MemoryBuffer.h"
31 #include "llvm/Support/TargetSelect.h"
32 #include "llvm/Support/TargetRegistry.h"
33 #include "llvm/Testing/Support/Error.h"
34 #include "gtest/gtest.h"
35 #include <climits>
36 #include <cstdint>
37 #include <cstring>
38 #include <string>
39 
40 using namespace llvm;
41 using namespace dwarf;
42 
43 namespace {
44 
45 void initLLVMIfNeeded() {
46   static bool gInitialized = false;
47   if (!gInitialized) {
48     gInitialized = true;
49     InitializeAllTargets();
50     InitializeAllTargetMCs();
51     InitializeAllAsmPrinters();
52     InitializeAllAsmParsers();
53   }
54 }
55 
56 Triple getHostTripleForAddrSize(uint8_t AddrSize) {
57   Triple PT(Triple::normalize(LLVM_HOST_TRIPLE));
58 
59   if (AddrSize == 8 && PT.isArch32Bit())
60     return PT.get64BitArchVariant();
61   if (AddrSize == 4 && PT.isArch64Bit())
62     return PT.get32BitArchVariant();
63   return PT;
64 }
65 
66 static bool isConfigurationSupported(Triple &T) {
67   initLLVMIfNeeded();
68   std::string Err;
69   return TargetRegistry::lookupTarget(T.getTriple(), Err);
70 }
71 
72 template <uint16_t Version, class AddrType, class RefAddrType>
73 void TestAllForms() {
74   Triple Triple = getHostTripleForAddrSize(sizeof(AddrType));
75   if (!isConfigurationSupported(Triple))
76     return;
77 
78   // Test that we can decode all DW_FORM values correctly.
79   const AddrType AddrValue = (AddrType)0x0123456789abcdefULL;
80   const uint8_t BlockData[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
81   const uint32_t BlockSize = sizeof(BlockData);
82   const RefAddrType RefAddr = 0x12345678;
83   const uint8_t Data1 = 0x01U;
84   const uint16_t Data2 = 0x2345U;
85   const uint32_t Data4 = 0x6789abcdU;
86   const uint64_t Data8 = 0x0011223344556677ULL;
87   const uint64_t Data8_2 = 0xAABBCCDDEEFF0011ULL;
88   const int64_t SData = INT64_MIN;
89   const int64_t ICSData = INT64_MAX; // DW_FORM_implicit_const SData
90   const uint64_t UData[] = {UINT64_MAX - 1, UINT64_MAX - 2, UINT64_MAX - 3,
91                             UINT64_MAX - 4, UINT64_MAX - 5, UINT64_MAX - 6,
92                             UINT64_MAX - 7, UINT64_MAX - 8, UINT64_MAX - 9};
93 #define UDATA_1 18446744073709551614ULL
94   const uint32_t Dwarf32Values[] = {1, 2, 3, 4, 5, 6, 7, 8};
95   const char *StringValue = "Hello";
96   const char *StrpValue = "World";
97 
98   auto ExpectedDG = dwarfgen::Generator::create(Triple, Version);
99   ASSERT_THAT_EXPECTED(ExpectedDG, Succeeded());
100   dwarfgen::Generator *DG = ExpectedDG.get().get();
101   dwarfgen::CompileUnit &CU = DG->addCompileUnit();
102   dwarfgen::DIE CUDie = CU.getUnitDIE();
103   uint16_t Attr = DW_AT_lo_user;
104 
105   //----------------------------------------------------------------------
106   // Test address forms
107   //----------------------------------------------------------------------
108   const auto Attr_DW_FORM_addr = static_cast<dwarf::Attribute>(Attr++);
109   CUDie.addAttribute(Attr_DW_FORM_addr, DW_FORM_addr, AddrValue);
110 
111   //----------------------------------------------------------------------
112   // Test block forms
113   //----------------------------------------------------------------------
114   const auto Attr_DW_FORM_block = static_cast<dwarf::Attribute>(Attr++);
115   CUDie.addAttribute(Attr_DW_FORM_block, DW_FORM_block, BlockData, BlockSize);
116 
117   const auto Attr_DW_FORM_block1 = static_cast<dwarf::Attribute>(Attr++);
118   CUDie.addAttribute(Attr_DW_FORM_block1, DW_FORM_block1, BlockData, BlockSize);
119 
120   const auto Attr_DW_FORM_block2 = static_cast<dwarf::Attribute>(Attr++);
121   CUDie.addAttribute(Attr_DW_FORM_block2, DW_FORM_block2, BlockData, BlockSize);
122 
123   const auto Attr_DW_FORM_block4 = static_cast<dwarf::Attribute>(Attr++);
124   CUDie.addAttribute(Attr_DW_FORM_block4, DW_FORM_block4, BlockData, BlockSize);
125 
126   //----------------------------------------------------------------------
127   // Test data forms
128   //----------------------------------------------------------------------
129   const auto Attr_DW_FORM_data1 = static_cast<dwarf::Attribute>(Attr++);
130   CUDie.addAttribute(Attr_DW_FORM_data1, DW_FORM_data1, Data1);
131 
132   const auto Attr_DW_FORM_data2 = static_cast<dwarf::Attribute>(Attr++);
133   CUDie.addAttribute(Attr_DW_FORM_data2, DW_FORM_data2, Data2);
134 
135   const auto Attr_DW_FORM_data4 = static_cast<dwarf::Attribute>(Attr++);
136   CUDie.addAttribute(Attr_DW_FORM_data4, DW_FORM_data4, Data4);
137 
138   const auto Attr_DW_FORM_data8 = static_cast<dwarf::Attribute>(Attr++);
139   CUDie.addAttribute(Attr_DW_FORM_data8, DW_FORM_data8, Data8);
140 
141   //----------------------------------------------------------------------
142   // Test string forms
143   //----------------------------------------------------------------------
144   const auto Attr_DW_FORM_string = static_cast<dwarf::Attribute>(Attr++);
145   CUDie.addAttribute(Attr_DW_FORM_string, DW_FORM_string, StringValue);
146 
147   const auto Attr_DW_FORM_strp = static_cast<dwarf::Attribute>(Attr++);
148   CUDie.addAttribute(Attr_DW_FORM_strp, DW_FORM_strp, StrpValue);
149 
150   //----------------------------------------------------------------------
151   // Test reference forms
152   //----------------------------------------------------------------------
153   const auto Attr_DW_FORM_ref_addr = static_cast<dwarf::Attribute>(Attr++);
154   CUDie.addAttribute(Attr_DW_FORM_ref_addr, DW_FORM_ref_addr, RefAddr);
155 
156   const auto Attr_DW_FORM_ref1 = static_cast<dwarf::Attribute>(Attr++);
157   CUDie.addAttribute(Attr_DW_FORM_ref1, DW_FORM_ref1, Data1);
158 
159   const auto Attr_DW_FORM_ref2 = static_cast<dwarf::Attribute>(Attr++);
160   CUDie.addAttribute(Attr_DW_FORM_ref2, DW_FORM_ref2, Data2);
161 
162   const auto Attr_DW_FORM_ref4 = static_cast<dwarf::Attribute>(Attr++);
163   CUDie.addAttribute(Attr_DW_FORM_ref4, DW_FORM_ref4, Data4);
164 
165   const auto Attr_DW_FORM_ref8 = static_cast<dwarf::Attribute>(Attr++);
166   CUDie.addAttribute(Attr_DW_FORM_ref8, DW_FORM_ref8, Data8);
167 
168   const auto Attr_DW_FORM_ref_sig8 = static_cast<dwarf::Attribute>(Attr++);
169   if (Version >= 4)
170     CUDie.addAttribute(Attr_DW_FORM_ref_sig8, DW_FORM_ref_sig8, Data8_2);
171 
172   const auto Attr_DW_FORM_ref_udata = static_cast<dwarf::Attribute>(Attr++);
173   CUDie.addAttribute(Attr_DW_FORM_ref_udata, DW_FORM_ref_udata, UData[0]);
174 
175   //----------------------------------------------------------------------
176   // Test flag forms
177   //----------------------------------------------------------------------
178   const auto Attr_DW_FORM_flag_true = static_cast<dwarf::Attribute>(Attr++);
179   CUDie.addAttribute(Attr_DW_FORM_flag_true, DW_FORM_flag, true);
180 
181   const auto Attr_DW_FORM_flag_false = static_cast<dwarf::Attribute>(Attr++);
182   CUDie.addAttribute(Attr_DW_FORM_flag_false, DW_FORM_flag, false);
183 
184   const auto Attr_DW_FORM_flag_present = static_cast<dwarf::Attribute>(Attr++);
185   if (Version >= 4)
186     CUDie.addAttribute(Attr_DW_FORM_flag_present, DW_FORM_flag_present);
187 
188   //----------------------------------------------------------------------
189   // Test SLEB128 based forms
190   //----------------------------------------------------------------------
191   const auto Attr_DW_FORM_sdata = static_cast<dwarf::Attribute>(Attr++);
192   CUDie.addAttribute(Attr_DW_FORM_sdata, DW_FORM_sdata, SData);
193 
194   const auto Attr_DW_FORM_implicit_const =
195     static_cast<dwarf::Attribute>(Attr++);
196   if (Version >= 5)
197     CUDie.addAttribute(Attr_DW_FORM_implicit_const, DW_FORM_implicit_const,
198                        ICSData);
199 
200   //----------------------------------------------------------------------
201   // Test ULEB128 based forms
202   //----------------------------------------------------------------------
203   const auto Attr_DW_FORM_udata = static_cast<dwarf::Attribute>(Attr++);
204   CUDie.addAttribute(Attr_DW_FORM_udata, DW_FORM_udata, UData[0]);
205 
206   //----------------------------------------------------------------------
207   // Test DWARF32/DWARF64 forms
208   //----------------------------------------------------------------------
209   const auto Attr_DW_FORM_GNU_ref_alt = static_cast<dwarf::Attribute>(Attr++);
210   CUDie.addAttribute(Attr_DW_FORM_GNU_ref_alt, DW_FORM_GNU_ref_alt,
211                      Dwarf32Values[0]);
212 
213   const auto Attr_DW_FORM_sec_offset = static_cast<dwarf::Attribute>(Attr++);
214   if (Version >= 4)
215     CUDie.addAttribute(Attr_DW_FORM_sec_offset, DW_FORM_sec_offset,
216                        Dwarf32Values[1]);
217 
218   //----------------------------------------------------------------------
219   // Add an address at the end to make sure we can decode this value
220   //----------------------------------------------------------------------
221   const auto Attr_Last = static_cast<dwarf::Attribute>(Attr++);
222   CUDie.addAttribute(Attr_Last, DW_FORM_addr, AddrValue);
223 
224   //----------------------------------------------------------------------
225   // Generate the DWARF
226   //----------------------------------------------------------------------
227   StringRef FileBytes = DG->generate();
228   MemoryBufferRef FileBuffer(FileBytes, "dwarf");
229   auto Obj = object::ObjectFile::createObjectFile(FileBuffer);
230   EXPECT_TRUE((bool)Obj);
231   DWARFContextInMemory DwarfContext(*Obj.get());
232   uint32_t NumCUs = DwarfContext.getNumCompileUnits();
233   EXPECT_EQ(NumCUs, 1u);
234   DWARFCompileUnit *U = DwarfContext.getCompileUnitAtIndex(0);
235   auto DieDG = U->getUnitDIE(false);
236   EXPECT_TRUE(DieDG.isValid());
237 
238   //----------------------------------------------------------------------
239   // Test address forms
240   //----------------------------------------------------------------------
241   EXPECT_EQ(AddrValue, toAddress(DieDG.find(Attr_DW_FORM_addr), 0));
242 
243   //----------------------------------------------------------------------
244   // Test block forms
245   //----------------------------------------------------------------------
246   Optional<DWARFFormValue> FormValue;
247   ArrayRef<uint8_t> ExtractedBlockData;
248   Optional<ArrayRef<uint8_t>> BlockDataOpt;
249 
250   FormValue = DieDG.find(Attr_DW_FORM_block);
251   EXPECT_TRUE((bool)FormValue);
252   BlockDataOpt = FormValue->getAsBlock();
253   EXPECT_TRUE(BlockDataOpt.hasValue());
254   ExtractedBlockData = BlockDataOpt.getValue();
255   EXPECT_EQ(ExtractedBlockData.size(), BlockSize);
256   EXPECT_TRUE(memcmp(ExtractedBlockData.data(), BlockData, BlockSize) == 0);
257 
258   FormValue = DieDG.find(Attr_DW_FORM_block1);
259   EXPECT_TRUE((bool)FormValue);
260   BlockDataOpt = FormValue->getAsBlock();
261   EXPECT_TRUE(BlockDataOpt.hasValue());
262   ExtractedBlockData = BlockDataOpt.getValue();
263   EXPECT_EQ(ExtractedBlockData.size(), BlockSize);
264   EXPECT_TRUE(memcmp(ExtractedBlockData.data(), BlockData, BlockSize) == 0);
265 
266   FormValue = DieDG.find(Attr_DW_FORM_block2);
267   EXPECT_TRUE((bool)FormValue);
268   BlockDataOpt = FormValue->getAsBlock();
269   EXPECT_TRUE(BlockDataOpt.hasValue());
270   ExtractedBlockData = BlockDataOpt.getValue();
271   EXPECT_EQ(ExtractedBlockData.size(), BlockSize);
272   EXPECT_TRUE(memcmp(ExtractedBlockData.data(), BlockData, BlockSize) == 0);
273 
274   FormValue = DieDG.find(Attr_DW_FORM_block4);
275   EXPECT_TRUE((bool)FormValue);
276   BlockDataOpt = FormValue->getAsBlock();
277   EXPECT_TRUE(BlockDataOpt.hasValue());
278   ExtractedBlockData = BlockDataOpt.getValue();
279   EXPECT_EQ(ExtractedBlockData.size(), BlockSize);
280   EXPECT_TRUE(memcmp(ExtractedBlockData.data(), BlockData, BlockSize) == 0);
281 
282   //----------------------------------------------------------------------
283   // Test data forms
284   //----------------------------------------------------------------------
285   EXPECT_EQ(Data1, toUnsigned(DieDG.find(Attr_DW_FORM_data1), 0));
286   EXPECT_EQ(Data2, toUnsigned(DieDG.find(Attr_DW_FORM_data2), 0));
287   EXPECT_EQ(Data4, toUnsigned(DieDG.find(Attr_DW_FORM_data4), 0));
288   EXPECT_EQ(Data8, toUnsigned(DieDG.find(Attr_DW_FORM_data8), 0));
289 
290   //----------------------------------------------------------------------
291   // Test string forms
292   //----------------------------------------------------------------------
293   auto ExtractedStringValue = toString(DieDG.find(Attr_DW_FORM_string));
294   EXPECT_TRUE((bool)ExtractedStringValue);
295   EXPECT_TRUE(strcmp(StringValue, *ExtractedStringValue) == 0);
296 
297   auto ExtractedStrpValue = toString(DieDG.find(Attr_DW_FORM_strp));
298   EXPECT_TRUE((bool)ExtractedStrpValue);
299   EXPECT_TRUE(strcmp(StrpValue, *ExtractedStrpValue) == 0);
300 
301   //----------------------------------------------------------------------
302   // Test reference forms
303   //----------------------------------------------------------------------
304   EXPECT_EQ(RefAddr, toReference(DieDG.find(Attr_DW_FORM_ref_addr), 0));
305   EXPECT_EQ(Data1, toReference(DieDG.find(Attr_DW_FORM_ref1), 0));
306   EXPECT_EQ(Data2, toReference(DieDG.find(Attr_DW_FORM_ref2), 0));
307   EXPECT_EQ(Data4, toReference(DieDG.find(Attr_DW_FORM_ref4), 0));
308   EXPECT_EQ(Data8, toReference(DieDG.find(Attr_DW_FORM_ref8), 0));
309   if (Version >= 4) {
310     EXPECT_EQ(Data8_2, toReference(DieDG.find(Attr_DW_FORM_ref_sig8), 0));
311   }
312   EXPECT_EQ(UData[0], toReference(DieDG.find(Attr_DW_FORM_ref_udata), 0));
313 
314   //----------------------------------------------------------------------
315   // Test flag forms
316   //----------------------------------------------------------------------
317   EXPECT_EQ(1ULL, toUnsigned(DieDG.find(Attr_DW_FORM_flag_true), 0));
318   EXPECT_EQ(0ULL, toUnsigned(DieDG.find(Attr_DW_FORM_flag_false), 1));
319   if (Version >= 4) {
320     EXPECT_EQ(1ULL, toUnsigned(DieDG.find(Attr_DW_FORM_flag_present), 0));
321   }
322 
323   //----------------------------------------------------------------------
324   // Test SLEB128 based forms
325   //----------------------------------------------------------------------
326   EXPECT_EQ(SData, toSigned(DieDG.find(Attr_DW_FORM_sdata), 0));
327   if (Version >= 5) {
328     EXPECT_EQ(ICSData, toSigned(DieDG.find(Attr_DW_FORM_implicit_const), 0));
329   }
330 
331   //----------------------------------------------------------------------
332   // Test ULEB128 based forms
333   //----------------------------------------------------------------------
334   EXPECT_EQ(UData[0], toUnsigned(DieDG.find(Attr_DW_FORM_udata), 0));
335 
336   //----------------------------------------------------------------------
337   // Test DWARF32/DWARF64 forms
338   //----------------------------------------------------------------------
339   EXPECT_EQ(Dwarf32Values[0],
340             toReference(DieDG.find(Attr_DW_FORM_GNU_ref_alt), 0));
341   if (Version >= 4) {
342     EXPECT_EQ(Dwarf32Values[1],
343               toSectionOffset(DieDG.find(Attr_DW_FORM_sec_offset), 0));
344   }
345 
346   //----------------------------------------------------------------------
347   // Add an address at the end to make sure we can decode this value
348   //----------------------------------------------------------------------
349   EXPECT_EQ(AddrValue, toAddress(DieDG.find(Attr_Last), 0));
350 }
351 
352 TEST(DWARFDebugInfo, TestDWARF32Version2Addr4AllForms) {
353   // Test that we can decode all forms for DWARF32, version 2, with 4 byte
354   // addresses.
355   typedef uint32_t AddrType;
356   // DW_FORM_ref_addr are the same as the address type in DWARF32 version 2.
357   typedef AddrType RefAddrType;
358   TestAllForms<2, AddrType, RefAddrType>();
359 }
360 
361 TEST(DWARFDebugInfo, TestDWARF32Version2Addr8AllForms) {
362   // Test that we can decode all forms for DWARF32, version 2, with 4 byte
363   // addresses.
364   typedef uint64_t AddrType;
365   // DW_FORM_ref_addr are the same as the address type in DWARF32 version 2.
366   typedef AddrType RefAddrType;
367   TestAllForms<2, AddrType, RefAddrType>();
368 }
369 
370 TEST(DWARFDebugInfo, TestDWARF32Version3Addr4AllForms) {
371   // Test that we can decode all forms for DWARF32, version 3, with 4 byte
372   // addresses.
373   typedef uint32_t AddrType;
374   // DW_FORM_ref_addr are 4 bytes in DWARF32 for version 3 and later.
375   typedef uint32_t RefAddrType;
376   TestAllForms<3, AddrType, RefAddrType>();
377 }
378 
379 TEST(DWARFDebugInfo, TestDWARF32Version3Addr8AllForms) {
380   // Test that we can decode all forms for DWARF32, version 3, with 8 byte
381   // addresses.
382   typedef uint64_t AddrType;
383   // DW_FORM_ref_addr are 4 bytes in DWARF32 for version 3 and later
384   typedef uint32_t RefAddrType;
385   TestAllForms<3, AddrType, RefAddrType>();
386 }
387 
388 TEST(DWARFDebugInfo, TestDWARF32Version4Addr4AllForms) {
389   // Test that we can decode all forms for DWARF32, version 4, with 4 byte
390   // addresses.
391   typedef uint32_t AddrType;
392   // DW_FORM_ref_addr are 4 bytes in DWARF32 for version 3 and later
393   typedef uint32_t RefAddrType;
394   TestAllForms<4, AddrType, RefAddrType>();
395 }
396 
397 TEST(DWARFDebugInfo, TestDWARF32Version4Addr8AllForms) {
398   // Test that we can decode all forms for DWARF32, version 4, with 8 byte
399   // addresses.
400   typedef uint64_t AddrType;
401   // DW_FORM_ref_addr are 4 bytes in DWARF32 for version 3 and later
402   typedef uint32_t RefAddrType;
403   TestAllForms<4, AddrType, RefAddrType>();
404 }
405 
406 TEST(DWARFDebugInfo, TestDWARF32Version5Addr4AllForms) {
407   // Test that we can decode all forms for DWARF32, version 5, with 4 byte
408   // addresses.
409   typedef uint32_t AddrType;
410   // DW_FORM_ref_addr are 4 bytes in DWARF32 for version 3 and later
411   typedef uint32_t RefAddrType;
412   TestAllForms<5, AddrType, RefAddrType>();
413 }
414 
415 TEST(DWARFDebugInfo, TestDWARF32Version5Addr8AllForms) {
416   // Test that we can decode all forms for DWARF32, version 5, with 8 byte
417   // addresses.
418   typedef uint64_t AddrType;
419   // DW_FORM_ref_addr are 4 bytes in DWARF32 for version 3 and later
420   typedef uint32_t RefAddrType;
421   TestAllForms<5, AddrType, RefAddrType>();
422 }
423 
424 template <uint16_t Version, class AddrType> void TestChildren() {
425   Triple Triple = getHostTripleForAddrSize(sizeof(AddrType));
426   if (!isConfigurationSupported(Triple))
427     return;
428 
429   // Test that we can decode DW_FORM_ref_addr values correctly in DWARF 2 with
430   // 4 byte addresses. DW_FORM_ref_addr values should be 4 bytes when using
431   // 8 byte addresses.
432 
433   auto ExpectedDG = dwarfgen::Generator::create(Triple, Version);
434   ASSERT_THAT_EXPECTED(ExpectedDG, Succeeded());
435   dwarfgen::Generator *DG = ExpectedDG.get().get();
436   dwarfgen::CompileUnit &CU = DG->addCompileUnit();
437   dwarfgen::DIE CUDie = CU.getUnitDIE();
438 
439   CUDie.addAttribute(DW_AT_name, DW_FORM_strp, "/tmp/main.c");
440   CUDie.addAttribute(DW_AT_language, DW_FORM_data2, DW_LANG_C);
441 
442   dwarfgen::DIE SubprogramDie = CUDie.addChild(DW_TAG_subprogram);
443   SubprogramDie.addAttribute(DW_AT_name, DW_FORM_strp, "main");
444   SubprogramDie.addAttribute(DW_AT_low_pc, DW_FORM_addr, 0x1000U);
445   SubprogramDie.addAttribute(DW_AT_high_pc, DW_FORM_addr, 0x2000U);
446 
447   dwarfgen::DIE IntDie = CUDie.addChild(DW_TAG_base_type);
448   IntDie.addAttribute(DW_AT_name, DW_FORM_strp, "int");
449   IntDie.addAttribute(DW_AT_encoding, DW_FORM_data1, DW_ATE_signed);
450   IntDie.addAttribute(DW_AT_byte_size, DW_FORM_data1, 4);
451 
452   dwarfgen::DIE ArgcDie = SubprogramDie.addChild(DW_TAG_formal_parameter);
453   ArgcDie.addAttribute(DW_AT_name, DW_FORM_strp, "argc");
454   // ArgcDie.addAttribute(DW_AT_type, DW_FORM_ref4, IntDie);
455   ArgcDie.addAttribute(DW_AT_type, DW_FORM_ref_addr, IntDie);
456 
457   StringRef FileBytes = DG->generate();
458   MemoryBufferRef FileBuffer(FileBytes, "dwarf");
459   auto Obj = object::ObjectFile::createObjectFile(FileBuffer);
460   EXPECT_TRUE((bool)Obj);
461   DWARFContextInMemory DwarfContext(*Obj.get());
462 
463   // Verify the number of compile units is correct.
464   uint32_t NumCUs = DwarfContext.getNumCompileUnits();
465   EXPECT_EQ(NumCUs, 1u);
466   DWARFCompileUnit *U = DwarfContext.getCompileUnitAtIndex(0);
467 
468   // Get the compile unit DIE is valid.
469   auto DieDG = U->getUnitDIE(false);
470   EXPECT_TRUE(DieDG.isValid());
471 
472   // Verify the first child of the compile unit DIE is our subprogram.
473   auto SubprogramDieDG = DieDG.getFirstChild();
474   EXPECT_TRUE(SubprogramDieDG.isValid());
475   EXPECT_EQ(SubprogramDieDG.getTag(), DW_TAG_subprogram);
476 
477   // Verify the first child of the subprogram is our formal parameter.
478   auto ArgcDieDG = SubprogramDieDG.getFirstChild();
479   EXPECT_TRUE(ArgcDieDG.isValid());
480   EXPECT_EQ(ArgcDieDG.getTag(), DW_TAG_formal_parameter);
481 
482   // Verify our formal parameter has a NULL tag sibling.
483   auto NullDieDG = ArgcDieDG.getSibling();
484   EXPECT_TRUE(NullDieDG.isValid());
485   if (NullDieDG) {
486     EXPECT_EQ(NullDieDG.getTag(), DW_TAG_null);
487     EXPECT_TRUE(!NullDieDG.getSibling().isValid());
488     EXPECT_TRUE(!NullDieDG.getFirstChild().isValid());
489   }
490 
491   // Verify the sibling of our subprogram is our integer base type.
492   auto IntDieDG = SubprogramDieDG.getSibling();
493   EXPECT_TRUE(IntDieDG.isValid());
494   EXPECT_EQ(IntDieDG.getTag(), DW_TAG_base_type);
495 
496   // Verify the sibling of our subprogram is our integer base is a NULL tag.
497   NullDieDG = IntDieDG.getSibling();
498   EXPECT_TRUE(NullDieDG.isValid());
499   if (NullDieDG) {
500     EXPECT_EQ(NullDieDG.getTag(), DW_TAG_null);
501     EXPECT_TRUE(!NullDieDG.getSibling().isValid());
502     EXPECT_TRUE(!NullDieDG.getFirstChild().isValid());
503   }
504 }
505 
506 TEST(DWARFDebugInfo, TestDWARF32Version2Addr4Children) {
507   // Test that we can decode all forms for DWARF32, version 2, with 4 byte
508   // addresses.
509   typedef uint32_t AddrType;
510   TestChildren<2, AddrType>();
511 }
512 
513 TEST(DWARFDebugInfo, TestDWARF32Version2Addr8Children) {
514   // Test that we can decode all forms for DWARF32, version 2, with 8 byte
515   // addresses.
516   typedef uint64_t AddrType;
517   TestChildren<2, AddrType>();
518 }
519 
520 TEST(DWARFDebugInfo, TestDWARF32Version3Addr4Children) {
521   // Test that we can decode all forms for DWARF32, version 3, with 4 byte
522   // addresses.
523   typedef uint32_t AddrType;
524   TestChildren<3, AddrType>();
525 }
526 
527 TEST(DWARFDebugInfo, TestDWARF32Version3Addr8Children) {
528   // Test that we can decode all forms for DWARF32, version 3, with 8 byte
529   // addresses.
530   typedef uint64_t AddrType;
531   TestChildren<3, AddrType>();
532 }
533 
534 TEST(DWARFDebugInfo, TestDWARF32Version4Addr4Children) {
535   // Test that we can decode all forms for DWARF32, version 4, with 4 byte
536   // addresses.
537   typedef uint32_t AddrType;
538   TestChildren<4, AddrType>();
539 }
540 
541 TEST(DWARFDebugInfo, TestDWARF32Version4Addr8Children) {
542   // Test that we can decode all forms for DWARF32, version 4, with 8 byte
543   // addresses.
544   typedef uint64_t AddrType;
545   TestChildren<4, AddrType>();
546 }
547 
548 template <uint16_t Version, class AddrType> void TestReferences() {
549   Triple Triple = getHostTripleForAddrSize(sizeof(AddrType));
550   if (!isConfigurationSupported(Triple))
551     return;
552 
553   // Test that we can decode DW_FORM_refXXX values correctly in DWARF.
554   auto ExpectedDG = dwarfgen::Generator::create(Triple, Version);
555   ASSERT_THAT_EXPECTED(ExpectedDG, Succeeded());
556   dwarfgen::Generator *DG = ExpectedDG.get().get();
557   dwarfgen::CompileUnit &CU1 = DG->addCompileUnit();
558   dwarfgen::CompileUnit &CU2 = DG->addCompileUnit();
559 
560   dwarfgen::DIE CU1Die = CU1.getUnitDIE();
561   CU1Die.addAttribute(DW_AT_name, DW_FORM_strp, "/tmp/main.c");
562   CU1Die.addAttribute(DW_AT_language, DW_FORM_data2, DW_LANG_C);
563 
564   dwarfgen::DIE CU1TypeDie = CU1Die.addChild(DW_TAG_base_type);
565   CU1TypeDie.addAttribute(DW_AT_name, DW_FORM_strp, "int");
566   CU1TypeDie.addAttribute(DW_AT_encoding, DW_FORM_data1, DW_ATE_signed);
567   CU1TypeDie.addAttribute(DW_AT_byte_size, DW_FORM_data1, 4);
568 
569   dwarfgen::DIE CU1Ref1Die = CU1Die.addChild(DW_TAG_variable);
570   CU1Ref1Die.addAttribute(DW_AT_name, DW_FORM_strp, "CU1Ref1");
571   CU1Ref1Die.addAttribute(DW_AT_type, DW_FORM_ref1, CU1TypeDie);
572 
573   dwarfgen::DIE CU1Ref2Die = CU1Die.addChild(DW_TAG_variable);
574   CU1Ref2Die.addAttribute(DW_AT_name, DW_FORM_strp, "CU1Ref2");
575   CU1Ref2Die.addAttribute(DW_AT_type, DW_FORM_ref2, CU1TypeDie);
576 
577   dwarfgen::DIE CU1Ref4Die = CU1Die.addChild(DW_TAG_variable);
578   CU1Ref4Die.addAttribute(DW_AT_name, DW_FORM_strp, "CU1Ref4");
579   CU1Ref4Die.addAttribute(DW_AT_type, DW_FORM_ref4, CU1TypeDie);
580 
581   dwarfgen::DIE CU1Ref8Die = CU1Die.addChild(DW_TAG_variable);
582   CU1Ref8Die.addAttribute(DW_AT_name, DW_FORM_strp, "CU1Ref8");
583   CU1Ref8Die.addAttribute(DW_AT_type, DW_FORM_ref8, CU1TypeDie);
584 
585   dwarfgen::DIE CU1RefAddrDie = CU1Die.addChild(DW_TAG_variable);
586   CU1RefAddrDie.addAttribute(DW_AT_name, DW_FORM_strp, "CU1RefAddr");
587   CU1RefAddrDie.addAttribute(DW_AT_type, DW_FORM_ref_addr, CU1TypeDie);
588 
589   dwarfgen::DIE CU2Die = CU2.getUnitDIE();
590   CU2Die.addAttribute(DW_AT_name, DW_FORM_strp, "/tmp/foo.c");
591   CU2Die.addAttribute(DW_AT_language, DW_FORM_data2, DW_LANG_C);
592 
593   dwarfgen::DIE CU2TypeDie = CU2Die.addChild(DW_TAG_base_type);
594   CU2TypeDie.addAttribute(DW_AT_name, DW_FORM_strp, "float");
595   CU2TypeDie.addAttribute(DW_AT_encoding, DW_FORM_data1, DW_ATE_float);
596   CU2TypeDie.addAttribute(DW_AT_byte_size, DW_FORM_data1, 4);
597 
598   dwarfgen::DIE CU2Ref1Die = CU2Die.addChild(DW_TAG_variable);
599   CU2Ref1Die.addAttribute(DW_AT_name, DW_FORM_strp, "CU2Ref1");
600   CU2Ref1Die.addAttribute(DW_AT_type, DW_FORM_ref1, CU2TypeDie);
601 
602   dwarfgen::DIE CU2Ref2Die = CU2Die.addChild(DW_TAG_variable);
603   CU2Ref2Die.addAttribute(DW_AT_name, DW_FORM_strp, "CU2Ref2");
604   CU2Ref2Die.addAttribute(DW_AT_type, DW_FORM_ref2, CU2TypeDie);
605 
606   dwarfgen::DIE CU2Ref4Die = CU2Die.addChild(DW_TAG_variable);
607   CU2Ref4Die.addAttribute(DW_AT_name, DW_FORM_strp, "CU2Ref4");
608   CU2Ref4Die.addAttribute(DW_AT_type, DW_FORM_ref4, CU2TypeDie);
609 
610   dwarfgen::DIE CU2Ref8Die = CU2Die.addChild(DW_TAG_variable);
611   CU2Ref8Die.addAttribute(DW_AT_name, DW_FORM_strp, "CU2Ref8");
612   CU2Ref8Die.addAttribute(DW_AT_type, DW_FORM_ref8, CU2TypeDie);
613 
614   dwarfgen::DIE CU2RefAddrDie = CU2Die.addChild(DW_TAG_variable);
615   CU2RefAddrDie.addAttribute(DW_AT_name, DW_FORM_strp, "CU2RefAddr");
616   CU2RefAddrDie.addAttribute(DW_AT_type, DW_FORM_ref_addr, CU2TypeDie);
617 
618   // Refer to a type in CU1 from CU2
619   dwarfgen::DIE CU2ToCU1RefAddrDie = CU2Die.addChild(DW_TAG_variable);
620   CU2ToCU1RefAddrDie.addAttribute(DW_AT_name, DW_FORM_strp, "CU2ToCU1RefAddr");
621   CU2ToCU1RefAddrDie.addAttribute(DW_AT_type, DW_FORM_ref_addr, CU1TypeDie);
622 
623   // Refer to a type in CU2 from CU1
624   dwarfgen::DIE CU1ToCU2RefAddrDie = CU1Die.addChild(DW_TAG_variable);
625   CU1ToCU2RefAddrDie.addAttribute(DW_AT_name, DW_FORM_strp, "CU1ToCU2RefAddr");
626   CU1ToCU2RefAddrDie.addAttribute(DW_AT_type, DW_FORM_ref_addr, CU2TypeDie);
627 
628   StringRef FileBytes = DG->generate();
629   MemoryBufferRef FileBuffer(FileBytes, "dwarf");
630   auto Obj = object::ObjectFile::createObjectFile(FileBuffer);
631   EXPECT_TRUE((bool)Obj);
632   DWARFContextInMemory DwarfContext(*Obj.get());
633 
634   // Verify the number of compile units is correct.
635   uint32_t NumCUs = DwarfContext.getNumCompileUnits();
636   EXPECT_EQ(NumCUs, 2u);
637   DWARFCompileUnit *U1 = DwarfContext.getCompileUnitAtIndex(0);
638   DWARFCompileUnit *U2 = DwarfContext.getCompileUnitAtIndex(1);
639 
640   // Get the compile unit DIE is valid.
641   auto Unit1DieDG = U1->getUnitDIE(false);
642   EXPECT_TRUE(Unit1DieDG.isValid());
643 
644   auto Unit2DieDG = U2->getUnitDIE(false);
645   EXPECT_TRUE(Unit2DieDG.isValid());
646 
647   // Verify the first child of the compile unit 1 DIE is our int base type.
648   auto CU1TypeDieDG = Unit1DieDG.getFirstChild();
649   EXPECT_TRUE(CU1TypeDieDG.isValid());
650   EXPECT_EQ(CU1TypeDieDG.getTag(), DW_TAG_base_type);
651   EXPECT_EQ(DW_ATE_signed, toUnsigned(CU1TypeDieDG.find(DW_AT_encoding), 0));
652 
653   // Verify the first child of the compile unit 2 DIE is our float base type.
654   auto CU2TypeDieDG = Unit2DieDG.getFirstChild();
655   EXPECT_TRUE(CU2TypeDieDG.isValid());
656   EXPECT_EQ(CU2TypeDieDG.getTag(), DW_TAG_base_type);
657   EXPECT_EQ(DW_ATE_float, toUnsigned(CU2TypeDieDG.find(DW_AT_encoding), 0));
658 
659   // Verify the sibling of the base type DIE is our Ref1 DIE and that its
660   // DW_AT_type points to our base type DIE.
661   auto CU1Ref1DieDG = CU1TypeDieDG.getSibling();
662   EXPECT_TRUE(CU1Ref1DieDG.isValid());
663   EXPECT_EQ(CU1Ref1DieDG.getTag(), DW_TAG_variable);
664   EXPECT_EQ(CU1TypeDieDG.getOffset(),
665             toReference(CU1Ref1DieDG.find(DW_AT_type), -1ULL));
666   // Verify the sibling is our Ref2 DIE and that its DW_AT_type points to our
667   // base type DIE in CU1.
668   auto CU1Ref2DieDG = CU1Ref1DieDG.getSibling();
669   EXPECT_TRUE(CU1Ref2DieDG.isValid());
670   EXPECT_EQ(CU1Ref2DieDG.getTag(), DW_TAG_variable);
671   EXPECT_EQ(CU1TypeDieDG.getOffset(),
672             toReference(CU1Ref2DieDG.find(DW_AT_type), -1ULL));
673 
674   // Verify the sibling is our Ref4 DIE and that its DW_AT_type points to our
675   // base type DIE in CU1.
676   auto CU1Ref4DieDG = CU1Ref2DieDG.getSibling();
677   EXPECT_TRUE(CU1Ref4DieDG.isValid());
678   EXPECT_EQ(CU1Ref4DieDG.getTag(), DW_TAG_variable);
679   EXPECT_EQ(CU1TypeDieDG.getOffset(),
680             toReference(CU1Ref4DieDG.find(DW_AT_type), -1ULL));
681 
682   // Verify the sibling is our Ref8 DIE and that its DW_AT_type points to our
683   // base type DIE in CU1.
684   auto CU1Ref8DieDG = CU1Ref4DieDG.getSibling();
685   EXPECT_TRUE(CU1Ref8DieDG.isValid());
686   EXPECT_EQ(CU1Ref8DieDG.getTag(), DW_TAG_variable);
687   EXPECT_EQ(CU1TypeDieDG.getOffset(),
688             toReference(CU1Ref8DieDG.find(DW_AT_type), -1ULL));
689 
690   // Verify the sibling is our RefAddr DIE and that its DW_AT_type points to our
691   // base type DIE in CU1.
692   auto CU1RefAddrDieDG = CU1Ref8DieDG.getSibling();
693   EXPECT_TRUE(CU1RefAddrDieDG.isValid());
694   EXPECT_EQ(CU1RefAddrDieDG.getTag(), DW_TAG_variable);
695   EXPECT_EQ(CU1TypeDieDG.getOffset(),
696             toReference(CU1RefAddrDieDG.find(DW_AT_type), -1ULL));
697 
698   // Verify the sibling of the Ref4 DIE is our RefAddr DIE and that its
699   // DW_AT_type points to our base type DIE.
700   auto CU1ToCU2RefAddrDieDG = CU1RefAddrDieDG.getSibling();
701   EXPECT_TRUE(CU1ToCU2RefAddrDieDG.isValid());
702   EXPECT_EQ(CU1ToCU2RefAddrDieDG.getTag(), DW_TAG_variable);
703   EXPECT_EQ(CU2TypeDieDG.getOffset(),
704             toReference(CU1ToCU2RefAddrDieDG.find(DW_AT_type), -1ULL));
705 
706   // Verify the sibling of the base type DIE is our Ref1 DIE and that its
707   // DW_AT_type points to our base type DIE.
708   auto CU2Ref1DieDG = CU2TypeDieDG.getSibling();
709   EXPECT_TRUE(CU2Ref1DieDG.isValid());
710   EXPECT_EQ(CU2Ref1DieDG.getTag(), DW_TAG_variable);
711   EXPECT_EQ(CU2TypeDieDG.getOffset(),
712             toReference(CU2Ref1DieDG.find(DW_AT_type), -1ULL));
713   // Verify the sibling is our Ref2 DIE and that its DW_AT_type points to our
714   // base type DIE in CU2.
715   auto CU2Ref2DieDG = CU2Ref1DieDG.getSibling();
716   EXPECT_TRUE(CU2Ref2DieDG.isValid());
717   EXPECT_EQ(CU2Ref2DieDG.getTag(), DW_TAG_variable);
718   EXPECT_EQ(CU2TypeDieDG.getOffset(),
719             toReference(CU2Ref2DieDG.find(DW_AT_type), -1ULL));
720 
721   // Verify the sibling is our Ref4 DIE and that its DW_AT_type points to our
722   // base type DIE in CU2.
723   auto CU2Ref4DieDG = CU2Ref2DieDG.getSibling();
724   EXPECT_TRUE(CU2Ref4DieDG.isValid());
725   EXPECT_EQ(CU2Ref4DieDG.getTag(), DW_TAG_variable);
726   EXPECT_EQ(CU2TypeDieDG.getOffset(),
727             toReference(CU2Ref4DieDG.find(DW_AT_type), -1ULL));
728 
729   // Verify the sibling is our Ref8 DIE and that its DW_AT_type points to our
730   // base type DIE in CU2.
731   auto CU2Ref8DieDG = CU2Ref4DieDG.getSibling();
732   EXPECT_TRUE(CU2Ref8DieDG.isValid());
733   EXPECT_EQ(CU2Ref8DieDG.getTag(), DW_TAG_variable);
734   EXPECT_EQ(CU2TypeDieDG.getOffset(),
735             toReference(CU2Ref8DieDG.find(DW_AT_type), -1ULL));
736 
737   // Verify the sibling is our RefAddr DIE and that its DW_AT_type points to our
738   // base type DIE in CU2.
739   auto CU2RefAddrDieDG = CU2Ref8DieDG.getSibling();
740   EXPECT_TRUE(CU2RefAddrDieDG.isValid());
741   EXPECT_EQ(CU2RefAddrDieDG.getTag(), DW_TAG_variable);
742   EXPECT_EQ(CU2TypeDieDG.getOffset(),
743             toReference(CU2RefAddrDieDG.find(DW_AT_type), -1ULL));
744 
745   // Verify the sibling of the Ref4 DIE is our RefAddr DIE and that its
746   // DW_AT_type points to our base type DIE.
747   auto CU2ToCU1RefAddrDieDG = CU2RefAddrDieDG.getSibling();
748   EXPECT_TRUE(CU2ToCU1RefAddrDieDG.isValid());
749   EXPECT_EQ(CU2ToCU1RefAddrDieDG.getTag(), DW_TAG_variable);
750   EXPECT_EQ(CU1TypeDieDG.getOffset(),
751             toReference(CU2ToCU1RefAddrDieDG.find(DW_AT_type), -1ULL));
752 }
753 
754 TEST(DWARFDebugInfo, TestDWARF32Version2Addr4References) {
755   // Test that we can decode all forms for DWARF32, version 2, with 4 byte
756   // addresses.
757   typedef uint32_t AddrType;
758   TestReferences<2, AddrType>();
759 }
760 
761 TEST(DWARFDebugInfo, TestDWARF32Version2Addr8References) {
762   // Test that we can decode all forms for DWARF32, version 2, with 8 byte
763   // addresses.
764   typedef uint64_t AddrType;
765   TestReferences<2, AddrType>();
766 }
767 
768 TEST(DWARFDebugInfo, TestDWARF32Version3Addr4References) {
769   // Test that we can decode all forms for DWARF32, version 3, with 4 byte
770   // addresses.
771   typedef uint32_t AddrType;
772   TestReferences<3, AddrType>();
773 }
774 
775 TEST(DWARFDebugInfo, TestDWARF32Version3Addr8References) {
776   // Test that we can decode all forms for DWARF32, version 3, with 8 byte
777   // addresses.
778   typedef uint64_t AddrType;
779   TestReferences<3, AddrType>();
780 }
781 
782 TEST(DWARFDebugInfo, TestDWARF32Version4Addr4References) {
783   // Test that we can decode all forms for DWARF32, version 4, with 4 byte
784   // addresses.
785   typedef uint32_t AddrType;
786   TestReferences<4, AddrType>();
787 }
788 
789 TEST(DWARFDebugInfo, TestDWARF32Version4Addr8References) {
790   // Test that we can decode all forms for DWARF32, version 4, with 8 byte
791   // addresses.
792   typedef uint64_t AddrType;
793   TestReferences<4, AddrType>();
794 }
795 
796 template <uint16_t Version, class AddrType> void TestAddresses() {
797   Triple Triple = getHostTripleForAddrSize(sizeof(AddrType));
798   if (!isConfigurationSupported(Triple))
799     return;
800 
801   // Test the DWARF APIs related to accessing the DW_AT_low_pc and
802   // DW_AT_high_pc.
803   const bool SupportsHighPCAsOffset = Version >= 4;
804   auto ExpectedDG = dwarfgen::Generator::create(Triple, Version);
805   ASSERT_THAT_EXPECTED(ExpectedDG, Succeeded());
806   dwarfgen::Generator *DG = ExpectedDG.get().get();
807   dwarfgen::CompileUnit &CU = DG->addCompileUnit();
808   dwarfgen::DIE CUDie = CU.getUnitDIE();
809 
810   CUDie.addAttribute(DW_AT_name, DW_FORM_strp, "/tmp/main.c");
811   CUDie.addAttribute(DW_AT_language, DW_FORM_data2, DW_LANG_C);
812 
813   // Create a subprogram DIE with no low or high PC.
814   dwarfgen::DIE SubprogramNoPC = CUDie.addChild(DW_TAG_subprogram);
815   SubprogramNoPC.addAttribute(DW_AT_name, DW_FORM_strp, "no_pc");
816 
817   // Create a subprogram DIE with a low PC only.
818   dwarfgen::DIE SubprogramLowPC = CUDie.addChild(DW_TAG_subprogram);
819   SubprogramLowPC.addAttribute(DW_AT_name, DW_FORM_strp, "low_pc");
820   const uint64_t ActualLowPC = 0x1000;
821   const uint64_t ActualHighPC = 0x2000;
822   const uint64_t ActualHighPCOffset = ActualHighPC - ActualLowPC;
823   SubprogramLowPC.addAttribute(DW_AT_low_pc, DW_FORM_addr, ActualLowPC);
824 
825   // Create a subprogram DIE with a low and high PC.
826   dwarfgen::DIE SubprogramLowHighPC = CUDie.addChild(DW_TAG_subprogram);
827   SubprogramLowHighPC.addAttribute(DW_AT_name, DW_FORM_strp, "low_high_pc");
828   SubprogramLowHighPC.addAttribute(DW_AT_low_pc, DW_FORM_addr, ActualLowPC);
829   // Encode the high PC as an offset from the low PC if supported.
830   if (SupportsHighPCAsOffset)
831     SubprogramLowHighPC.addAttribute(DW_AT_high_pc, DW_FORM_data4,
832                                      ActualHighPCOffset);
833   else
834     SubprogramLowHighPC.addAttribute(DW_AT_high_pc, DW_FORM_addr, ActualHighPC);
835 
836   StringRef FileBytes = DG->generate();
837   MemoryBufferRef FileBuffer(FileBytes, "dwarf");
838   auto Obj = object::ObjectFile::createObjectFile(FileBuffer);
839   EXPECT_TRUE((bool)Obj);
840   DWARFContextInMemory DwarfContext(*Obj.get());
841 
842   // Verify the number of compile units is correct.
843   uint32_t NumCUs = DwarfContext.getNumCompileUnits();
844   EXPECT_EQ(NumCUs, 1u);
845   DWARFCompileUnit *U = DwarfContext.getCompileUnitAtIndex(0);
846 
847   // Get the compile unit DIE is valid.
848   auto DieDG = U->getUnitDIE(false);
849   EXPECT_TRUE(DieDG.isValid());
850 
851   uint64_t LowPC, HighPC, SectionIndex;
852   Optional<uint64_t> OptU64;
853   // Verify the that our subprogram with no PC value fails appropriately when
854   // asked for any PC values.
855   auto SubprogramDieNoPC = DieDG.getFirstChild();
856   EXPECT_TRUE(SubprogramDieNoPC.isValid());
857   EXPECT_EQ(SubprogramDieNoPC.getTag(), DW_TAG_subprogram);
858   OptU64 = toAddress(SubprogramDieNoPC.find(DW_AT_low_pc));
859   EXPECT_FALSE((bool)OptU64);
860   OptU64 = toAddress(SubprogramDieNoPC.find(DW_AT_high_pc));
861   EXPECT_FALSE((bool)OptU64);
862   EXPECT_FALSE(SubprogramDieNoPC.getLowAndHighPC(LowPC, HighPC, SectionIndex));
863   OptU64 = toAddress(SubprogramDieNoPC.find(DW_AT_high_pc));
864   EXPECT_FALSE((bool)OptU64);
865   OptU64 = toUnsigned(SubprogramDieNoPC.find(DW_AT_high_pc));
866   EXPECT_FALSE((bool)OptU64);
867   OptU64 = SubprogramDieNoPC.getHighPC(ActualLowPC);
868   EXPECT_FALSE((bool)OptU64);
869   EXPECT_FALSE(SubprogramDieNoPC.getLowAndHighPC(LowPC, HighPC, SectionIndex));
870 
871   // Verify the that our subprogram with only a low PC value succeeds when
872   // we ask for the Low PC, but fails appropriately when asked for the high PC
873   // or both low and high PC values.
874   auto SubprogramDieLowPC = SubprogramDieNoPC.getSibling();
875   EXPECT_TRUE(SubprogramDieLowPC.isValid());
876   EXPECT_EQ(SubprogramDieLowPC.getTag(), DW_TAG_subprogram);
877   OptU64 = toAddress(SubprogramDieLowPC.find(DW_AT_low_pc));
878   EXPECT_TRUE((bool)OptU64);
879   EXPECT_EQ(OptU64.getValue(), ActualLowPC);
880   OptU64 = toAddress(SubprogramDieLowPC.find(DW_AT_high_pc));
881   EXPECT_FALSE((bool)OptU64);
882   OptU64 = toUnsigned(SubprogramDieLowPC.find(DW_AT_high_pc));
883   EXPECT_FALSE((bool)OptU64);
884   OptU64 = SubprogramDieLowPC.getHighPC(ActualLowPC);
885   EXPECT_FALSE((bool)OptU64);
886   EXPECT_FALSE(SubprogramDieLowPC.getLowAndHighPC(LowPC, HighPC, SectionIndex));
887 
888   // Verify the that our subprogram with only a low PC value succeeds when
889   // we ask for the Low PC, but fails appropriately when asked for the high PC
890   // or both low and high PC values.
891   auto SubprogramDieLowHighPC = SubprogramDieLowPC.getSibling();
892   EXPECT_TRUE(SubprogramDieLowHighPC.isValid());
893   EXPECT_EQ(SubprogramDieLowHighPC.getTag(), DW_TAG_subprogram);
894   OptU64 = toAddress(SubprogramDieLowHighPC.find(DW_AT_low_pc));
895   EXPECT_TRUE((bool)OptU64);
896   EXPECT_EQ(OptU64.getValue(), ActualLowPC);
897   // Get the high PC as an address. This should succeed if the high PC was
898   // encoded as an address and fail if the high PC was encoded as an offset.
899   OptU64 = toAddress(SubprogramDieLowHighPC.find(DW_AT_high_pc));
900   if (SupportsHighPCAsOffset) {
901     EXPECT_FALSE((bool)OptU64);
902   } else {
903     EXPECT_TRUE((bool)OptU64);
904     EXPECT_EQ(OptU64.getValue(), ActualHighPC);
905   }
906   // Get the high PC as an unsigned constant. This should succeed if the high PC
907   // was encoded as an offset and fail if the high PC was encoded as an address.
908   OptU64 = toUnsigned(SubprogramDieLowHighPC.find(DW_AT_high_pc));
909   if (SupportsHighPCAsOffset) {
910     EXPECT_TRUE((bool)OptU64);
911     EXPECT_EQ(OptU64.getValue(), ActualHighPCOffset);
912   } else {
913     EXPECT_FALSE((bool)OptU64);
914   }
915 
916   OptU64 = SubprogramDieLowHighPC.getHighPC(ActualLowPC);
917   EXPECT_TRUE((bool)OptU64);
918   EXPECT_EQ(OptU64.getValue(), ActualHighPC);
919 
920   EXPECT_TRUE(SubprogramDieLowHighPC.getLowAndHighPC(LowPC, HighPC, SectionIndex));
921   EXPECT_EQ(LowPC, ActualLowPC);
922   EXPECT_EQ(HighPC, ActualHighPC);
923 }
924 
925 TEST(DWARFDebugInfo, TestDWARF32Version2Addr4Addresses) {
926   // Test that we can decode address values in DWARF32, version 2, with 4 byte
927   // addresses.
928   typedef uint32_t AddrType;
929   TestAddresses<2, AddrType>();
930 }
931 
932 TEST(DWARFDebugInfo, TestDWARF32Version2Addr8Addresses) {
933   // Test that we can decode address values in DWARF32, version 2, with 8 byte
934   // addresses.
935   typedef uint64_t AddrType;
936   TestAddresses<2, AddrType>();
937 }
938 
939 TEST(DWARFDebugInfo, TestDWARF32Version3Addr4Addresses) {
940   // Test that we can decode address values in DWARF32, version 3, with 4 byte
941   // addresses.
942   typedef uint32_t AddrType;
943   TestAddresses<3, AddrType>();
944 }
945 
946 TEST(DWARFDebugInfo, TestDWARF32Version3Addr8Addresses) {
947   // Test that we can decode address values in DWARF32, version 3, with 8 byte
948   // addresses.
949   typedef uint64_t AddrType;
950   TestAddresses<3, AddrType>();
951 }
952 
953 TEST(DWARFDebugInfo, TestDWARF32Version4Addr4Addresses) {
954   // Test that we can decode address values in DWARF32, version 4, with 4 byte
955   // addresses.
956   typedef uint32_t AddrType;
957   TestAddresses<4, AddrType>();
958 }
959 
960 TEST(DWARFDebugInfo, TestDWARF32Version4Addr8Addresses) {
961   // Test that we can decode address values in DWARF32, version 4, with 8 byte
962   // addresses.
963   typedef uint64_t AddrType;
964   TestAddresses<4, AddrType>();
965 }
966 
967 TEST(DWARFDebugInfo, TestRelations) {
968   Triple Triple = getHostTripleForAddrSize(sizeof(void *));
969   if (!isConfigurationSupported(Triple))
970     return;
971 
972   // Test the DWARF APIs related to accessing the DW_AT_low_pc and
973   // DW_AT_high_pc.
974   uint16_t Version = 4;
975   auto ExpectedDG = dwarfgen::Generator::create(Triple, Version);
976   ASSERT_THAT_EXPECTED(ExpectedDG, Succeeded());
977   dwarfgen::Generator *DG = ExpectedDG.get().get();
978   dwarfgen::CompileUnit &CU = DG->addCompileUnit();
979 
980   enum class Tag: uint16_t  {
981     A = dwarf::DW_TAG_lo_user,
982     B,
983     C,
984     C1,
985     C2,
986     D,
987     D1
988   };
989 
990   // Scope to allow us to re-use the same DIE names
991   {
992     // Create DWARF tree that looks like:
993     //
994     // CU
995     //   A
996     //     B
997     //     C
998     //       C1
999     //       C2
1000     //     D
1001     //       D1
1002     dwarfgen::DIE CUDie = CU.getUnitDIE();
1003     dwarfgen::DIE A = CUDie.addChild((dwarf::Tag)Tag::A);
1004     A.addChild((dwarf::Tag)Tag::B);
1005     dwarfgen::DIE C = A.addChild((dwarf::Tag)Tag::C);
1006     dwarfgen::DIE D = A.addChild((dwarf::Tag)Tag::D);
1007     C.addChild((dwarf::Tag)Tag::C1);
1008     C.addChild((dwarf::Tag)Tag::C2);
1009     D.addChild((dwarf::Tag)Tag::D1);
1010   }
1011 
1012   MemoryBufferRef FileBuffer(DG->generate(), "dwarf");
1013   auto Obj = object::ObjectFile::createObjectFile(FileBuffer);
1014   EXPECT_TRUE((bool)Obj);
1015   DWARFContextInMemory DwarfContext(*Obj.get());
1016 
1017   // Verify the number of compile units is correct.
1018   uint32_t NumCUs = DwarfContext.getNumCompileUnits();
1019   EXPECT_EQ(NumCUs, 1u);
1020   DWARFCompileUnit *U = DwarfContext.getCompileUnitAtIndex(0);
1021 
1022   // Get the compile unit DIE is valid.
1023   auto CUDie = U->getUnitDIE(false);
1024   EXPECT_TRUE(CUDie.isValid());
1025 
1026   // The compile unit doesn't have a parent or a sibling.
1027   auto ParentDie = CUDie.getParent();
1028   EXPECT_FALSE(ParentDie.isValid());
1029   auto SiblingDie = CUDie.getSibling();
1030   EXPECT_FALSE(SiblingDie.isValid());
1031 
1032   // Get the children of the compile unit
1033   auto A = CUDie.getFirstChild();
1034   auto B = A.getFirstChild();
1035   auto C = B.getSibling();
1036   auto D = C.getSibling();
1037   auto Null = D.getSibling();
1038 
1039   // Verify NULL Die is NULL and has no children or siblings
1040   EXPECT_TRUE(Null.isNULL());
1041   EXPECT_FALSE(Null.getSibling().isValid());
1042   EXPECT_FALSE(Null.getFirstChild().isValid());
1043 
1044   // Verify all children of the compile unit DIE are correct.
1045   EXPECT_EQ(A.getTag(), (dwarf::Tag)Tag::A);
1046   EXPECT_EQ(B.getTag(), (dwarf::Tag)Tag::B);
1047   EXPECT_EQ(C.getTag(), (dwarf::Tag)Tag::C);
1048   EXPECT_EQ(D.getTag(), (dwarf::Tag)Tag::D);
1049 
1050   // Verify who has children
1051   EXPECT_TRUE(A.hasChildren());
1052   EXPECT_FALSE(B.hasChildren());
1053   EXPECT_TRUE(C.hasChildren());
1054   EXPECT_TRUE(D.hasChildren());
1055 
1056   // Make sure the parent of all the children of the compile unit are the
1057   // compile unit.
1058   EXPECT_EQ(A.getParent(), CUDie);
1059 
1060   // Make sure the parent of all the children of A are the A.
1061   // B is the first child in A, so we need to verify we can get the previous
1062   // DIE as the parent.
1063   EXPECT_EQ(B.getParent(), A);
1064   // C is the second child in A, so we need to make sure we can backup across
1065   // other DIE (B) at the same level to get the correct parent.
1066   EXPECT_EQ(C.getParent(), A);
1067   // D is the third child of A. We need to verify we can backup across other DIE
1068   // (B and C) including DIE that have children (D) to get the correct parent.
1069   EXPECT_EQ(D.getParent(), A);
1070 
1071   // Verify that a DIE with no children returns an invalid DWARFDie.
1072   EXPECT_FALSE(B.getFirstChild().isValid());
1073 
1074   // Verify the children of the B DIE
1075   auto C1 = C.getFirstChild();
1076   auto C2 = C1.getSibling();
1077   EXPECT_TRUE(C2.getSibling().isNULL());
1078 
1079   // Verify all children of the B DIE correctly valid or invalid.
1080   EXPECT_EQ(C1.getTag(), (dwarf::Tag)Tag::C1);
1081   EXPECT_EQ(C2.getTag(), (dwarf::Tag)Tag::C2);
1082 
1083   // Make sure the parent of all the children of the B are the B.
1084   EXPECT_EQ(C1.getParent(), C);
1085   EXPECT_EQ(C2.getParent(), C);
1086 }
1087 
1088 TEST(DWARFDebugInfo, TestDWARFDie) {
1089   // Make sure a default constructed DWARFDie doesn't have any parent, sibling
1090   // or child;
1091   DWARFDie DefaultDie;
1092   EXPECT_FALSE(DefaultDie.getParent().isValid());
1093   EXPECT_FALSE(DefaultDie.getFirstChild().isValid());
1094   EXPECT_FALSE(DefaultDie.getSibling().isValid());
1095 }
1096 
1097 TEST(DWARFDebugInfo, TestChildIterators) {
1098   Triple Triple = getHostTripleForAddrSize(sizeof(void *));
1099   if (!isConfigurationSupported(Triple))
1100     return;
1101 
1102   // Test the DWARF APIs related to iterating across the children of a DIE using
1103   // the DWARFDie::iterator class.
1104   uint16_t Version = 4;
1105   auto ExpectedDG = dwarfgen::Generator::create(Triple, Version);
1106   ASSERT_THAT_EXPECTED(ExpectedDG, Succeeded());
1107   dwarfgen::Generator *DG = ExpectedDG.get().get();
1108   dwarfgen::CompileUnit &CU = DG->addCompileUnit();
1109 
1110   enum class Tag: uint16_t  {
1111     A = dwarf::DW_TAG_lo_user,
1112     B,
1113   };
1114 
1115   // Scope to allow us to re-use the same DIE names
1116   {
1117     // Create DWARF tree that looks like:
1118     //
1119     // CU
1120     //   A
1121     //   B
1122     auto CUDie = CU.getUnitDIE();
1123     CUDie.addChild((dwarf::Tag)Tag::A);
1124     CUDie.addChild((dwarf::Tag)Tag::B);
1125   }
1126 
1127   MemoryBufferRef FileBuffer(DG->generate(), "dwarf");
1128   auto Obj = object::ObjectFile::createObjectFile(FileBuffer);
1129   EXPECT_TRUE((bool)Obj);
1130   DWARFContextInMemory DwarfContext(*Obj.get());
1131 
1132   // Verify the number of compile units is correct.
1133   uint32_t NumCUs = DwarfContext.getNumCompileUnits();
1134   EXPECT_EQ(NumCUs, 1u);
1135   DWARFCompileUnit *U = DwarfContext.getCompileUnitAtIndex(0);
1136 
1137   // Get the compile unit DIE is valid.
1138   auto CUDie = U->getUnitDIE(false);
1139   EXPECT_TRUE(CUDie.isValid());
1140   uint32_t Index;
1141   DWARFDie A;
1142   DWARFDie B;
1143 
1144   // Verify the compile unit DIE's children.
1145   Index = 0;
1146   for (auto Die : CUDie.children()) {
1147     switch (Index++) {
1148       case 0: A = Die; break;
1149       case 1: B = Die; break;
1150     }
1151   }
1152 
1153   EXPECT_EQ(A.getTag(), (dwarf::Tag)Tag::A);
1154   EXPECT_EQ(B.getTag(), (dwarf::Tag)Tag::B);
1155 
1156   // Verify that A has no children by verifying that the begin and end contain
1157   // invalid DIEs and also that the iterators are equal.
1158   EXPECT_EQ(A.begin(), A.end());
1159 }
1160 
1161 TEST(DWARFDebugInfo, TestChildIteratorsOnInvalidDie) {
1162   // Verify that an invalid DIE has no children.
1163   DWARFDie Invalid;
1164   auto begin = Invalid.begin();
1165   auto end = Invalid.end();
1166   EXPECT_FALSE(begin->isValid());
1167   EXPECT_FALSE(end->isValid());
1168   EXPECT_EQ(begin, end);
1169 }
1170 
1171 TEST(DWARFDebugInfo, TestEmptyChildren) {
1172   const char *yamldata = "debug_abbrev:\n"
1173                          "  - Code:            0x00000001\n"
1174                          "    Tag:             DW_TAG_compile_unit\n"
1175                          "    Children:        DW_CHILDREN_yes\n"
1176                          "    Attributes:\n"
1177                          "debug_info:\n"
1178                          "  - Length:\n"
1179                          "      TotalLength:          9\n"
1180                          "    Version:         4\n"
1181                          "    AbbrOffset:      0\n"
1182                          "    AddrSize:        8\n"
1183                          "    Entries:\n"
1184                          "      - AbbrCode:        0x00000001\n"
1185                          "        Values:\n"
1186                          "      - AbbrCode:        0x00000000\n"
1187                          "        Values:\n";
1188 
1189   auto ErrOrSections = DWARFYAML::EmitDebugSections(StringRef(yamldata));
1190   ASSERT_TRUE((bool)ErrOrSections);
1191   DWARFContextInMemory DwarfContext(*ErrOrSections, 8);
1192 
1193   // Verify the number of compile units is correct.
1194   uint32_t NumCUs = DwarfContext.getNumCompileUnits();
1195   EXPECT_EQ(NumCUs, 1u);
1196   DWARFCompileUnit *U = DwarfContext.getCompileUnitAtIndex(0);
1197 
1198   // Get the compile unit DIE is valid.
1199   auto CUDie = U->getUnitDIE(false);
1200   EXPECT_TRUE(CUDie.isValid());
1201 
1202   // Verify that the CU Die that says it has children, but doesn't, actually
1203   // has begin and end iterators that are equal. We want to make sure we don't
1204   // see the Null DIEs during iteration.
1205   EXPECT_EQ(CUDie.begin(), CUDie.end());
1206 }
1207 
1208 TEST(DWARFDebugInfo, TestAttributeIterators) {
1209   Triple Triple = getHostTripleForAddrSize(sizeof(void *));
1210   if (!isConfigurationSupported(Triple))
1211     return;
1212 
1213   // Test the DWARF APIs related to iterating across all attribute values in a
1214   // a DWARFDie.
1215   uint16_t Version = 4;
1216   auto ExpectedDG = dwarfgen::Generator::create(Triple, Version);
1217   ASSERT_THAT_EXPECTED(ExpectedDG, Succeeded());
1218   dwarfgen::Generator *DG = ExpectedDG.get().get();
1219   dwarfgen::CompileUnit &CU = DG->addCompileUnit();
1220   const uint64_t CULowPC = 0x1000;
1221   StringRef CUPath("/tmp/main.c");
1222 
1223   // Scope to allow us to re-use the same DIE names
1224   {
1225     auto CUDie = CU.getUnitDIE();
1226     // Encode an attribute value before an attribute with no data.
1227     CUDie.addAttribute(DW_AT_name, DW_FORM_strp, CUPath.data());
1228     // Encode an attribute value with no data in .debug_info/types to ensure
1229     // the iteration works correctly.
1230     CUDie.addAttribute(DW_AT_declaration, DW_FORM_flag_present);
1231     // Encode an attribute value after an attribute with no data.
1232     CUDie.addAttribute(DW_AT_low_pc, DW_FORM_addr, CULowPC);
1233   }
1234 
1235   MemoryBufferRef FileBuffer(DG->generate(), "dwarf");
1236   auto Obj = object::ObjectFile::createObjectFile(FileBuffer);
1237   EXPECT_TRUE((bool)Obj);
1238   DWARFContextInMemory DwarfContext(*Obj.get());
1239 
1240   // Verify the number of compile units is correct.
1241   uint32_t NumCUs = DwarfContext.getNumCompileUnits();
1242   EXPECT_EQ(NumCUs, 1u);
1243   DWARFCompileUnit *U = DwarfContext.getCompileUnitAtIndex(0);
1244 
1245   // Get the compile unit DIE is valid.
1246   auto CUDie = U->getUnitDIE(false);
1247   EXPECT_TRUE(CUDie.isValid());
1248 
1249   auto R = CUDie.attributes();
1250   auto I = R.begin();
1251   auto E = R.end();
1252 
1253   ASSERT_NE(E, I);
1254   EXPECT_EQ(I->Attr, DW_AT_name);
1255   auto ActualCUPath = I->Value.getAsCString();
1256   EXPECT_EQ(CUPath, *ActualCUPath);
1257 
1258   ASSERT_NE(E, ++I);
1259   EXPECT_EQ(I->Attr, DW_AT_declaration);
1260   EXPECT_EQ(1ull, *I->Value.getAsUnsignedConstant());
1261 
1262   ASSERT_NE(E, ++I);
1263   EXPECT_EQ(I->Attr, DW_AT_low_pc);
1264   EXPECT_EQ(CULowPC, *I->Value.getAsAddress());
1265 
1266   EXPECT_EQ(E, ++I);
1267 }
1268 
1269 TEST(DWARFDebugInfo, TestFindRecurse) {
1270   Triple Triple = getHostTripleForAddrSize(sizeof(void *));
1271   if (!isConfigurationSupported(Triple))
1272     return;
1273 
1274   uint16_t Version = 4;
1275   auto ExpectedDG = dwarfgen::Generator::create(Triple, Version);
1276   ASSERT_THAT_EXPECTED(ExpectedDG, Succeeded());
1277   dwarfgen::Generator *DG = ExpectedDG.get().get();
1278   dwarfgen::CompileUnit &CU = DG->addCompileUnit();
1279 
1280   StringRef SpecDieName = "spec";
1281   StringRef SpecLinkageName = "spec_linkage";
1282   StringRef AbsDieName = "abs";
1283   // Scope to allow us to re-use the same DIE names
1284   {
1285     auto CUDie = CU.getUnitDIE();
1286     auto FuncSpecDie = CUDie.addChild(DW_TAG_subprogram);
1287     auto FuncAbsDie = CUDie.addChild(DW_TAG_subprogram);
1288     auto FuncDie = CUDie.addChild(DW_TAG_subprogram);
1289     auto VarAbsDie = CUDie.addChild(DW_TAG_variable);
1290     auto VarDie = CUDie.addChild(DW_TAG_variable);
1291     FuncSpecDie.addAttribute(DW_AT_name, DW_FORM_strp, SpecDieName);
1292     FuncAbsDie.addAttribute(DW_AT_linkage_name, DW_FORM_strp, SpecLinkageName);
1293     FuncAbsDie.addAttribute(DW_AT_specification, DW_FORM_ref4, FuncSpecDie);
1294     FuncDie.addAttribute(DW_AT_abstract_origin, DW_FORM_ref4, FuncAbsDie);
1295     VarAbsDie.addAttribute(DW_AT_name, DW_FORM_strp, AbsDieName);
1296     VarDie.addAttribute(DW_AT_abstract_origin, DW_FORM_ref4, VarAbsDie);
1297   }
1298 
1299   MemoryBufferRef FileBuffer(DG->generate(), "dwarf");
1300   auto Obj = object::ObjectFile::createObjectFile(FileBuffer);
1301   EXPECT_TRUE((bool)Obj);
1302   DWARFContextInMemory DwarfContext(*Obj.get());
1303 
1304   // Verify the number of compile units is correct.
1305   uint32_t NumCUs = DwarfContext.getNumCompileUnits();
1306   EXPECT_EQ(NumCUs, 1u);
1307   DWARFCompileUnit *U = DwarfContext.getCompileUnitAtIndex(0);
1308 
1309   // Get the compile unit DIE is valid.
1310   auto CUDie = U->getUnitDIE(false);
1311   EXPECT_TRUE(CUDie.isValid());
1312 
1313   auto FuncSpecDie = CUDie.getFirstChild();
1314   auto FuncAbsDie = FuncSpecDie.getSibling();
1315   auto FuncDie = FuncAbsDie.getSibling();
1316   auto VarAbsDie = FuncDie.getSibling();
1317   auto VarDie = VarAbsDie.getSibling();
1318 
1319   // Make sure we can't extract the name from the specification die when using
1320   // DWARFDie::find() since it won't check the DW_AT_specification DIE.
1321   EXPECT_FALSE(FuncDie.find(DW_AT_name));
1322 
1323   // Make sure we can extract the name from the specification die when using
1324   // DWARFDie::findRecursively() since it should recurse through the
1325   // DW_AT_specification DIE.
1326   auto NameOpt = FuncDie.findRecursively(DW_AT_name);
1327   EXPECT_TRUE(NameOpt);
1328   // Test the dwarf::toString() helper function.
1329   auto StringOpt = toString(NameOpt);
1330   EXPECT_TRUE(StringOpt);
1331   EXPECT_EQ(SpecDieName, StringOpt.getValueOr(nullptr));
1332   // Test the dwarf::toString() helper function with a default value specified.
1333   EXPECT_EQ(SpecDieName, toString(NameOpt, nullptr));
1334 
1335   auto LinkageNameOpt = FuncDie.findRecursively(DW_AT_linkage_name);
1336   EXPECT_EQ(SpecLinkageName, toString(LinkageNameOpt).getValueOr(nullptr));
1337 
1338   // Make sure we can't extract the name from the abstract origin die when using
1339   // DWARFDie::find() since it won't check the DW_AT_abstract_origin DIE.
1340   EXPECT_FALSE(VarDie.find(DW_AT_name));
1341 
1342   // Make sure we can extract the name from the abstract origin die when using
1343   // DWARFDie::findRecursively() since it should recurse through the
1344   // DW_AT_abstract_origin DIE.
1345   NameOpt = VarDie.findRecursively(DW_AT_name);
1346   EXPECT_TRUE(NameOpt);
1347   // Test the dwarf::toString() helper function.
1348   StringOpt = toString(NameOpt);
1349   EXPECT_TRUE(StringOpt);
1350   EXPECT_EQ(AbsDieName, StringOpt.getValueOr(nullptr));
1351 }
1352 
1353 TEST(DWARFDebugInfo, TestDwarfToFunctions) {
1354   // Test all of the dwarf::toXXX functions that take a
1355   // Optional<DWARFFormValue> and extract the values from it.
1356   DWARFFormValue FormVal;
1357   uint64_t InvalidU64 = 0xBADBADBADBADBADB;
1358   int64_t InvalidS64 = 0xBADBADBADBADBADB;
1359   // First test that we don't get valid values back when using an optional with
1360   // no value.
1361   Optional<DWARFFormValue> FormValOpt;
1362   EXPECT_FALSE(toString(FormValOpt).hasValue());
1363   EXPECT_FALSE(toUnsigned(FormValOpt).hasValue());
1364   EXPECT_FALSE(toReference(FormValOpt).hasValue());
1365   EXPECT_FALSE(toSigned(FormValOpt).hasValue());
1366   EXPECT_FALSE(toAddress(FormValOpt).hasValue());
1367   EXPECT_FALSE(toSectionOffset(FormValOpt).hasValue());
1368   EXPECT_FALSE(toBlock(FormValOpt).hasValue());
1369   EXPECT_EQ(nullptr, toString(FormValOpt, nullptr));
1370   EXPECT_EQ(InvalidU64, toUnsigned(FormValOpt, InvalidU64));
1371   EXPECT_EQ(InvalidU64, toReference(FormValOpt, InvalidU64));
1372   EXPECT_EQ(InvalidU64, toAddress(FormValOpt, InvalidU64));
1373   EXPECT_EQ(InvalidU64, toSectionOffset(FormValOpt, InvalidU64));
1374   EXPECT_EQ(InvalidS64, toSigned(FormValOpt, InvalidS64));
1375 
1376   // Test successful and unsuccessful address decoding.
1377   uint64_t Address = 0x100000000ULL;
1378   FormVal.setForm(DW_FORM_addr);
1379   FormVal.setUValue(Address);
1380   FormValOpt = FormVal;
1381 
1382   EXPECT_FALSE(toString(FormValOpt).hasValue());
1383   EXPECT_FALSE(toUnsigned(FormValOpt).hasValue());
1384   EXPECT_FALSE(toReference(FormValOpt).hasValue());
1385   EXPECT_FALSE(toSigned(FormValOpt).hasValue());
1386   EXPECT_TRUE(toAddress(FormValOpt).hasValue());
1387   EXPECT_FALSE(toSectionOffset(FormValOpt).hasValue());
1388   EXPECT_FALSE(toBlock(FormValOpt).hasValue());
1389   EXPECT_EQ(nullptr, toString(FormValOpt, nullptr));
1390   EXPECT_EQ(InvalidU64, toUnsigned(FormValOpt, InvalidU64));
1391   EXPECT_EQ(InvalidU64, toReference(FormValOpt, InvalidU64));
1392   EXPECT_EQ(Address, toAddress(FormValOpt, InvalidU64));
1393   EXPECT_EQ(InvalidU64, toSectionOffset(FormValOpt, InvalidU64));
1394   EXPECT_EQ(InvalidS64, toSigned(FormValOpt, InvalidU64));
1395 
1396   // Test successful and unsuccessful unsigned constant decoding.
1397   uint64_t UData8 = 0x1020304050607080ULL;
1398   FormVal.setForm(DW_FORM_udata);
1399   FormVal.setUValue(UData8);
1400   FormValOpt = FormVal;
1401 
1402   EXPECT_FALSE(toString(FormValOpt).hasValue());
1403   EXPECT_TRUE(toUnsigned(FormValOpt).hasValue());
1404   EXPECT_FALSE(toReference(FormValOpt).hasValue());
1405   EXPECT_TRUE(toSigned(FormValOpt).hasValue());
1406   EXPECT_FALSE(toAddress(FormValOpt).hasValue());
1407   EXPECT_FALSE(toSectionOffset(FormValOpt).hasValue());
1408   EXPECT_FALSE(toBlock(FormValOpt).hasValue());
1409   EXPECT_EQ(nullptr, toString(FormValOpt, nullptr));
1410   EXPECT_EQ(UData8, toUnsigned(FormValOpt, InvalidU64));
1411   EXPECT_EQ(InvalidU64, toReference(FormValOpt, InvalidU64));
1412   EXPECT_EQ(InvalidU64, toAddress(FormValOpt, InvalidU64));
1413   EXPECT_EQ(InvalidU64, toSectionOffset(FormValOpt, InvalidU64));
1414   EXPECT_EQ((int64_t)UData8, toSigned(FormValOpt, InvalidU64));
1415 
1416   // Test successful and unsuccessful reference decoding.
1417   uint32_t RefData = 0x11223344U;
1418   FormVal.setForm(DW_FORM_ref_addr);
1419   FormVal.setUValue(RefData);
1420   FormValOpt = FormVal;
1421 
1422   EXPECT_FALSE(toString(FormValOpt).hasValue());
1423   EXPECT_FALSE(toUnsigned(FormValOpt).hasValue());
1424   EXPECT_TRUE(toReference(FormValOpt).hasValue());
1425   EXPECT_FALSE(toSigned(FormValOpt).hasValue());
1426   EXPECT_FALSE(toAddress(FormValOpt).hasValue());
1427   EXPECT_FALSE(toSectionOffset(FormValOpt).hasValue());
1428   EXPECT_FALSE(toBlock(FormValOpt).hasValue());
1429   EXPECT_EQ(nullptr, toString(FormValOpt, nullptr));
1430   EXPECT_EQ(InvalidU64, toUnsigned(FormValOpt, InvalidU64));
1431   EXPECT_EQ(RefData, toReference(FormValOpt, InvalidU64));
1432   EXPECT_EQ(InvalidU64, toAddress(FormValOpt, InvalidU64));
1433   EXPECT_EQ(InvalidU64, toSectionOffset(FormValOpt, InvalidU64));
1434   EXPECT_EQ(InvalidS64, toSigned(FormValOpt, InvalidU64));
1435 
1436   // Test successful and unsuccessful signed constant decoding.
1437   int64_t SData8 = 0x1020304050607080ULL;
1438   FormVal.setForm(DW_FORM_udata);
1439   FormVal.setSValue(SData8);
1440   FormValOpt = FormVal;
1441 
1442   EXPECT_FALSE(toString(FormValOpt).hasValue());
1443   EXPECT_TRUE(toUnsigned(FormValOpt).hasValue());
1444   EXPECT_FALSE(toReference(FormValOpt).hasValue());
1445   EXPECT_TRUE(toSigned(FormValOpt).hasValue());
1446   EXPECT_FALSE(toAddress(FormValOpt).hasValue());
1447   EXPECT_FALSE(toSectionOffset(FormValOpt).hasValue());
1448   EXPECT_FALSE(toBlock(FormValOpt).hasValue());
1449   EXPECT_EQ(nullptr, toString(FormValOpt, nullptr));
1450   EXPECT_EQ((uint64_t)SData8, toUnsigned(FormValOpt, InvalidU64));
1451   EXPECT_EQ(InvalidU64, toReference(FormValOpt, InvalidU64));
1452   EXPECT_EQ(InvalidU64, toAddress(FormValOpt, InvalidU64));
1453   EXPECT_EQ(InvalidU64, toSectionOffset(FormValOpt, InvalidU64));
1454   EXPECT_EQ(SData8, toSigned(FormValOpt, InvalidU64));
1455 
1456   // Test successful and unsuccessful block decoding.
1457   uint8_t Data[] = { 2, 3, 4 };
1458   ArrayRef<uint8_t> Array(Data);
1459   FormVal.setForm(DW_FORM_block1);
1460   FormVal.setBlockValue(Array);
1461   FormValOpt = FormVal;
1462 
1463   EXPECT_FALSE(toString(FormValOpt).hasValue());
1464   EXPECT_FALSE(toUnsigned(FormValOpt).hasValue());
1465   EXPECT_FALSE(toReference(FormValOpt).hasValue());
1466   EXPECT_FALSE(toSigned(FormValOpt).hasValue());
1467   EXPECT_FALSE(toAddress(FormValOpt).hasValue());
1468   EXPECT_FALSE(toSectionOffset(FormValOpt).hasValue());
1469   auto BlockOpt = toBlock(FormValOpt);
1470   EXPECT_TRUE(BlockOpt.hasValue());
1471   EXPECT_EQ(*BlockOpt, Array);
1472   EXPECT_EQ(nullptr, toString(FormValOpt, nullptr));
1473   EXPECT_EQ(InvalidU64, toUnsigned(FormValOpt, InvalidU64));
1474   EXPECT_EQ(InvalidU64, toReference(FormValOpt, InvalidU64));
1475   EXPECT_EQ(InvalidU64, toAddress(FormValOpt, InvalidU64));
1476   EXPECT_EQ(InvalidU64, toSectionOffset(FormValOpt, InvalidU64));
1477   EXPECT_EQ(InvalidS64, toSigned(FormValOpt, InvalidU64));
1478 
1479   // Test
1480 }
1481 
1482 TEST(DWARFDebugInfo, TestFindAttrs) {
1483   Triple Triple = getHostTripleForAddrSize(sizeof(void *));
1484   if (!isConfigurationSupported(Triple))
1485     return;
1486 
1487   // Test the DWARFDie::find() and DWARFDie::findRecursively() that take an
1488   // ArrayRef<dwarf::Attribute> value to make sure they work correctly.
1489   uint16_t Version = 4;
1490   auto ExpectedDG = dwarfgen::Generator::create(Triple, Version);
1491   ASSERT_THAT_EXPECTED(ExpectedDG, Succeeded());
1492   dwarfgen::Generator *DG = ExpectedDG.get().get();
1493   dwarfgen::CompileUnit &CU = DG->addCompileUnit();
1494 
1495   StringRef DieMangled("_Z3fooi");
1496   // Scope to allow us to re-use the same DIE names
1497   {
1498     auto CUDie = CU.getUnitDIE();
1499     auto FuncSpecDie = CUDie.addChild(DW_TAG_subprogram);
1500     auto FuncDie = CUDie.addChild(DW_TAG_subprogram);
1501     FuncSpecDie.addAttribute(DW_AT_MIPS_linkage_name, DW_FORM_strp, DieMangled);
1502     FuncDie.addAttribute(DW_AT_specification, DW_FORM_ref4, FuncSpecDie);
1503   }
1504 
1505   MemoryBufferRef FileBuffer(DG->generate(), "dwarf");
1506   auto Obj = object::ObjectFile::createObjectFile(FileBuffer);
1507   EXPECT_TRUE((bool)Obj);
1508   DWARFContextInMemory DwarfContext(*Obj.get());
1509 
1510   // Verify the number of compile units is correct.
1511   uint32_t NumCUs = DwarfContext.getNumCompileUnits();
1512   EXPECT_EQ(NumCUs, 1u);
1513   DWARFCompileUnit *U = DwarfContext.getCompileUnitAtIndex(0);
1514 
1515   // Get the compile unit DIE is valid.
1516   auto CUDie = U->getUnitDIE(false);
1517   EXPECT_TRUE(CUDie.isValid());
1518 
1519   auto FuncSpecDie = CUDie.getFirstChild();
1520   auto FuncDie = FuncSpecDie.getSibling();
1521 
1522   // Make sure that passing in an empty attribute list behave correctly.
1523   EXPECT_FALSE(FuncDie.find(ArrayRef<dwarf::Attribute>()).hasValue());
1524 
1525   // Make sure that passing in a list of attribute that are not contained
1526   // in the DIE returns nothing.
1527   EXPECT_FALSE(FuncDie.find({DW_AT_low_pc, DW_AT_entry_pc}).hasValue());
1528 
1529   const dwarf::Attribute Attrs[] = {DW_AT_linkage_name,
1530                                     DW_AT_MIPS_linkage_name};
1531 
1532   // Make sure we can't extract the linkage name attributes when using
1533   // DWARFDie::find() since it won't check the DW_AT_specification DIE.
1534   EXPECT_FALSE(FuncDie.find(Attrs).hasValue());
1535 
1536   // Make sure we can extract the name from the specification die when using
1537   // DWARFDie::findRecursively() since it should recurse through the
1538   // DW_AT_specification DIE.
1539   auto NameOpt = FuncDie.findRecursively(Attrs);
1540   EXPECT_TRUE(NameOpt.hasValue());
1541   EXPECT_EQ(DieMangled, toString(NameOpt, ""));
1542 }
1543 
1544 TEST(DWARFDebugInfo, TestImplicitConstAbbrevs) {
1545   Triple Triple = getHostTripleForAddrSize(sizeof(void *));
1546   if (!isConfigurationSupported(Triple))
1547     return;
1548 
1549   uint16_t Version = 5;
1550   auto ExpectedDG = dwarfgen::Generator::create(Triple, Version);
1551   ASSERT_THAT_EXPECTED(ExpectedDG, Succeeded());
1552   dwarfgen::Generator *DG = ExpectedDG.get().get();
1553   dwarfgen::CompileUnit &CU = DG->addCompileUnit();
1554   dwarfgen::DIE CUDie = CU.getUnitDIE();
1555   const dwarf::Attribute Attr = DW_AT_lo_user;
1556   const int64_t Val1 = 42;
1557   const int64_t Val2 = 43;
1558 
1559   auto FirstVal1DIE = CUDie.addChild(DW_TAG_class_type);
1560   FirstVal1DIE.addAttribute(Attr, DW_FORM_implicit_const, Val1);
1561 
1562   auto SecondVal1DIE = CUDie.addChild(DW_TAG_class_type);
1563   SecondVal1DIE.addAttribute(Attr, DW_FORM_implicit_const, Val1);
1564 
1565   auto Val2DIE = CUDie.addChild(DW_TAG_class_type);
1566   Val2DIE.addAttribute(Attr, DW_FORM_implicit_const, Val2);
1567 
1568   MemoryBufferRef FileBuffer(DG->generate(), "dwarf");
1569   auto Obj = object::ObjectFile::createObjectFile(FileBuffer);
1570   EXPECT_TRUE((bool)Obj);
1571   DWARFContextInMemory DwarfContext(*Obj.get());
1572   DWARFCompileUnit *U = DwarfContext.getCompileUnitAtIndex(0);
1573   EXPECT_TRUE((bool)U);
1574 
1575   const auto *Abbrevs = U->getAbbreviations();
1576   EXPECT_TRUE((bool)Abbrevs);
1577 
1578   // Let's find implicit_const abbrevs and verify,
1579   // that there are exactly two of them and both of them
1580   // can be dumped correctly.
1581   typedef decltype(Abbrevs->begin()) AbbrevIt;
1582   AbbrevIt Val1Abbrev = Abbrevs->end();
1583   AbbrevIt Val2Abbrev = Abbrevs->end();
1584   for(auto it = Abbrevs->begin(); it != Abbrevs->end(); ++it) {
1585     if (it->getNumAttributes() == 0)
1586       continue; // root abbrev for DW_TAG_compile_unit
1587 
1588     auto A = it->getAttrByIndex(0);
1589     EXPECT_EQ(A, Attr);
1590 
1591     auto FormValue = it->getAttributeValue(/* offset */ 0, A, *U);
1592     EXPECT_TRUE((bool)FormValue);
1593     EXPECT_EQ(FormValue->getForm(), dwarf::DW_FORM_implicit_const);
1594 
1595     const auto V = FormValue->getAsSignedConstant();
1596     EXPECT_TRUE((bool)V);
1597 
1598     auto VerifyAbbrevDump = [&V](AbbrevIt it) {
1599       std::string S;
1600       llvm::raw_string_ostream OS(S);
1601       it->dump(OS);
1602       auto FormPos = OS.str().find("DW_FORM_implicit_const");
1603       EXPECT_NE(FormPos, std::string::npos);
1604       auto ValPos = S.find_first_of("-0123456789", FormPos);
1605       EXPECT_NE(ValPos, std::string::npos);
1606       int64_t Val = std::atoll(S.substr(ValPos).c_str());
1607       EXPECT_EQ(Val, *V);
1608     };
1609 
1610     switch(*V) {
1611     case Val1:
1612       EXPECT_EQ(Val1Abbrev, Abbrevs->end());
1613       Val1Abbrev = it;
1614       VerifyAbbrevDump(it);
1615       break;
1616     case Val2:
1617       EXPECT_EQ(Val2Abbrev, Abbrevs->end());
1618       Val2Abbrev = it;
1619       VerifyAbbrevDump(it);
1620       break;
1621     default:
1622       FAIL() << "Unexpected attribute value: " << *V;
1623     }
1624   }
1625 
1626   // Now let's make sure that two Val1-DIEs refer to the same abbrev,
1627   // and Val2-DIE refers to another one.
1628   auto DieDG = U->getUnitDIE(false);
1629   auto it = DieDG.begin();
1630   std::multimap<int64_t, decltype(it->getAbbreviationDeclarationPtr())> DIEs;
1631   const DWARFAbbreviationDeclaration *AbbrevPtrVal1 = nullptr;
1632   const DWARFAbbreviationDeclaration *AbbrevPtrVal2 = nullptr;
1633   for (; it != DieDG.end(); ++it) {
1634     const auto *AbbrevPtr = it->getAbbreviationDeclarationPtr();
1635     EXPECT_TRUE((bool)AbbrevPtr);
1636     auto FormValue = it->find(Attr);
1637     EXPECT_TRUE((bool)FormValue);
1638     const auto V = FormValue->getAsSignedConstant();
1639     EXPECT_TRUE((bool)V);
1640     switch(*V) {
1641     case Val1:
1642       AbbrevPtrVal1 = AbbrevPtr;
1643       break;
1644     case Val2:
1645       AbbrevPtrVal2 = AbbrevPtr;
1646       break;
1647     default:
1648       FAIL() << "Unexpected attribute value: " << *V;
1649     }
1650     DIEs.insert(std::make_pair(*V, AbbrevPtr));
1651   }
1652   EXPECT_EQ(DIEs.count(Val1), 2u);
1653   EXPECT_EQ(DIEs.count(Val2), 1u);
1654   auto Val1Range = DIEs.equal_range(Val1);
1655   for (auto it = Val1Range.first; it != Val1Range.second; ++it)
1656     EXPECT_EQ(it->second, AbbrevPtrVal1);
1657   EXPECT_EQ(DIEs.find(Val2)->second, AbbrevPtrVal2);
1658 }
1659 
1660 void VerifyError(DWARFContext &DwarfContext, StringRef Error) {
1661   SmallString<1024> Str;
1662   raw_svector_ostream Strm(Str);
1663   EXPECT_FALSE(DwarfContext.verify(Strm, DIDT_All));
1664   EXPECT_TRUE(Str.str().contains(Error));
1665 }
1666 
1667 TEST(DWARFDebugInfo, TestDwarfVerifyInvalidCURef) {
1668   // Create a single compile unit with a single function that has a DW_AT_type
1669   // that is CU relative. The CU offset is not valid becuase it is larger than
1670   // the compile unit itself.
1671 
1672   const char *yamldata = R"(
1673     debug_str:
1674       - ''
1675       - /tmp/main.c
1676       - main
1677     debug_abbrev:
1678       - Code:            0x00000001
1679         Tag:             DW_TAG_compile_unit
1680         Children:        DW_CHILDREN_yes
1681         Attributes:
1682           - Attribute:       DW_AT_name
1683             Form:            DW_FORM_strp
1684       - Code:            0x00000002
1685         Tag:             DW_TAG_subprogram
1686         Children:        DW_CHILDREN_no
1687         Attributes:
1688           - Attribute:       DW_AT_name
1689             Form:            DW_FORM_strp
1690           - Attribute:       DW_AT_type
1691             Form:            DW_FORM_ref4
1692     debug_info:
1693       - Length:
1694           TotalLength:     22
1695         Version:         4
1696         AbbrOffset:      0
1697         AddrSize:        8
1698         Entries:
1699           - AbbrCode:        0x00000001
1700             Values:
1701               - Value:           0x0000000000000001
1702           - AbbrCode:        0x00000002
1703             Values:
1704               - Value:           0x000000000000000D
1705               - Value:           0x0000000000001234
1706           - AbbrCode:        0x00000000
1707             Values:
1708   )";
1709   auto ErrOrSections = DWARFYAML::EmitDebugSections(StringRef(yamldata));
1710   ASSERT_TRUE((bool)ErrOrSections);
1711   DWARFContextInMemory DwarfContext(*ErrOrSections, 8);
1712   VerifyError(DwarfContext, "error: DW_FORM_ref4 CU offset 0x00001234 is "
1713                             "invalid (must be less than CU size of "
1714                             "0x0000001a):");
1715 }
1716 
1717 TEST(DWARFDebugInfo, TestDwarfVerifyInvalidRefAddr) {
1718   // Create a single compile unit with a single function that has an invalid
1719   // DW_AT_type with an invalid .debug_info offset in its DW_FORM_ref_addr.
1720   const char *yamldata = R"(
1721     debug_str:
1722       - ''
1723       - /tmp/main.c
1724       - main
1725     debug_abbrev:
1726       - Code:            0x00000001
1727         Tag:             DW_TAG_compile_unit
1728         Children:        DW_CHILDREN_yes
1729         Attributes:
1730           - Attribute:       DW_AT_name
1731             Form:            DW_FORM_strp
1732       - Code:            0x00000002
1733         Tag:             DW_TAG_subprogram
1734         Children:        DW_CHILDREN_no
1735         Attributes:
1736           - Attribute:       DW_AT_name
1737             Form:            DW_FORM_strp
1738           - Attribute:       DW_AT_type
1739             Form:            DW_FORM_ref_addr
1740     debug_info:
1741       - Length:
1742           TotalLength:     22
1743         Version:         4
1744         AbbrOffset:      0
1745         AddrSize:        8
1746         Entries:
1747           - AbbrCode:        0x00000001
1748             Values:
1749               - Value:           0x0000000000000001
1750           - AbbrCode:        0x00000002
1751             Values:
1752               - Value:           0x000000000000000D
1753               - Value:           0x0000000000001234
1754           - AbbrCode:        0x00000000
1755             Values:
1756   )";
1757   auto ErrOrSections = DWARFYAML::EmitDebugSections(StringRef(yamldata));
1758   ASSERT_TRUE((bool)ErrOrSections);
1759   DWARFContextInMemory DwarfContext(*ErrOrSections, 8);
1760   VerifyError(DwarfContext,
1761               "error: DW_FORM_ref_addr offset beyond .debug_info bounds:");
1762 }
1763 
1764 TEST(DWARFDebugInfo, TestDwarfVerifyInvalidRanges) {
1765   // Create a single compile unit with a DW_AT_ranges whose section offset
1766   // isn't valid.
1767   const char *yamldata = R"(
1768     debug_str:
1769       - ''
1770       - /tmp/main.c
1771     debug_abbrev:
1772       - Code:            0x00000001
1773         Tag:             DW_TAG_compile_unit
1774         Children:        DW_CHILDREN_no
1775         Attributes:
1776           - Attribute:       DW_AT_name
1777             Form:            DW_FORM_strp
1778           - Attribute:       DW_AT_ranges
1779             Form:            DW_FORM_sec_offset
1780     debug_info:
1781       - Length:
1782           TotalLength:     16
1783         Version:         4
1784         AbbrOffset:      0
1785         AddrSize:        8
1786         Entries:
1787           - AbbrCode:        0x00000001
1788             Values:
1789               - Value:           0x0000000000000001
1790               - Value:           0x0000000000001000
1791 
1792   )";
1793   auto ErrOrSections = DWARFYAML::EmitDebugSections(StringRef(yamldata));
1794   ASSERT_TRUE((bool)ErrOrSections);
1795   DWARFContextInMemory DwarfContext(*ErrOrSections, 8);
1796   VerifyError(DwarfContext,
1797               "error: DW_AT_ranges offset is beyond .debug_ranges bounds:");
1798 }
1799 
1800 TEST(DWARFDebugInfo, TestDwarfVerifyInvalidStmtList) {
1801   // Create a single compile unit with a DW_AT_stmt_list whose section offset
1802   // isn't valid.
1803   const char *yamldata = R"(
1804     debug_str:
1805       - ''
1806       - /tmp/main.c
1807     debug_abbrev:
1808       - Code:            0x00000001
1809         Tag:             DW_TAG_compile_unit
1810         Children:        DW_CHILDREN_no
1811         Attributes:
1812           - Attribute:       DW_AT_name
1813             Form:            DW_FORM_strp
1814           - Attribute:       DW_AT_stmt_list
1815             Form:            DW_FORM_sec_offset
1816     debug_info:
1817       - Length:
1818           TotalLength:     16
1819         Version:         4
1820         AbbrOffset:      0
1821         AddrSize:        8
1822         Entries:
1823           - AbbrCode:        0x00000001
1824             Values:
1825               - Value:           0x0000000000000001
1826               - Value:           0x0000000000001000
1827 
1828   )";
1829   auto ErrOrSections = DWARFYAML::EmitDebugSections(StringRef(yamldata));
1830   ASSERT_TRUE((bool)ErrOrSections);
1831   DWARFContextInMemory DwarfContext(*ErrOrSections, 8);
1832   VerifyError(
1833       DwarfContext,
1834       "error: DW_AT_stmt_list offset is beyond .debug_line bounds: 0x00001000");
1835 }
1836 
1837 TEST(DWARFDebugInfo, TestDwarfVerifyInvalidStrp) {
1838   // Create a single compile unit with a single function that has an invalid
1839   // DW_FORM_strp for the DW_AT_name.
1840   const char *yamldata = R"(
1841     debug_str:
1842       - ''
1843     debug_abbrev:
1844       - Code:            0x00000001
1845         Tag:             DW_TAG_compile_unit
1846         Children:        DW_CHILDREN_no
1847         Attributes:
1848           - Attribute:       DW_AT_name
1849             Form:            DW_FORM_strp
1850     debug_info:
1851       - Length:
1852           TotalLength:     12
1853         Version:         4
1854         AbbrOffset:      0
1855         AddrSize:        8
1856         Entries:
1857           - AbbrCode:        0x00000001
1858             Values:
1859               - Value:           0x0000000000001234
1860   )";
1861   auto ErrOrSections = DWARFYAML::EmitDebugSections(StringRef(yamldata));
1862   ASSERT_TRUE((bool)ErrOrSections);
1863   DWARFContextInMemory DwarfContext(*ErrOrSections, 8);
1864   VerifyError(DwarfContext,
1865               "error: DW_FORM_strp offset beyond .debug_str bounds:");
1866 }
1867 
1868 TEST(DWARFDebugInfo, TestDwarfVerifyInvalidRefAddrBetween) {
1869   // Create a single compile unit with a single function that has a DW_AT_type
1870   // with a valid .debug_info offset, but the offset is between two DIEs.
1871   const char *yamldata = R"(
1872     debug_str:
1873       - ''
1874       - /tmp/main.c
1875       - main
1876     debug_abbrev:
1877       - Code:            0x00000001
1878         Tag:             DW_TAG_compile_unit
1879         Children:        DW_CHILDREN_yes
1880         Attributes:
1881           - Attribute:       DW_AT_name
1882             Form:            DW_FORM_strp
1883       - Code:            0x00000002
1884         Tag:             DW_TAG_subprogram
1885         Children:        DW_CHILDREN_no
1886         Attributes:
1887           - Attribute:       DW_AT_name
1888             Form:            DW_FORM_strp
1889           - Attribute:       DW_AT_type
1890             Form:            DW_FORM_ref_addr
1891     debug_info:
1892       - Length:
1893           TotalLength:     22
1894         Version:         4
1895         AbbrOffset:      0
1896         AddrSize:        8
1897         Entries:
1898           - AbbrCode:        0x00000001
1899             Values:
1900               - Value:           0x0000000000000001
1901           - AbbrCode:        0x00000002
1902             Values:
1903               - Value:           0x000000000000000D
1904               - Value:           0x0000000000000011
1905           - AbbrCode:        0x00000000
1906             Values:
1907   )";
1908   auto ErrOrSections = DWARFYAML::EmitDebugSections(StringRef(yamldata));
1909   ASSERT_TRUE((bool)ErrOrSections);
1910   DWARFContextInMemory DwarfContext(*ErrOrSections, 8);
1911   VerifyError(
1912       DwarfContext,
1913       "error: invalid DIE reference 0x00000011. Offset is in between DIEs:");
1914 }
1915 
1916 TEST(DWARFDebugInfo, TestDwarfVerifyInvalidLineSequence) {
1917   // Create a single compile unit whose line table has a sequence in it where
1918   // the address decreases.
1919   StringRef yamldata = R"(
1920     debug_str:
1921       - ''
1922       - /tmp/main.c
1923     debug_abbrev:
1924       - Code:            0x00000001
1925         Tag:             DW_TAG_compile_unit
1926         Children:        DW_CHILDREN_no
1927         Attributes:
1928           - Attribute:       DW_AT_name
1929             Form:            DW_FORM_strp
1930           - Attribute:       DW_AT_stmt_list
1931             Form:            DW_FORM_sec_offset
1932     debug_info:
1933       - Length:
1934           TotalLength:     16
1935         Version:         4
1936         AbbrOffset:      0
1937         AddrSize:        8
1938         Entries:
1939           - AbbrCode:        0x00000001
1940             Values:
1941               - Value:           0x0000000000000001
1942               - Value:           0x0000000000000000
1943     debug_line:
1944       - Length:
1945           TotalLength:     68
1946         Version:         2
1947         PrologueLength:  34
1948         MinInstLength:   1
1949         DefaultIsStmt:   1
1950         LineBase:        251
1951         LineRange:       14
1952         OpcodeBase:      13
1953         StandardOpcodeLengths: [ 0, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 1 ]
1954         IncludeDirs:
1955           - /tmp
1956         Files:
1957           - Name:            main.c
1958             DirIdx:          1
1959             ModTime:         0
1960             Length:          0
1961         Opcodes:
1962           - Opcode:          DW_LNS_extended_op
1963             ExtLen:          9
1964             SubOpcode:       DW_LNE_set_address
1965             Data:            4112
1966           - Opcode:          DW_LNS_advance_line
1967             SData:           9
1968             Data:            4112
1969           - Opcode:          DW_LNS_copy
1970             Data:            4112
1971           - Opcode:          DW_LNS_advance_pc
1972             Data:            18446744073709551600
1973           - Opcode:          DW_LNS_extended_op
1974             ExtLen:          1
1975             SubOpcode:       DW_LNE_end_sequence
1976             Data:            18446744073709551600
1977   )";
1978   auto ErrOrSections = DWARFYAML::EmitDebugSections(yamldata);
1979   ASSERT_TRUE((bool)ErrOrSections);
1980   DWARFContextInMemory DwarfContext(*ErrOrSections, 8);
1981   VerifyError(DwarfContext, "error: .debug_line[0x00000000] row[1] decreases "
1982                             "in address from previous row:");
1983 }
1984 
1985 TEST(DWARFDebugInfo, TestDwarfVerifyInvalidLineFileIndex) {
1986   // Create a single compile unit whose line table has a line table row with
1987   // an invalid file index.
1988   StringRef yamldata = R"(
1989     debug_str:
1990       - ''
1991       - /tmp/main.c
1992     debug_abbrev:
1993       - Code:            0x00000001
1994         Tag:             DW_TAG_compile_unit
1995         Children:        DW_CHILDREN_no
1996         Attributes:
1997           - Attribute:       DW_AT_name
1998             Form:            DW_FORM_strp
1999           - Attribute:       DW_AT_stmt_list
2000             Form:            DW_FORM_sec_offset
2001     debug_info:
2002       - Length:
2003           TotalLength:     16
2004         Version:         4
2005         AbbrOffset:      0
2006         AddrSize:        8
2007         Entries:
2008           - AbbrCode:        0x00000001
2009             Values:
2010               - Value:           0x0000000000000001
2011               - Value:           0x0000000000000000
2012     debug_line:
2013       - Length:
2014           TotalLength:     61
2015         Version:         2
2016         PrologueLength:  34
2017         MinInstLength:   1
2018         DefaultIsStmt:   1
2019         LineBase:        251
2020         LineRange:       14
2021         OpcodeBase:      13
2022         StandardOpcodeLengths: [ 0, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 1 ]
2023         IncludeDirs:
2024           - /tmp
2025         Files:
2026           - Name:            main.c
2027             DirIdx:          1
2028             ModTime:         0
2029             Length:          0
2030         Opcodes:
2031           - Opcode:          DW_LNS_extended_op
2032             ExtLen:          9
2033             SubOpcode:       DW_LNE_set_address
2034             Data:            4096
2035           - Opcode:          DW_LNS_advance_line
2036             SData:           9
2037             Data:            4096
2038           - Opcode:          DW_LNS_copy
2039             Data:            4096
2040           - Opcode:          DW_LNS_advance_pc
2041             Data:            16
2042           - Opcode:          DW_LNS_set_file
2043             Data:            5
2044           - Opcode:          DW_LNS_extended_op
2045             ExtLen:          1
2046             SubOpcode:       DW_LNE_end_sequence
2047             Data:            5
2048   )";
2049   auto ErrOrSections = DWARFYAML::EmitDebugSections(yamldata);
2050   ASSERT_TRUE((bool)ErrOrSections);
2051   DWARFContextInMemory DwarfContext(*ErrOrSections, 8);
2052   VerifyError(DwarfContext, "error: .debug_line[0x00000000][1] has invalid "
2053                             "file index 5 (valid values are [1,1]):");
2054 }
2055 
2056 TEST(DWARFDebugInfo, TestDwarfVerifyCUDontShareLineTable) {
2057   // Create a two compile units where both compile units share the same
2058   // DW_AT_stmt_list value and verify we report the error correctly.
2059   StringRef yamldata = R"(
2060     debug_str:
2061       - ''
2062       - /tmp/main.c
2063       - /tmp/foo.c
2064     debug_abbrev:
2065       - Code:            0x00000001
2066         Tag:             DW_TAG_compile_unit
2067         Children:        DW_CHILDREN_no
2068         Attributes:
2069           - Attribute:       DW_AT_name
2070             Form:            DW_FORM_strp
2071           - Attribute:       DW_AT_stmt_list
2072             Form:            DW_FORM_sec_offset
2073     debug_info:
2074       - Length:
2075           TotalLength:     16
2076         Version:         4
2077         AbbrOffset:      0
2078         AddrSize:        8
2079         Entries:
2080           - AbbrCode:        0x00000001
2081             Values:
2082               - Value:           0x0000000000000001
2083               - Value:           0x0000000000000000
2084       - Length:
2085           TotalLength:     16
2086         Version:         4
2087         AbbrOffset:      0
2088         AddrSize:        8
2089         Entries:
2090           - AbbrCode:        0x00000001
2091             Values:
2092               - Value:           0x000000000000000D
2093               - Value:           0x0000000000000000
2094     debug_line:
2095       - Length:
2096           TotalLength:     60
2097         Version:         2
2098         PrologueLength:  34
2099         MinInstLength:   1
2100         DefaultIsStmt:   1
2101         LineBase:        251
2102         LineRange:       14
2103         OpcodeBase:      13
2104         StandardOpcodeLengths: [ 0, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 1 ]
2105         IncludeDirs:
2106           - /tmp
2107         Files:
2108           - Name:            main.c
2109             DirIdx:          1
2110             ModTime:         0
2111             Length:          0
2112         Opcodes:
2113           - Opcode:          DW_LNS_extended_op
2114             ExtLen:          9
2115             SubOpcode:       DW_LNE_set_address
2116             Data:            4096
2117           - Opcode:          DW_LNS_advance_line
2118             SData:           9
2119             Data:            4096
2120           - Opcode:          DW_LNS_copy
2121             Data:            4096
2122           - Opcode:          DW_LNS_advance_pc
2123             Data:            256
2124           - Opcode:          DW_LNS_extended_op
2125             ExtLen:          1
2126             SubOpcode:       DW_LNE_end_sequence
2127             Data:            256
2128   )";
2129   auto ErrOrSections = DWARFYAML::EmitDebugSections(yamldata);
2130   ASSERT_TRUE((bool)ErrOrSections);
2131   DWARFContextInMemory DwarfContext(*ErrOrSections, 8);
2132   VerifyError(DwarfContext, "error: two compile unit DIEs, 0x0000000b and "
2133                             "0x0000001f, have the same DW_AT_stmt_list section "
2134                             "offset:");
2135 }
2136 
2137 TEST(DWARFDebugInfo, TestErrorReportingPolicy) {
2138   Triple Triple("x86_64-pc-linux");
2139   if (!isConfigurationSupported(Triple))
2140       return;
2141 
2142   auto ExpectedDG = dwarfgen::Generator::create(Triple, 4 /*DwarfVersion*/);
2143   ASSERT_THAT_EXPECTED(ExpectedDG, Succeeded());
2144   dwarfgen::Generator *DG = ExpectedDG.get().get();
2145   AsmPrinter *AP = DG->getAsmPrinter();
2146   MCContext *MC = DG->getMCContext();
2147 
2148   // Emit two compressed sections with broken headers.
2149   AP->OutStreamer->SwitchSection(
2150       MC->getELFSection(".zdebug_foo", 0 /*Type*/, 0 /*Flags*/));
2151   AP->OutStreamer->EmitBytes("0");
2152   AP->OutStreamer->SwitchSection(
2153       MC->getELFSection(".zdebug_bar", 0 /*Type*/, 0 /*Flags*/));
2154   AP->OutStreamer->EmitBytes("0");
2155 
2156   MemoryBufferRef FileBuffer(DG->generate(), "dwarf");
2157   auto Obj = object::ObjectFile::createObjectFile(FileBuffer);
2158   EXPECT_TRUE((bool)Obj);
2159 
2160   // Case 1: error handler handles all errors. That allows
2161   // DWARFContextInMemory
2162   //         to parse whole file and find both two errors we know about.
2163   int Errors = 0;
2164   DWARFContextInMemory Ctx1(*Obj.get(), nullptr, [&](Error E) {
2165     ++Errors;
2166     consumeError(std::move(E));
2167     return ErrorPolicy::Continue;
2168   });
2169   EXPECT_TRUE(Errors == 2);
2170 
2171   // Case 2: error handler stops parsing of object after first error.
2172   Errors = 0;
2173   DWARFContextInMemory Ctx2(*Obj.get(), nullptr, [&](Error E) {
2174     ++Errors;
2175     consumeError(std::move(E));
2176     return ErrorPolicy::Halt;
2177   });
2178   EXPECT_TRUE(Errors == 1);
2179 }
2180 
2181 } // end anonymous namespace
2182