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/StringRef.h"
14 #include "llvm/ADT/Triple.h"
15 #include "llvm/Config/llvm-config.h"
16 #include "llvm/DebugInfo/DWARF/DWARFCompileUnit.h"
17 #include "llvm/DebugInfo/DWARF/DWARFContext.h"
18 #include "llvm/DebugInfo/DWARF/DWARFDie.h"
19 #include "llvm/DebugInfo/DWARF/DWARFFormValue.h"
20 #include "llvm/Object/ObjectFile.h"
21 #include "llvm/ObjectYAML/DWARFYAML.h"
22 #include "llvm/ObjectYAML/DWARFEmitter.h"
23 #include "llvm/Support/Dwarf.h"
24 #include "llvm/Support/Error.h"
25 #include "llvm/Support/MemoryBuffer.h"
26 #include "llvm/Support/TargetSelect.h"
27 #include "gtest/gtest.h"
28 #include <climits>
29 #include <cstdint>
30 #include <cstring>
31 #include <string>
32 
33 using namespace llvm;
34 using namespace dwarf;
35 
36 namespace {
37 
38 void initLLVMIfNeeded() {
39   static bool gInitialized = false;
40   if (!gInitialized) {
41     gInitialized = true;
42     InitializeAllTargets();
43     InitializeAllTargetMCs();
44     InitializeAllAsmPrinters();
45     InitializeAllAsmParsers();
46   }
47 }
48 
49 Triple getHostTripleForAddrSize(uint8_t AddrSize) {
50   Triple PT(Triple::normalize(LLVM_HOST_TRIPLE));
51 
52   if (AddrSize == 8 && PT.isArch32Bit())
53     return PT.get64BitArchVariant();
54   if (AddrSize == 4 && PT.isArch64Bit())
55     return PT.get32BitArchVariant();
56   return PT;
57 }
58 
59 /// Take any llvm::Expected and check and handle any errors.
60 ///
61 /// \param Expected a llvm::Excepted instance to check.
62 /// \returns true if there were errors, false otherwise.
63 template <typename T>
64 static bool HandleExpectedError(T &Expected) {
65   std::string ErrorMsg;
66   handleAllErrors(Expected.takeError(), [&](const ErrorInfoBase &EI) {
67     ErrorMsg = EI.message();
68   });
69   if (!ErrorMsg.empty()) {
70     ::testing::AssertionFailure() << "error: " << ErrorMsg;
71     return true;
72   }
73   return false;
74 }
75 
76 template <uint16_t Version, class AddrType, class RefAddrType>
77 void TestAllForms() {
78   // Test that we can decode all DW_FORM values correctly.
79 
80   const uint8_t AddrSize = sizeof(AddrType);
81   const AddrType AddrValue = (AddrType)0x0123456789abcdefULL;
82   const uint8_t BlockData[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
83   const uint32_t BlockSize = sizeof(BlockData);
84   const RefAddrType RefAddr = 0x12345678;
85   const uint8_t Data1 = 0x01U;
86   const uint16_t Data2 = 0x2345U;
87   const uint32_t Data4 = 0x6789abcdU;
88   const uint64_t Data8 = 0x0011223344556677ULL;
89   const uint64_t Data8_2 = 0xAABBCCDDEEFF0011ULL;
90   const int64_t SData = INT64_MIN;
91   const int64_t ICSData = INT64_MAX; // DW_FORM_implicit_const SData
92   const uint64_t UData[] = {UINT64_MAX - 1, UINT64_MAX - 2, UINT64_MAX - 3,
93                             UINT64_MAX - 4, UINT64_MAX - 5, UINT64_MAX - 6,
94                             UINT64_MAX - 7, UINT64_MAX - 8, UINT64_MAX - 9};
95 #define UDATA_1 18446744073709551614ULL
96   const uint32_t Dwarf32Values[] = {1, 2, 3, 4, 5, 6, 7, 8};
97   const char *StringValue = "Hello";
98   const char *StrpValue = "World";
99   initLLVMIfNeeded();
100   Triple Triple = getHostTripleForAddrSize(AddrSize);
101   auto ExpectedDG = dwarfgen::Generator::create(Triple, Version);
102   if (HandleExpectedError(ExpectedDG))
103     return;
104   dwarfgen::Generator *DG = ExpectedDG.get().get();
105   dwarfgen::CompileUnit &CU = DG->addCompileUnit();
106   dwarfgen::DIE CUDie = CU.getUnitDIE();
107   uint16_t Attr = DW_AT_lo_user;
108 
109   //----------------------------------------------------------------------
110   // Test address forms
111   //----------------------------------------------------------------------
112   const auto Attr_DW_FORM_addr = static_cast<dwarf::Attribute>(Attr++);
113   CUDie.addAttribute(Attr_DW_FORM_addr, DW_FORM_addr, AddrValue);
114 
115   //----------------------------------------------------------------------
116   // Test block forms
117   //----------------------------------------------------------------------
118   const auto Attr_DW_FORM_block = static_cast<dwarf::Attribute>(Attr++);
119   CUDie.addAttribute(Attr_DW_FORM_block, DW_FORM_block, BlockData, BlockSize);
120 
121   const auto Attr_DW_FORM_block1 = static_cast<dwarf::Attribute>(Attr++);
122   CUDie.addAttribute(Attr_DW_FORM_block1, DW_FORM_block1, BlockData, BlockSize);
123 
124   const auto Attr_DW_FORM_block2 = static_cast<dwarf::Attribute>(Attr++);
125   CUDie.addAttribute(Attr_DW_FORM_block2, DW_FORM_block2, BlockData, BlockSize);
126 
127   const auto Attr_DW_FORM_block4 = static_cast<dwarf::Attribute>(Attr++);
128   CUDie.addAttribute(Attr_DW_FORM_block4, DW_FORM_block4, BlockData, BlockSize);
129 
130   //----------------------------------------------------------------------
131   // Test data forms
132   //----------------------------------------------------------------------
133   const auto Attr_DW_FORM_data1 = static_cast<dwarf::Attribute>(Attr++);
134   CUDie.addAttribute(Attr_DW_FORM_data1, DW_FORM_data1, Data1);
135 
136   const auto Attr_DW_FORM_data2 = static_cast<dwarf::Attribute>(Attr++);
137   CUDie.addAttribute(Attr_DW_FORM_data2, DW_FORM_data2, Data2);
138 
139   const auto Attr_DW_FORM_data4 = static_cast<dwarf::Attribute>(Attr++);
140   CUDie.addAttribute(Attr_DW_FORM_data4, DW_FORM_data4, Data4);
141 
142   const auto Attr_DW_FORM_data8 = static_cast<dwarf::Attribute>(Attr++);
143   CUDie.addAttribute(Attr_DW_FORM_data8, DW_FORM_data8, Data8);
144 
145   //----------------------------------------------------------------------
146   // Test string forms
147   //----------------------------------------------------------------------
148   const auto Attr_DW_FORM_string = static_cast<dwarf::Attribute>(Attr++);
149   CUDie.addAttribute(Attr_DW_FORM_string, DW_FORM_string, StringValue);
150 
151   const auto Attr_DW_FORM_strp = static_cast<dwarf::Attribute>(Attr++);
152   CUDie.addAttribute(Attr_DW_FORM_strp, DW_FORM_strp, StrpValue);
153 
154   //----------------------------------------------------------------------
155   // Test reference forms
156   //----------------------------------------------------------------------
157   const auto Attr_DW_FORM_ref_addr = static_cast<dwarf::Attribute>(Attr++);
158   CUDie.addAttribute(Attr_DW_FORM_ref_addr, DW_FORM_ref_addr, RefAddr);
159 
160   const auto Attr_DW_FORM_ref1 = static_cast<dwarf::Attribute>(Attr++);
161   CUDie.addAttribute(Attr_DW_FORM_ref1, DW_FORM_ref1, Data1);
162 
163   const auto Attr_DW_FORM_ref2 = static_cast<dwarf::Attribute>(Attr++);
164   CUDie.addAttribute(Attr_DW_FORM_ref2, DW_FORM_ref2, Data2);
165 
166   const auto Attr_DW_FORM_ref4 = static_cast<dwarf::Attribute>(Attr++);
167   CUDie.addAttribute(Attr_DW_FORM_ref4, DW_FORM_ref4, Data4);
168 
169   const auto Attr_DW_FORM_ref8 = static_cast<dwarf::Attribute>(Attr++);
170   CUDie.addAttribute(Attr_DW_FORM_ref8, DW_FORM_ref8, Data8);
171 
172   const auto Attr_DW_FORM_ref_sig8 = static_cast<dwarf::Attribute>(Attr++);
173   if (Version >= 4)
174     CUDie.addAttribute(Attr_DW_FORM_ref_sig8, DW_FORM_ref_sig8, Data8_2);
175 
176   const auto Attr_DW_FORM_ref_udata = static_cast<dwarf::Attribute>(Attr++);
177   CUDie.addAttribute(Attr_DW_FORM_ref_udata, DW_FORM_ref_udata, UData[0]);
178 
179   //----------------------------------------------------------------------
180   // Test flag forms
181   //----------------------------------------------------------------------
182   const auto Attr_DW_FORM_flag_true = static_cast<dwarf::Attribute>(Attr++);
183   CUDie.addAttribute(Attr_DW_FORM_flag_true, DW_FORM_flag, true);
184 
185   const auto Attr_DW_FORM_flag_false = static_cast<dwarf::Attribute>(Attr++);
186   CUDie.addAttribute(Attr_DW_FORM_flag_false, DW_FORM_flag, false);
187 
188   const auto Attr_DW_FORM_flag_present = static_cast<dwarf::Attribute>(Attr++);
189   if (Version >= 4)
190     CUDie.addAttribute(Attr_DW_FORM_flag_present, DW_FORM_flag_present);
191 
192   //----------------------------------------------------------------------
193   // Test SLEB128 based forms
194   //----------------------------------------------------------------------
195   const auto Attr_DW_FORM_sdata = static_cast<dwarf::Attribute>(Attr++);
196   CUDie.addAttribute(Attr_DW_FORM_sdata, DW_FORM_sdata, SData);
197 
198   const auto Attr_DW_FORM_implicit_const =
199     static_cast<dwarf::Attribute>(Attr++);
200   if (Version >= 5)
201     CUDie.addAttribute(Attr_DW_FORM_implicit_const, DW_FORM_implicit_const,
202                        ICSData);
203 
204   //----------------------------------------------------------------------
205   // Test ULEB128 based forms
206   //----------------------------------------------------------------------
207   const auto Attr_DW_FORM_udata = static_cast<dwarf::Attribute>(Attr++);
208   CUDie.addAttribute(Attr_DW_FORM_udata, DW_FORM_udata, UData[0]);
209 
210   //----------------------------------------------------------------------
211   // Test DWARF32/DWARF64 forms
212   //----------------------------------------------------------------------
213   const auto Attr_DW_FORM_GNU_ref_alt = static_cast<dwarf::Attribute>(Attr++);
214   CUDie.addAttribute(Attr_DW_FORM_GNU_ref_alt, DW_FORM_GNU_ref_alt,
215                      Dwarf32Values[0]);
216 
217   const auto Attr_DW_FORM_sec_offset = static_cast<dwarf::Attribute>(Attr++);
218   if (Version >= 4)
219     CUDie.addAttribute(Attr_DW_FORM_sec_offset, DW_FORM_sec_offset,
220                        Dwarf32Values[1]);
221 
222   //----------------------------------------------------------------------
223   // Add an address at the end to make sure we can decode this value
224   //----------------------------------------------------------------------
225   const auto Attr_Last = static_cast<dwarf::Attribute>(Attr++);
226   CUDie.addAttribute(Attr_Last, DW_FORM_addr, AddrValue);
227 
228   //----------------------------------------------------------------------
229   // Generate the DWARF
230   //----------------------------------------------------------------------
231   StringRef FileBytes = DG->generate();
232   MemoryBufferRef FileBuffer(FileBytes, "dwarf");
233   auto Obj = object::ObjectFile::createObjectFile(FileBuffer);
234   EXPECT_TRUE((bool)Obj);
235   DWARFContextInMemory DwarfContext(*Obj.get());
236   uint32_t NumCUs = DwarfContext.getNumCompileUnits();
237   EXPECT_EQ(NumCUs, 1u);
238   DWARFCompileUnit *U = DwarfContext.getCompileUnitAtIndex(0);
239   auto DieDG = U->getUnitDIE(false);
240   EXPECT_TRUE(DieDG.isValid());
241 
242   //----------------------------------------------------------------------
243   // Test address forms
244   //----------------------------------------------------------------------
245   EXPECT_EQ(AddrValue, toAddress(DieDG.find(Attr_DW_FORM_addr), 0));
246 
247   //----------------------------------------------------------------------
248   // Test block forms
249   //----------------------------------------------------------------------
250   Optional<DWARFFormValue> FormValue;
251   ArrayRef<uint8_t> ExtractedBlockData;
252   Optional<ArrayRef<uint8_t>> BlockDataOpt;
253 
254   FormValue = DieDG.find(Attr_DW_FORM_block);
255   EXPECT_TRUE((bool)FormValue);
256   BlockDataOpt = FormValue->getAsBlock();
257   EXPECT_TRUE(BlockDataOpt.hasValue());
258   ExtractedBlockData = BlockDataOpt.getValue();
259   EXPECT_EQ(ExtractedBlockData.size(), BlockSize);
260   EXPECT_TRUE(memcmp(ExtractedBlockData.data(), BlockData, BlockSize) == 0);
261 
262   FormValue = DieDG.find(Attr_DW_FORM_block1);
263   EXPECT_TRUE((bool)FormValue);
264   BlockDataOpt = FormValue->getAsBlock();
265   EXPECT_TRUE(BlockDataOpt.hasValue());
266   ExtractedBlockData = BlockDataOpt.getValue();
267   EXPECT_EQ(ExtractedBlockData.size(), BlockSize);
268   EXPECT_TRUE(memcmp(ExtractedBlockData.data(), BlockData, BlockSize) == 0);
269 
270   FormValue = DieDG.find(Attr_DW_FORM_block2);
271   EXPECT_TRUE((bool)FormValue);
272   BlockDataOpt = FormValue->getAsBlock();
273   EXPECT_TRUE(BlockDataOpt.hasValue());
274   ExtractedBlockData = BlockDataOpt.getValue();
275   EXPECT_EQ(ExtractedBlockData.size(), BlockSize);
276   EXPECT_TRUE(memcmp(ExtractedBlockData.data(), BlockData, BlockSize) == 0);
277 
278   FormValue = DieDG.find(Attr_DW_FORM_block4);
279   EXPECT_TRUE((bool)FormValue);
280   BlockDataOpt = FormValue->getAsBlock();
281   EXPECT_TRUE(BlockDataOpt.hasValue());
282   ExtractedBlockData = BlockDataOpt.getValue();
283   EXPECT_EQ(ExtractedBlockData.size(), BlockSize);
284   EXPECT_TRUE(memcmp(ExtractedBlockData.data(), BlockData, BlockSize) == 0);
285 
286   //----------------------------------------------------------------------
287   // Test data forms
288   //----------------------------------------------------------------------
289   EXPECT_EQ(Data1, toUnsigned(DieDG.find(Attr_DW_FORM_data1), 0));
290   EXPECT_EQ(Data2, toUnsigned(DieDG.find(Attr_DW_FORM_data2), 0));
291   EXPECT_EQ(Data4, toUnsigned(DieDG.find(Attr_DW_FORM_data4), 0));
292   EXPECT_EQ(Data8, toUnsigned(DieDG.find(Attr_DW_FORM_data8), 0));
293 
294   //----------------------------------------------------------------------
295   // Test string forms
296   //----------------------------------------------------------------------
297   auto ExtractedStringValue = toString(DieDG.find(Attr_DW_FORM_string));
298   EXPECT_TRUE((bool)ExtractedStringValue);
299   EXPECT_TRUE(strcmp(StringValue, *ExtractedStringValue) == 0);
300 
301   auto ExtractedStrpValue = toString(DieDG.find(Attr_DW_FORM_strp));
302   EXPECT_TRUE((bool)ExtractedStrpValue);
303   EXPECT_TRUE(strcmp(StrpValue, *ExtractedStrpValue) == 0);
304 
305   //----------------------------------------------------------------------
306   // Test reference forms
307   //----------------------------------------------------------------------
308   EXPECT_EQ(RefAddr, toReference(DieDG.find(Attr_DW_FORM_ref_addr), 0));
309   EXPECT_EQ(Data1, toReference(DieDG.find(Attr_DW_FORM_ref1), 0));
310   EXPECT_EQ(Data2, toReference(DieDG.find(Attr_DW_FORM_ref2), 0));
311   EXPECT_EQ(Data4, toReference(DieDG.find(Attr_DW_FORM_ref4), 0));
312   EXPECT_EQ(Data8, toReference(DieDG.find(Attr_DW_FORM_ref8), 0));
313   if (Version >= 4)
314     EXPECT_EQ(Data8_2, toReference(DieDG.find(Attr_DW_FORM_ref_sig8), 0));
315   EXPECT_EQ(UData[0], toReference(DieDG.find(Attr_DW_FORM_ref_udata), 0));
316 
317   //----------------------------------------------------------------------
318   // Test flag forms
319   //----------------------------------------------------------------------
320   EXPECT_EQ(1ULL, toUnsigned(DieDG.find(Attr_DW_FORM_flag_true), 0));
321   EXPECT_EQ(0ULL, toUnsigned(DieDG.find(Attr_DW_FORM_flag_false), 1));
322   if (Version >= 4)
323     EXPECT_EQ(1ULL, toUnsigned(DieDG.find(Attr_DW_FORM_flag_present), 0));
324 
325   //----------------------------------------------------------------------
326   // Test SLEB128 based forms
327   //----------------------------------------------------------------------
328   EXPECT_EQ(SData, toSigned(DieDG.find(Attr_DW_FORM_sdata), 0));
329   if (Version >= 5)
330     EXPECT_EQ(ICSData, toSigned(DieDG.find(Attr_DW_FORM_implicit_const), 0));
331 
332   //----------------------------------------------------------------------
333   // Test ULEB128 based forms
334   //----------------------------------------------------------------------
335   EXPECT_EQ(UData[0], toUnsigned(DieDG.find(Attr_DW_FORM_udata), 0));
336 
337   //----------------------------------------------------------------------
338   // Test DWARF32/DWARF64 forms
339   //----------------------------------------------------------------------
340   EXPECT_EQ(Dwarf32Values[0],
341             toReference(DieDG.find(Attr_DW_FORM_GNU_ref_alt), 0));
342   if (Version >= 4)
343     EXPECT_EQ(Dwarf32Values[1],
344               toSectionOffset(DieDG.find(Attr_DW_FORM_sec_offset), 0));
345 
346   //----------------------------------------------------------------------
347   // 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   // Test that we can decode DW_FORM_ref_addr values correctly in DWARF 2 with
426   // 4 byte addresses. DW_FORM_ref_addr values should be 4 bytes when using
427   // 8 byte addresses.
428 
429   const uint8_t AddrSize = sizeof(AddrType);
430   initLLVMIfNeeded();
431   Triple Triple = getHostTripleForAddrSize(AddrSize);
432   auto ExpectedDG = dwarfgen::Generator::create(Triple, Version);
433   if (HandleExpectedError(ExpectedDG))
434     return;
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   // Test that we can decode DW_FORM_refXXX values correctly in DWARF.
550 
551   const uint8_t AddrSize = sizeof(AddrType);
552   initLLVMIfNeeded();
553   Triple Triple = getHostTripleForAddrSize(AddrSize);
554   auto ExpectedDG = dwarfgen::Generator::create(Triple, Version);
555   if (HandleExpectedError(ExpectedDG))
556     return;
557   dwarfgen::Generator *DG = ExpectedDG.get().get();
558   dwarfgen::CompileUnit &CU1 = DG->addCompileUnit();
559   dwarfgen::CompileUnit &CU2 = DG->addCompileUnit();
560 
561   dwarfgen::DIE CU1Die = CU1.getUnitDIE();
562   CU1Die.addAttribute(DW_AT_name, DW_FORM_strp, "/tmp/main.c");
563   CU1Die.addAttribute(DW_AT_language, DW_FORM_data2, DW_LANG_C);
564 
565   dwarfgen::DIE CU1TypeDie = CU1Die.addChild(DW_TAG_base_type);
566   CU1TypeDie.addAttribute(DW_AT_name, DW_FORM_strp, "int");
567   CU1TypeDie.addAttribute(DW_AT_encoding, DW_FORM_data1, DW_ATE_signed);
568   CU1TypeDie.addAttribute(DW_AT_byte_size, DW_FORM_data1, 4);
569 
570   dwarfgen::DIE CU1Ref1Die = CU1Die.addChild(DW_TAG_variable);
571   CU1Ref1Die.addAttribute(DW_AT_name, DW_FORM_strp, "CU1Ref1");
572   CU1Ref1Die.addAttribute(DW_AT_type, DW_FORM_ref1, CU1TypeDie);
573 
574   dwarfgen::DIE CU1Ref2Die = CU1Die.addChild(DW_TAG_variable);
575   CU1Ref2Die.addAttribute(DW_AT_name, DW_FORM_strp, "CU1Ref2");
576   CU1Ref2Die.addAttribute(DW_AT_type, DW_FORM_ref2, CU1TypeDie);
577 
578   dwarfgen::DIE CU1Ref4Die = CU1Die.addChild(DW_TAG_variable);
579   CU1Ref4Die.addAttribute(DW_AT_name, DW_FORM_strp, "CU1Ref4");
580   CU1Ref4Die.addAttribute(DW_AT_type, DW_FORM_ref4, CU1TypeDie);
581 
582   dwarfgen::DIE CU1Ref8Die = CU1Die.addChild(DW_TAG_variable);
583   CU1Ref8Die.addAttribute(DW_AT_name, DW_FORM_strp, "CU1Ref8");
584   CU1Ref8Die.addAttribute(DW_AT_type, DW_FORM_ref8, CU1TypeDie);
585 
586   dwarfgen::DIE CU1RefAddrDie = CU1Die.addChild(DW_TAG_variable);
587   CU1RefAddrDie.addAttribute(DW_AT_name, DW_FORM_strp, "CU1RefAddr");
588   CU1RefAddrDie.addAttribute(DW_AT_type, DW_FORM_ref_addr, CU1TypeDie);
589 
590   dwarfgen::DIE CU2Die = CU2.getUnitDIE();
591   CU2Die.addAttribute(DW_AT_name, DW_FORM_strp, "/tmp/foo.c");
592   CU2Die.addAttribute(DW_AT_language, DW_FORM_data2, DW_LANG_C);
593 
594   dwarfgen::DIE CU2TypeDie = CU2Die.addChild(DW_TAG_base_type);
595   CU2TypeDie.addAttribute(DW_AT_name, DW_FORM_strp, "float");
596   CU2TypeDie.addAttribute(DW_AT_encoding, DW_FORM_data1, DW_ATE_float);
597   CU2TypeDie.addAttribute(DW_AT_byte_size, DW_FORM_data1, 4);
598 
599   dwarfgen::DIE CU2Ref1Die = CU2Die.addChild(DW_TAG_variable);
600   CU2Ref1Die.addAttribute(DW_AT_name, DW_FORM_strp, "CU2Ref1");
601   CU2Ref1Die.addAttribute(DW_AT_type, DW_FORM_ref1, CU2TypeDie);
602 
603   dwarfgen::DIE CU2Ref2Die = CU2Die.addChild(DW_TAG_variable);
604   CU2Ref2Die.addAttribute(DW_AT_name, DW_FORM_strp, "CU2Ref2");
605   CU2Ref2Die.addAttribute(DW_AT_type, DW_FORM_ref2, CU2TypeDie);
606 
607   dwarfgen::DIE CU2Ref4Die = CU2Die.addChild(DW_TAG_variable);
608   CU2Ref4Die.addAttribute(DW_AT_name, DW_FORM_strp, "CU2Ref4");
609   CU2Ref4Die.addAttribute(DW_AT_type, DW_FORM_ref4, CU2TypeDie);
610 
611   dwarfgen::DIE CU2Ref8Die = CU2Die.addChild(DW_TAG_variable);
612   CU2Ref8Die.addAttribute(DW_AT_name, DW_FORM_strp, "CU2Ref8");
613   CU2Ref8Die.addAttribute(DW_AT_type, DW_FORM_ref8, CU2TypeDie);
614 
615   dwarfgen::DIE CU2RefAddrDie = CU2Die.addChild(DW_TAG_variable);
616   CU2RefAddrDie.addAttribute(DW_AT_name, DW_FORM_strp, "CU2RefAddr");
617   CU2RefAddrDie.addAttribute(DW_AT_type, DW_FORM_ref_addr, CU2TypeDie);
618 
619   // Refer to a type in CU1 from CU2
620   dwarfgen::DIE CU2ToCU1RefAddrDie = CU2Die.addChild(DW_TAG_variable);
621   CU2ToCU1RefAddrDie.addAttribute(DW_AT_name, DW_FORM_strp, "CU2ToCU1RefAddr");
622   CU2ToCU1RefAddrDie.addAttribute(DW_AT_type, DW_FORM_ref_addr, CU1TypeDie);
623 
624   // Refer to a type in CU2 from CU1
625   dwarfgen::DIE CU1ToCU2RefAddrDie = CU1Die.addChild(DW_TAG_variable);
626   CU1ToCU2RefAddrDie.addAttribute(DW_AT_name, DW_FORM_strp, "CU1ToCU2RefAddr");
627   CU1ToCU2RefAddrDie.addAttribute(DW_AT_type, DW_FORM_ref_addr, CU2TypeDie);
628 
629   StringRef FileBytes = DG->generate();
630   MemoryBufferRef FileBuffer(FileBytes, "dwarf");
631   auto Obj = object::ObjectFile::createObjectFile(FileBuffer);
632   EXPECT_TRUE((bool)Obj);
633   DWARFContextInMemory DwarfContext(*Obj.get());
634 
635   // Verify the number of compile units is correct.
636   uint32_t NumCUs = DwarfContext.getNumCompileUnits();
637   EXPECT_EQ(NumCUs, 2u);
638   DWARFCompileUnit *U1 = DwarfContext.getCompileUnitAtIndex(0);
639   DWARFCompileUnit *U2 = DwarfContext.getCompileUnitAtIndex(1);
640 
641   // Get the compile unit DIE is valid.
642   auto Unit1DieDG = U1->getUnitDIE(false);
643   EXPECT_TRUE(Unit1DieDG.isValid());
644 
645   auto Unit2DieDG = U2->getUnitDIE(false);
646   EXPECT_TRUE(Unit2DieDG.isValid());
647 
648   // Verify the first child of the compile unit 1 DIE is our int base type.
649   auto CU1TypeDieDG = Unit1DieDG.getFirstChild();
650   EXPECT_TRUE(CU1TypeDieDG.isValid());
651   EXPECT_EQ(CU1TypeDieDG.getTag(), DW_TAG_base_type);
652   EXPECT_EQ(DW_ATE_signed, toUnsigned(CU1TypeDieDG.find(DW_AT_encoding), 0));
653 
654   // Verify the first child of the compile unit 2 DIE is our float base type.
655   auto CU2TypeDieDG = Unit2DieDG.getFirstChild();
656   EXPECT_TRUE(CU2TypeDieDG.isValid());
657   EXPECT_EQ(CU2TypeDieDG.getTag(), DW_TAG_base_type);
658   EXPECT_EQ(DW_ATE_float, toUnsigned(CU2TypeDieDG.find(DW_AT_encoding), 0));
659 
660   // Verify the sibling of the base type DIE is our Ref1 DIE and that its
661   // DW_AT_type points to our base type DIE.
662   auto CU1Ref1DieDG = CU1TypeDieDG.getSibling();
663   EXPECT_TRUE(CU1Ref1DieDG.isValid());
664   EXPECT_EQ(CU1Ref1DieDG.getTag(), DW_TAG_variable);
665   EXPECT_EQ(CU1TypeDieDG.getOffset(),
666             toReference(CU1Ref1DieDG.find(DW_AT_type), -1ULL));
667   // Verify the sibling is our Ref2 DIE and that its DW_AT_type points to our
668   // base type DIE in CU1.
669   auto CU1Ref2DieDG = CU1Ref1DieDG.getSibling();
670   EXPECT_TRUE(CU1Ref2DieDG.isValid());
671   EXPECT_EQ(CU1Ref2DieDG.getTag(), DW_TAG_variable);
672   EXPECT_EQ(CU1TypeDieDG.getOffset(),
673             toReference(CU1Ref2DieDG.find(DW_AT_type), -1ULL));
674 
675   // Verify the sibling is our Ref4 DIE and that its DW_AT_type points to our
676   // base type DIE in CU1.
677   auto CU1Ref4DieDG = CU1Ref2DieDG.getSibling();
678   EXPECT_TRUE(CU1Ref4DieDG.isValid());
679   EXPECT_EQ(CU1Ref4DieDG.getTag(), DW_TAG_variable);
680   EXPECT_EQ(CU1TypeDieDG.getOffset(),
681             toReference(CU1Ref4DieDG.find(DW_AT_type), -1ULL));
682 
683   // Verify the sibling is our Ref8 DIE and that its DW_AT_type points to our
684   // base type DIE in CU1.
685   auto CU1Ref8DieDG = CU1Ref4DieDG.getSibling();
686   EXPECT_TRUE(CU1Ref8DieDG.isValid());
687   EXPECT_EQ(CU1Ref8DieDG.getTag(), DW_TAG_variable);
688   EXPECT_EQ(CU1TypeDieDG.getOffset(),
689             toReference(CU1Ref8DieDG.find(DW_AT_type), -1ULL));
690 
691   // Verify the sibling is our RefAddr DIE and that its DW_AT_type points to our
692   // base type DIE in CU1.
693   auto CU1RefAddrDieDG = CU1Ref8DieDG.getSibling();
694   EXPECT_TRUE(CU1RefAddrDieDG.isValid());
695   EXPECT_EQ(CU1RefAddrDieDG.getTag(), DW_TAG_variable);
696   EXPECT_EQ(CU1TypeDieDG.getOffset(),
697             toReference(CU1RefAddrDieDG.find(DW_AT_type), -1ULL));
698 
699   // Verify the sibling of the Ref4 DIE is our RefAddr DIE and that its
700   // DW_AT_type points to our base type DIE.
701   auto CU1ToCU2RefAddrDieDG = CU1RefAddrDieDG.getSibling();
702   EXPECT_TRUE(CU1ToCU2RefAddrDieDG.isValid());
703   EXPECT_EQ(CU1ToCU2RefAddrDieDG.getTag(), DW_TAG_variable);
704   EXPECT_EQ(CU2TypeDieDG.getOffset(),
705             toReference(CU1ToCU2RefAddrDieDG.find(DW_AT_type), -1ULL));
706 
707   // Verify the sibling of the base type DIE is our Ref1 DIE and that its
708   // DW_AT_type points to our base type DIE.
709   auto CU2Ref1DieDG = CU2TypeDieDG.getSibling();
710   EXPECT_TRUE(CU2Ref1DieDG.isValid());
711   EXPECT_EQ(CU2Ref1DieDG.getTag(), DW_TAG_variable);
712   EXPECT_EQ(CU2TypeDieDG.getOffset(),
713             toReference(CU2Ref1DieDG.find(DW_AT_type), -1ULL));
714   // Verify the sibling is our Ref2 DIE and that its DW_AT_type points to our
715   // base type DIE in CU2.
716   auto CU2Ref2DieDG = CU2Ref1DieDG.getSibling();
717   EXPECT_TRUE(CU2Ref2DieDG.isValid());
718   EXPECT_EQ(CU2Ref2DieDG.getTag(), DW_TAG_variable);
719   EXPECT_EQ(CU2TypeDieDG.getOffset(),
720             toReference(CU2Ref2DieDG.find(DW_AT_type), -1ULL));
721 
722   // Verify the sibling is our Ref4 DIE and that its DW_AT_type points to our
723   // base type DIE in CU2.
724   auto CU2Ref4DieDG = CU2Ref2DieDG.getSibling();
725   EXPECT_TRUE(CU2Ref4DieDG.isValid());
726   EXPECT_EQ(CU2Ref4DieDG.getTag(), DW_TAG_variable);
727   EXPECT_EQ(CU2TypeDieDG.getOffset(),
728             toReference(CU2Ref4DieDG.find(DW_AT_type), -1ULL));
729 
730   // Verify the sibling is our Ref8 DIE and that its DW_AT_type points to our
731   // base type DIE in CU2.
732   auto CU2Ref8DieDG = CU2Ref4DieDG.getSibling();
733   EXPECT_TRUE(CU2Ref8DieDG.isValid());
734   EXPECT_EQ(CU2Ref8DieDG.getTag(), DW_TAG_variable);
735   EXPECT_EQ(CU2TypeDieDG.getOffset(),
736             toReference(CU2Ref8DieDG.find(DW_AT_type), -1ULL));
737 
738   // Verify the sibling is our RefAddr DIE and that its DW_AT_type points to our
739   // base type DIE in CU2.
740   auto CU2RefAddrDieDG = CU2Ref8DieDG.getSibling();
741   EXPECT_TRUE(CU2RefAddrDieDG.isValid());
742   EXPECT_EQ(CU2RefAddrDieDG.getTag(), DW_TAG_variable);
743   EXPECT_EQ(CU2TypeDieDG.getOffset(),
744             toReference(CU2RefAddrDieDG.find(DW_AT_type), -1ULL));
745 
746   // Verify the sibling of the Ref4 DIE is our RefAddr DIE and that its
747   // DW_AT_type points to our base type DIE.
748   auto CU2ToCU1RefAddrDieDG = CU2RefAddrDieDG.getSibling();
749   EXPECT_TRUE(CU2ToCU1RefAddrDieDG.isValid());
750   EXPECT_EQ(CU2ToCU1RefAddrDieDG.getTag(), DW_TAG_variable);
751   EXPECT_EQ(CU1TypeDieDG.getOffset(),
752             toReference(CU2ToCU1RefAddrDieDG.find(DW_AT_type), -1ULL));
753 }
754 
755 TEST(DWARFDebugInfo, TestDWARF32Version2Addr4References) {
756   // Test that we can decode all forms for DWARF32, version 2, with 4 byte
757   // addresses.
758   typedef uint32_t AddrType;
759   TestReferences<2, AddrType>();
760 }
761 
762 TEST(DWARFDebugInfo, TestDWARF32Version2Addr8References) {
763   // Test that we can decode all forms for DWARF32, version 2, with 8 byte
764   // addresses.
765   typedef uint64_t AddrType;
766   TestReferences<2, AddrType>();
767 }
768 
769 TEST(DWARFDebugInfo, TestDWARF32Version3Addr4References) {
770   // Test that we can decode all forms for DWARF32, version 3, with 4 byte
771   // addresses.
772   typedef uint32_t AddrType;
773   TestReferences<3, AddrType>();
774 }
775 
776 TEST(DWARFDebugInfo, TestDWARF32Version3Addr8References) {
777   // Test that we can decode all forms for DWARF32, version 3, with 8 byte
778   // addresses.
779   typedef uint64_t AddrType;
780   TestReferences<3, AddrType>();
781 }
782 
783 TEST(DWARFDebugInfo, TestDWARF32Version4Addr4References) {
784   // Test that we can decode all forms for DWARF32, version 4, with 4 byte
785   // addresses.
786   typedef uint32_t AddrType;
787   TestReferences<4, AddrType>();
788 }
789 
790 TEST(DWARFDebugInfo, TestDWARF32Version4Addr8References) {
791   // Test that we can decode all forms for DWARF32, version 4, with 8 byte
792   // addresses.
793   typedef uint64_t AddrType;
794   TestReferences<4, AddrType>();
795 }
796 
797 template <uint16_t Version, class AddrType> void TestAddresses() {
798   // Test the DWARF APIs related to accessing the DW_AT_low_pc and
799   // DW_AT_high_pc.
800   const uint8_t AddrSize = sizeof(AddrType);
801   const bool SupportsHighPCAsOffset = Version >= 4;
802   initLLVMIfNeeded();
803   Triple Triple = getHostTripleForAddrSize(AddrSize);
804   auto ExpectedDG = dwarfgen::Generator::create(Triple, Version);
805   if (HandleExpectedError(ExpectedDG))
806     return;
807   dwarfgen::Generator *DG = ExpectedDG.get().get();
808   dwarfgen::CompileUnit &CU = DG->addCompileUnit();
809   dwarfgen::DIE CUDie = CU.getUnitDIE();
810 
811   CUDie.addAttribute(DW_AT_name, DW_FORM_strp, "/tmp/main.c");
812   CUDie.addAttribute(DW_AT_language, DW_FORM_data2, DW_LANG_C);
813 
814   // Create a subprogram DIE with no low or high PC.
815   dwarfgen::DIE SubprogramNoPC = CUDie.addChild(DW_TAG_subprogram);
816   SubprogramNoPC.addAttribute(DW_AT_name, DW_FORM_strp, "no_pc");
817 
818   // Create a subprogram DIE with a low PC only.
819   dwarfgen::DIE SubprogramLowPC = CUDie.addChild(DW_TAG_subprogram);
820   SubprogramLowPC.addAttribute(DW_AT_name, DW_FORM_strp, "low_pc");
821   const uint64_t ActualLowPC = 0x1000;
822   const uint64_t ActualHighPC = 0x2000;
823   const uint64_t ActualHighPCOffset = ActualHighPC - ActualLowPC;
824   SubprogramLowPC.addAttribute(DW_AT_low_pc, DW_FORM_addr, ActualLowPC);
825 
826   // Create a subprogram DIE with a low and high PC.
827   dwarfgen::DIE SubprogramLowHighPC = CUDie.addChild(DW_TAG_subprogram);
828   SubprogramLowHighPC.addAttribute(DW_AT_name, DW_FORM_strp, "low_high_pc");
829   SubprogramLowHighPC.addAttribute(DW_AT_low_pc, DW_FORM_addr, ActualLowPC);
830   // Encode the high PC as an offset from the low PC if supported.
831   if (SupportsHighPCAsOffset)
832     SubprogramLowHighPC.addAttribute(DW_AT_high_pc, DW_FORM_data4,
833                                      ActualHighPCOffset);
834   else
835     SubprogramLowHighPC.addAttribute(DW_AT_high_pc, DW_FORM_addr, ActualHighPC);
836 
837   StringRef FileBytes = DG->generate();
838   MemoryBufferRef FileBuffer(FileBytes, "dwarf");
839   auto Obj = object::ObjectFile::createObjectFile(FileBuffer);
840   EXPECT_TRUE((bool)Obj);
841   DWARFContextInMemory DwarfContext(*Obj.get());
842 
843   // Verify the number of compile units is correct.
844   uint32_t NumCUs = DwarfContext.getNumCompileUnits();
845   EXPECT_EQ(NumCUs, 1u);
846   DWARFCompileUnit *U = DwarfContext.getCompileUnitAtIndex(0);
847 
848   // Get the compile unit DIE is valid.
849   auto DieDG = U->getUnitDIE(false);
850   EXPECT_TRUE(DieDG.isValid());
851 
852   uint64_t LowPC, HighPC;
853   Optional<uint64_t> OptU64;
854   // Verify the that our subprogram with no PC value fails appropriately when
855   // asked for any PC values.
856   auto SubprogramDieNoPC = DieDG.getFirstChild();
857   EXPECT_TRUE(SubprogramDieNoPC.isValid());
858   EXPECT_EQ(SubprogramDieNoPC.getTag(), DW_TAG_subprogram);
859   OptU64 = toAddress(SubprogramDieNoPC.find(DW_AT_low_pc));
860   EXPECT_FALSE((bool)OptU64);
861   OptU64 = toAddress(SubprogramDieNoPC.find(DW_AT_high_pc));
862   EXPECT_FALSE((bool)OptU64);
863   EXPECT_FALSE(SubprogramDieNoPC.getLowAndHighPC(LowPC, HighPC));
864   OptU64 = toAddress(SubprogramDieNoPC.find(DW_AT_high_pc));
865   EXPECT_FALSE((bool)OptU64);
866   OptU64 = toUnsigned(SubprogramDieNoPC.find(DW_AT_high_pc));
867   EXPECT_FALSE((bool)OptU64);
868   OptU64 = SubprogramDieNoPC.getHighPC(ActualLowPC);
869   EXPECT_FALSE((bool)OptU64);
870   EXPECT_FALSE(SubprogramDieNoPC.getLowAndHighPC(LowPC, HighPC));
871 
872   // Verify the that our subprogram with only a low PC value succeeds when
873   // we ask for the Low PC, but fails appropriately when asked for the high PC
874   // or both low and high PC values.
875   auto SubprogramDieLowPC = SubprogramDieNoPC.getSibling();
876   EXPECT_TRUE(SubprogramDieLowPC.isValid());
877   EXPECT_EQ(SubprogramDieLowPC.getTag(), DW_TAG_subprogram);
878   OptU64 = toAddress(SubprogramDieLowPC.find(DW_AT_low_pc));
879   EXPECT_TRUE((bool)OptU64);
880   EXPECT_EQ(OptU64.getValue(), ActualLowPC);
881   OptU64 = toAddress(SubprogramDieLowPC.find(DW_AT_high_pc));
882   EXPECT_FALSE((bool)OptU64);
883   OptU64 = toUnsigned(SubprogramDieLowPC.find(DW_AT_high_pc));
884   EXPECT_FALSE((bool)OptU64);
885   OptU64 = SubprogramDieLowPC.getHighPC(ActualLowPC);
886   EXPECT_FALSE((bool)OptU64);
887   EXPECT_FALSE(SubprogramDieLowPC.getLowAndHighPC(LowPC, HighPC));
888 
889   // Verify the that our subprogram with only a low PC value succeeds when
890   // we ask for the Low PC, but fails appropriately when asked for the high PC
891   // or both low and high PC values.
892   auto SubprogramDieLowHighPC = SubprogramDieLowPC.getSibling();
893   EXPECT_TRUE(SubprogramDieLowHighPC.isValid());
894   EXPECT_EQ(SubprogramDieLowHighPC.getTag(), DW_TAG_subprogram);
895   OptU64 = toAddress(SubprogramDieLowHighPC.find(DW_AT_low_pc));
896   EXPECT_TRUE((bool)OptU64);
897   EXPECT_EQ(OptU64.getValue(), ActualLowPC);
898   // Get the high PC as an address. This should succeed if the high PC was
899   // encoded as an address and fail if the high PC was encoded as an offset.
900   OptU64 = toAddress(SubprogramDieLowHighPC.find(DW_AT_high_pc));
901   if (SupportsHighPCAsOffset) {
902     EXPECT_FALSE((bool)OptU64);
903   } else {
904     EXPECT_TRUE((bool)OptU64);
905     EXPECT_EQ(OptU64.getValue(), ActualHighPC);
906   }
907   // Get the high PC as an unsigned constant. This should succeed if the high PC
908   // was encoded as an offset and fail if the high PC was encoded as an address.
909   OptU64 = toUnsigned(SubprogramDieLowHighPC.find(DW_AT_high_pc));
910   if (SupportsHighPCAsOffset) {
911     EXPECT_TRUE((bool)OptU64);
912     EXPECT_EQ(OptU64.getValue(), ActualHighPCOffset);
913   } else {
914     EXPECT_FALSE((bool)OptU64);
915   }
916 
917   OptU64 = SubprogramDieLowHighPC.getHighPC(ActualLowPC);
918   EXPECT_TRUE((bool)OptU64);
919   EXPECT_EQ(OptU64.getValue(), ActualHighPC);
920 
921   EXPECT_TRUE(SubprogramDieLowHighPC.getLowAndHighPC(LowPC, HighPC));
922   EXPECT_EQ(LowPC, ActualLowPC);
923   EXPECT_EQ(HighPC, ActualHighPC);
924 }
925 
926 TEST(DWARFDebugInfo, TestDWARF32Version2Addr4Addresses) {
927   // Test that we can decode address values in DWARF32, version 2, with 4 byte
928   // addresses.
929   typedef uint32_t AddrType;
930   TestAddresses<2, AddrType>();
931 }
932 
933 TEST(DWARFDebugInfo, TestDWARF32Version2Addr8Addresses) {
934   // Test that we can decode address values in DWARF32, version 2, with 8 byte
935   // addresses.
936   typedef uint64_t AddrType;
937   TestAddresses<2, AddrType>();
938 }
939 
940 TEST(DWARFDebugInfo, TestDWARF32Version3Addr4Addresses) {
941   // Test that we can decode address values in DWARF32, version 3, with 4 byte
942   // addresses.
943   typedef uint32_t AddrType;
944   TestAddresses<3, AddrType>();
945 }
946 
947 TEST(DWARFDebugInfo, TestDWARF32Version3Addr8Addresses) {
948   // Test that we can decode address values in DWARF32, version 3, with 8 byte
949   // addresses.
950   typedef uint64_t AddrType;
951   TestAddresses<3, AddrType>();
952 }
953 
954 TEST(DWARFDebugInfo, TestDWARF32Version4Addr4Addresses) {
955   // Test that we can decode address values in DWARF32, version 4, with 4 byte
956   // addresses.
957   typedef uint32_t AddrType;
958   TestAddresses<4, AddrType>();
959 }
960 
961 TEST(DWARFDebugInfo, TestDWARF32Version4Addr8Addresses) {
962   // Test that we can decode address values in DWARF32, version 4, with 8 byte
963   // addresses.
964   typedef uint64_t AddrType;
965   TestAddresses<4, AddrType>();
966 }
967 
968 TEST(DWARFDebugInfo, TestRelations) {
969   // Test the DWARF APIs related to accessing the DW_AT_low_pc and
970   // DW_AT_high_pc.
971   uint16_t Version = 4;
972 
973   const uint8_t AddrSize = sizeof(void *);
974   initLLVMIfNeeded();
975   Triple Triple = getHostTripleForAddrSize(AddrSize);
976   auto ExpectedDG = dwarfgen::Generator::create(Triple, Version);
977   if (HandleExpectedError(ExpectedDG))
978     return;
979   dwarfgen::Generator *DG = ExpectedDG.get().get();
980   dwarfgen::CompileUnit &CU = DG->addCompileUnit();
981 
982   enum class Tag: uint16_t  {
983     A = dwarf::DW_TAG_lo_user,
984     B,
985     C,
986     C1,
987     C2,
988     D,
989     D1
990   };
991 
992   // Scope to allow us to re-use the same DIE names
993   {
994     // Create DWARF tree that looks like:
995     //
996     // CU
997     //   A
998     //     B
999     //     C
1000     //       C1
1001     //       C2
1002     //     D
1003     //       D1
1004     dwarfgen::DIE CUDie = CU.getUnitDIE();
1005     dwarfgen::DIE A = CUDie.addChild((dwarf::Tag)Tag::A);
1006     A.addChild((dwarf::Tag)Tag::B);
1007     dwarfgen::DIE C = A.addChild((dwarf::Tag)Tag::C);
1008     dwarfgen::DIE D = A.addChild((dwarf::Tag)Tag::D);
1009     C.addChild((dwarf::Tag)Tag::C1);
1010     C.addChild((dwarf::Tag)Tag::C2);
1011     D.addChild((dwarf::Tag)Tag::D1);
1012   }
1013 
1014   MemoryBufferRef FileBuffer(DG->generate(), "dwarf");
1015   auto Obj = object::ObjectFile::createObjectFile(FileBuffer);
1016   EXPECT_TRUE((bool)Obj);
1017   DWARFContextInMemory DwarfContext(*Obj.get());
1018 
1019   // Verify the number of compile units is correct.
1020   uint32_t NumCUs = DwarfContext.getNumCompileUnits();
1021   EXPECT_EQ(NumCUs, 1u);
1022   DWARFCompileUnit *U = DwarfContext.getCompileUnitAtIndex(0);
1023 
1024   // Get the compile unit DIE is valid.
1025   auto CUDie = U->getUnitDIE(false);
1026   EXPECT_TRUE(CUDie.isValid());
1027 
1028   // The compile unit doesn't have a parent or a sibling.
1029   auto ParentDie = CUDie.getParent();
1030   EXPECT_FALSE(ParentDie.isValid());
1031   auto SiblingDie = CUDie.getSibling();
1032   EXPECT_FALSE(SiblingDie.isValid());
1033 
1034   // Get the children of the compile unit
1035   auto A = CUDie.getFirstChild();
1036   auto B = A.getFirstChild();
1037   auto C = B.getSibling();
1038   auto D = C.getSibling();
1039   auto Null = D.getSibling();
1040 
1041   // Verify NULL Die is NULL and has no children or siblings
1042   EXPECT_TRUE(Null.isNULL());
1043   EXPECT_FALSE(Null.getSibling().isValid());
1044   EXPECT_FALSE(Null.getFirstChild().isValid());
1045 
1046   // Verify all children of the compile unit DIE are correct.
1047   EXPECT_EQ(A.getTag(), (dwarf::Tag)Tag::A);
1048   EXPECT_EQ(B.getTag(), (dwarf::Tag)Tag::B);
1049   EXPECT_EQ(C.getTag(), (dwarf::Tag)Tag::C);
1050   EXPECT_EQ(D.getTag(), (dwarf::Tag)Tag::D);
1051 
1052   // Verify who has children
1053   EXPECT_TRUE(A.hasChildren());
1054   EXPECT_FALSE(B.hasChildren());
1055   EXPECT_TRUE(C.hasChildren());
1056   EXPECT_TRUE(D.hasChildren());
1057 
1058   // Make sure the parent of all the children of the compile unit are the
1059   // compile unit.
1060   EXPECT_EQ(A.getParent(), CUDie);
1061 
1062   // Make sure the parent of all the children of A are the A.
1063   // B is the first child in A, so we need to verify we can get the previous
1064   // DIE as the parent.
1065   EXPECT_EQ(B.getParent(), A);
1066   // C is the second child in A, so we need to make sure we can backup across
1067   // other DIE (B) at the same level to get the correct parent.
1068   EXPECT_EQ(C.getParent(), A);
1069   // D is the third child of A. We need to verify we can backup across other DIE
1070   // (B and C) including DIE that have children (D) to get the correct parent.
1071   EXPECT_EQ(D.getParent(), A);
1072 
1073   // Verify that a DIE with no children returns an invalid DWARFDie.
1074   EXPECT_FALSE(B.getFirstChild().isValid());
1075 
1076   // Verify the children of the B DIE
1077   auto C1 = C.getFirstChild();
1078   auto C2 = C1.getSibling();
1079   EXPECT_TRUE(C2.getSibling().isNULL());
1080 
1081   // Verify all children of the B DIE correctly valid or invalid.
1082   EXPECT_EQ(C1.getTag(), (dwarf::Tag)Tag::C1);
1083   EXPECT_EQ(C2.getTag(), (dwarf::Tag)Tag::C2);
1084 
1085   // Make sure the parent of all the children of the B are the B.
1086   EXPECT_EQ(C1.getParent(), C);
1087   EXPECT_EQ(C2.getParent(), C);
1088 }
1089 
1090 TEST(DWARFDebugInfo, TestDWARFDie) {
1091   // Make sure a default constructed DWARFDie doesn't have any parent, sibling
1092   // or child;
1093   DWARFDie DefaultDie;
1094   EXPECT_FALSE(DefaultDie.getParent().isValid());
1095   EXPECT_FALSE(DefaultDie.getFirstChild().isValid());
1096   EXPECT_FALSE(DefaultDie.getSibling().isValid());
1097 }
1098 
1099 TEST(DWARFDebugInfo, TestChildIterators) {
1100   // Test the DWARF APIs related to iterating across the children of a DIE using
1101   // the DWARFDie::iterator class.
1102   uint16_t Version = 4;
1103 
1104   const uint8_t AddrSize = sizeof(void *);
1105   initLLVMIfNeeded();
1106   Triple Triple = getHostTripleForAddrSize(AddrSize);
1107   auto ExpectedDG = dwarfgen::Generator::create(Triple, Version);
1108   if (HandleExpectedError(ExpectedDG))
1109     return;
1110   dwarfgen::Generator *DG = ExpectedDG.get().get();
1111   dwarfgen::CompileUnit &CU = DG->addCompileUnit();
1112 
1113   enum class Tag: uint16_t  {
1114     A = dwarf::DW_TAG_lo_user,
1115     B,
1116   };
1117 
1118   // Scope to allow us to re-use the same DIE names
1119   {
1120     // Create DWARF tree that looks like:
1121     //
1122     // CU
1123     //   A
1124     //   B
1125     auto CUDie = CU.getUnitDIE();
1126     CUDie.addChild((dwarf::Tag)Tag::A);
1127     CUDie.addChild((dwarf::Tag)Tag::B);
1128   }
1129 
1130   MemoryBufferRef FileBuffer(DG->generate(), "dwarf");
1131   auto Obj = object::ObjectFile::createObjectFile(FileBuffer);
1132   EXPECT_TRUE((bool)Obj);
1133   DWARFContextInMemory DwarfContext(*Obj.get());
1134 
1135   // Verify the number of compile units is correct.
1136   uint32_t NumCUs = DwarfContext.getNumCompileUnits();
1137   EXPECT_EQ(NumCUs, 1u);
1138   DWARFCompileUnit *U = DwarfContext.getCompileUnitAtIndex(0);
1139 
1140   // Get the compile unit DIE is valid.
1141   auto CUDie = U->getUnitDIE(false);
1142   EXPECT_TRUE(CUDie.isValid());
1143   uint32_t Index;
1144   DWARFDie A;
1145   DWARFDie B;
1146 
1147   // Verify the compile unit DIE's children.
1148   Index = 0;
1149   for (auto Die : CUDie.children()) {
1150     switch (Index++) {
1151       case 0: A = Die; break;
1152       case 1: B = Die; break;
1153     }
1154   }
1155 
1156   EXPECT_EQ(A.getTag(), (dwarf::Tag)Tag::A);
1157   EXPECT_EQ(B.getTag(), (dwarf::Tag)Tag::B);
1158 
1159   // Verify that A has no children by verifying that the begin and end contain
1160   // invalid DIEs and also that the iterators are equal.
1161   EXPECT_EQ(A.begin(), A.end());
1162 }
1163 
1164 TEST(DWARFDebugInfo, TestChildIteratorsOnInvalidDie) {
1165   // Verify that an invalid DIE has no children.
1166   DWARFDie Invalid;
1167   auto begin = Invalid.begin();
1168   auto end = Invalid.end();
1169   EXPECT_FALSE(begin->isValid());
1170   EXPECT_FALSE(end->isValid());
1171   EXPECT_EQ(begin, end);
1172 }
1173 
1174 TEST(DWARFDebugInfo, TestEmptyChildren) {
1175   const char *yamldata = "debug_abbrev:\n"
1176                          "  - Code:            0x00000001\n"
1177                          "    Tag:             DW_TAG_compile_unit\n"
1178                          "    Children:        DW_CHILDREN_yes\n"
1179                          "    Attributes:\n"
1180                          "debug_info:\n"
1181                          "  - Length:\n"
1182                          "      TotalLength:          9\n"
1183                          "    Version:         4\n"
1184                          "    AbbrOffset:      0\n"
1185                          "    AddrSize:        8\n"
1186                          "    Entries:\n"
1187                          "      - AbbrCode:        0x00000001\n"
1188                          "        Values:\n"
1189                          "      - AbbrCode:        0x00000000\n"
1190                          "        Values:\n";
1191 
1192   auto ErrOrSections = DWARFYAML::EmitDebugSections(StringRef(yamldata));
1193   ASSERT_TRUE((bool)ErrOrSections);
1194 
1195   auto &DebugSections = *ErrOrSections;
1196 
1197   DWARFContextInMemory DwarfContext(DebugSections, 8);
1198 
1199   // Verify the number of compile units is correct.
1200   uint32_t NumCUs = DwarfContext.getNumCompileUnits();
1201   EXPECT_EQ(NumCUs, 1u);
1202   DWARFCompileUnit *U = DwarfContext.getCompileUnitAtIndex(0);
1203 
1204   // Get the compile unit DIE is valid.
1205   auto CUDie = U->getUnitDIE(false);
1206   EXPECT_TRUE(CUDie.isValid());
1207 
1208   // Verify that the CU Die that says it has children, but doesn't, actually
1209   // has begin and end iterators that are equal. We want to make sure we don't
1210   // see the Null DIEs during iteration.
1211   EXPECT_EQ(CUDie.begin(), CUDie.end());
1212 }
1213 
1214 TEST(DWARFDebugInfo, TestAttributeIterators) {
1215   // Test the DWARF APIs related to iterating across all attribute values in a
1216   // a DWARFDie.
1217   uint16_t Version = 4;
1218 
1219   const uint8_t AddrSize = sizeof(void *);
1220   initLLVMIfNeeded();
1221   Triple Triple = getHostTripleForAddrSize(AddrSize);
1222   auto ExpectedDG = dwarfgen::Generator::create(Triple, Version);
1223   if (HandleExpectedError(ExpectedDG))
1224     return;
1225   dwarfgen::Generator *DG = ExpectedDG.get().get();
1226   dwarfgen::CompileUnit &CU = DG->addCompileUnit();
1227   const uint64_t CULowPC = 0x1000;
1228   StringRef CUPath("/tmp/main.c");
1229 
1230   // Scope to allow us to re-use the same DIE names
1231   {
1232     auto CUDie = CU.getUnitDIE();
1233     // Encode an attribute value before an attribute with no data.
1234     CUDie.addAttribute(DW_AT_name, DW_FORM_strp, CUPath.data());
1235     // Encode an attribute value with no data in .debug_info/types to ensure
1236     // the iteration works correctly.
1237     CUDie.addAttribute(DW_AT_declaration, DW_FORM_flag_present);
1238     // Encode an attribute value after an attribute with no data.
1239     CUDie.addAttribute(DW_AT_low_pc, DW_FORM_addr, CULowPC);
1240   }
1241 
1242   MemoryBufferRef FileBuffer(DG->generate(), "dwarf");
1243   auto Obj = object::ObjectFile::createObjectFile(FileBuffer);
1244   EXPECT_TRUE((bool)Obj);
1245   DWARFContextInMemory DwarfContext(*Obj.get());
1246 
1247   // Verify the number of compile units is correct.
1248   uint32_t NumCUs = DwarfContext.getNumCompileUnits();
1249   EXPECT_EQ(NumCUs, 1u);
1250   DWARFCompileUnit *U = DwarfContext.getCompileUnitAtIndex(0);
1251 
1252   // Get the compile unit DIE is valid.
1253   auto CUDie = U->getUnitDIE(false);
1254   EXPECT_TRUE(CUDie.isValid());
1255 
1256   auto R = CUDie.attributes();
1257   auto I = R.begin();
1258   auto E = R.end();
1259 
1260   ASSERT_NE(E, I);
1261   EXPECT_EQ(I->Attr, DW_AT_name);
1262   auto ActualCUPath = I->Value.getAsCString();
1263   EXPECT_EQ(CUPath, *ActualCUPath);
1264 
1265   ASSERT_NE(E, ++I);
1266   EXPECT_EQ(I->Attr, DW_AT_declaration);
1267   EXPECT_EQ(1ull, *I->Value.getAsUnsignedConstant());
1268 
1269   ASSERT_NE(E, ++I);
1270   EXPECT_EQ(I->Attr, DW_AT_low_pc);
1271   EXPECT_EQ(CULowPC, *I->Value.getAsAddress());
1272 
1273   EXPECT_EQ(E, ++I);
1274 }
1275 
1276 TEST(DWARFDebugInfo, TestFindRecurse) {
1277   uint16_t Version = 4;
1278 
1279   const uint8_t AddrSize = sizeof(void *);
1280   initLLVMIfNeeded();
1281   Triple Triple = getHostTripleForAddrSize(AddrSize);
1282   auto ExpectedDG = dwarfgen::Generator::create(Triple, Version);
1283   if (HandleExpectedError(ExpectedDG))
1284     return;
1285   dwarfgen::Generator *DG = ExpectedDG.get().get();
1286   dwarfgen::CompileUnit &CU = DG->addCompileUnit();
1287 
1288   StringRef SpecDieName = "spec";
1289   StringRef SpecLinkageName = "spec_linkage";
1290   StringRef AbsDieName = "abs";
1291   // Scope to allow us to re-use the same DIE names
1292   {
1293     auto CUDie = CU.getUnitDIE();
1294     auto FuncSpecDie = CUDie.addChild(DW_TAG_subprogram);
1295     auto FuncAbsDie = CUDie.addChild(DW_TAG_subprogram);
1296     auto FuncDie = CUDie.addChild(DW_TAG_subprogram);
1297     auto VarAbsDie = CUDie.addChild(DW_TAG_variable);
1298     auto VarDie = CUDie.addChild(DW_TAG_variable);
1299     FuncSpecDie.addAttribute(DW_AT_name, DW_FORM_strp, SpecDieName);
1300     FuncAbsDie.addAttribute(DW_AT_linkage_name, DW_FORM_strp, SpecLinkageName);
1301     FuncAbsDie.addAttribute(DW_AT_specification, DW_FORM_ref4, FuncSpecDie);
1302     FuncDie.addAttribute(DW_AT_abstract_origin, DW_FORM_ref4, FuncAbsDie);
1303     VarAbsDie.addAttribute(DW_AT_name, DW_FORM_strp, AbsDieName);
1304     VarDie.addAttribute(DW_AT_abstract_origin, DW_FORM_ref4, VarAbsDie);
1305   }
1306 
1307   MemoryBufferRef FileBuffer(DG->generate(), "dwarf");
1308   auto Obj = object::ObjectFile::createObjectFile(FileBuffer);
1309   EXPECT_TRUE((bool)Obj);
1310   DWARFContextInMemory DwarfContext(*Obj.get());
1311 
1312   // Verify the number of compile units is correct.
1313   uint32_t NumCUs = DwarfContext.getNumCompileUnits();
1314   EXPECT_EQ(NumCUs, 1u);
1315   DWARFCompileUnit *U = DwarfContext.getCompileUnitAtIndex(0);
1316 
1317   // Get the compile unit DIE is valid.
1318   auto CUDie = U->getUnitDIE(false);
1319   EXPECT_TRUE(CUDie.isValid());
1320 
1321   auto FuncSpecDie = CUDie.getFirstChild();
1322   auto FuncAbsDie = FuncSpecDie.getSibling();
1323   auto FuncDie = FuncAbsDie.getSibling();
1324   auto VarAbsDie = FuncDie.getSibling();
1325   auto VarDie = VarAbsDie.getSibling();
1326 
1327   // Make sure we can't extract the name from the specification die when using
1328   // DWARFDie::find() since it won't check the DW_AT_specification DIE.
1329   EXPECT_FALSE(FuncDie.find(DW_AT_name));
1330 
1331   // Make sure we can extract the name from the specification die when using
1332   // DWARFDie::findRecursively() since it should recurse through the
1333   // DW_AT_specification DIE.
1334   auto NameOpt = FuncDie.findRecursively(DW_AT_name);
1335   EXPECT_TRUE(NameOpt);
1336   // Test the dwarf::toString() helper function.
1337   auto StringOpt = toString(NameOpt);
1338   EXPECT_TRUE(StringOpt);
1339   EXPECT_EQ(SpecDieName, StringOpt.getValueOr(nullptr));
1340   // Test the dwarf::toString() helper function with a default value specified.
1341   EXPECT_EQ(SpecDieName, toString(NameOpt, nullptr));
1342 
1343   auto LinkageNameOpt = FuncDie.findRecursively(DW_AT_linkage_name);
1344   EXPECT_EQ(SpecLinkageName, toString(LinkageNameOpt).getValueOr(nullptr));
1345 
1346   // Make sure we can't extract the name from the abstract origin die when using
1347   // DWARFDie::find() since it won't check the DW_AT_abstract_origin DIE.
1348   EXPECT_FALSE(VarDie.find(DW_AT_name));
1349 
1350   // Make sure we can extract the name from the abstract origin die when using
1351   // DWARFDie::findRecursively() since it should recurse through the
1352   // DW_AT_abstract_origin DIE.
1353   NameOpt = VarDie.findRecursively(DW_AT_name);
1354   EXPECT_TRUE(NameOpt);
1355   // Test the dwarf::toString() helper function.
1356   StringOpt = toString(NameOpt);
1357   EXPECT_TRUE(StringOpt);
1358   EXPECT_EQ(AbsDieName, StringOpt.getValueOr(nullptr));
1359 }
1360 
1361 TEST(DWARFDebugInfo, TestDwarfToFunctions) {
1362   // Test all of the dwarf::toXXX functions that take a
1363   // Optional<DWARFFormValue> and extract the values from it.
1364   DWARFFormValue FormVal;
1365   uint64_t InvalidU64 = 0xBADBADBADBADBADB;
1366   int64_t InvalidS64 = 0xBADBADBADBADBADB;
1367   // First test that we don't get valid values back when using an optional with
1368   // no value.
1369   Optional<DWARFFormValue> FormValOpt;
1370   EXPECT_FALSE(toString(FormValOpt).hasValue());
1371   EXPECT_FALSE(toUnsigned(FormValOpt).hasValue());
1372   EXPECT_FALSE(toReference(FormValOpt).hasValue());
1373   EXPECT_FALSE(toSigned(FormValOpt).hasValue());
1374   EXPECT_FALSE(toAddress(FormValOpt).hasValue());
1375   EXPECT_FALSE(toSectionOffset(FormValOpt).hasValue());
1376   EXPECT_FALSE(toBlock(FormValOpt).hasValue());
1377   EXPECT_EQ(nullptr, toString(FormValOpt, nullptr));
1378   EXPECT_EQ(InvalidU64, toUnsigned(FormValOpt, InvalidU64));
1379   EXPECT_EQ(InvalidU64, toReference(FormValOpt, InvalidU64));
1380   EXPECT_EQ(InvalidU64, toAddress(FormValOpt, InvalidU64));
1381   EXPECT_EQ(InvalidU64, toSectionOffset(FormValOpt, InvalidU64));
1382   EXPECT_EQ(InvalidS64, toSigned(FormValOpt, InvalidS64));
1383 
1384   // Test successful and unsuccessful address decoding.
1385   uint64_t Address = 0x100000000ULL;
1386   FormVal.setForm(DW_FORM_addr);
1387   FormVal.setUValue(Address);
1388   FormValOpt = FormVal;
1389 
1390   EXPECT_FALSE(toString(FormValOpt).hasValue());
1391   EXPECT_FALSE(toUnsigned(FormValOpt).hasValue());
1392   EXPECT_FALSE(toReference(FormValOpt).hasValue());
1393   EXPECT_FALSE(toSigned(FormValOpt).hasValue());
1394   EXPECT_TRUE(toAddress(FormValOpt).hasValue());
1395   EXPECT_FALSE(toSectionOffset(FormValOpt).hasValue());
1396   EXPECT_FALSE(toBlock(FormValOpt).hasValue());
1397   EXPECT_EQ(nullptr, toString(FormValOpt, nullptr));
1398   EXPECT_EQ(InvalidU64, toUnsigned(FormValOpt, InvalidU64));
1399   EXPECT_EQ(InvalidU64, toReference(FormValOpt, InvalidU64));
1400   EXPECT_EQ(Address, toAddress(FormValOpt, InvalidU64));
1401   EXPECT_EQ(InvalidU64, toSectionOffset(FormValOpt, InvalidU64));
1402   EXPECT_EQ(InvalidS64, toSigned(FormValOpt, InvalidU64));
1403 
1404   // Test successful and unsuccessful unsigned constant decoding.
1405   uint64_t UData8 = 0x1020304050607080ULL;
1406   FormVal.setForm(DW_FORM_udata);
1407   FormVal.setUValue(UData8);
1408   FormValOpt = FormVal;
1409 
1410   EXPECT_FALSE(toString(FormValOpt).hasValue());
1411   EXPECT_TRUE(toUnsigned(FormValOpt).hasValue());
1412   EXPECT_FALSE(toReference(FormValOpt).hasValue());
1413   EXPECT_TRUE(toSigned(FormValOpt).hasValue());
1414   EXPECT_FALSE(toAddress(FormValOpt).hasValue());
1415   EXPECT_FALSE(toSectionOffset(FormValOpt).hasValue());
1416   EXPECT_FALSE(toBlock(FormValOpt).hasValue());
1417   EXPECT_EQ(nullptr, toString(FormValOpt, nullptr));
1418   EXPECT_EQ(UData8, toUnsigned(FormValOpt, InvalidU64));
1419   EXPECT_EQ(InvalidU64, toReference(FormValOpt, InvalidU64));
1420   EXPECT_EQ(InvalidU64, toAddress(FormValOpt, InvalidU64));
1421   EXPECT_EQ(InvalidU64, toSectionOffset(FormValOpt, InvalidU64));
1422   EXPECT_EQ((int64_t)UData8, toSigned(FormValOpt, InvalidU64));
1423 
1424   // Test successful and unsuccessful reference decoding.
1425   uint32_t RefData = 0x11223344U;
1426   FormVal.setForm(DW_FORM_ref_addr);
1427   FormVal.setUValue(RefData);
1428   FormValOpt = FormVal;
1429 
1430   EXPECT_FALSE(toString(FormValOpt).hasValue());
1431   EXPECT_FALSE(toUnsigned(FormValOpt).hasValue());
1432   EXPECT_TRUE(toReference(FormValOpt).hasValue());
1433   EXPECT_FALSE(toSigned(FormValOpt).hasValue());
1434   EXPECT_FALSE(toAddress(FormValOpt).hasValue());
1435   EXPECT_FALSE(toSectionOffset(FormValOpt).hasValue());
1436   EXPECT_FALSE(toBlock(FormValOpt).hasValue());
1437   EXPECT_EQ(nullptr, toString(FormValOpt, nullptr));
1438   EXPECT_EQ(InvalidU64, toUnsigned(FormValOpt, InvalidU64));
1439   EXPECT_EQ(RefData, toReference(FormValOpt, InvalidU64));
1440   EXPECT_EQ(InvalidU64, toAddress(FormValOpt, InvalidU64));
1441   EXPECT_EQ(InvalidU64, toSectionOffset(FormValOpt, InvalidU64));
1442   EXPECT_EQ(InvalidS64, toSigned(FormValOpt, InvalidU64));
1443 
1444   // Test successful and unsuccessful signed constant decoding.
1445   int64_t SData8 = 0x1020304050607080ULL;
1446   FormVal.setForm(DW_FORM_udata);
1447   FormVal.setSValue(SData8);
1448   FormValOpt = FormVal;
1449 
1450   EXPECT_FALSE(toString(FormValOpt).hasValue());
1451   EXPECT_TRUE(toUnsigned(FormValOpt).hasValue());
1452   EXPECT_FALSE(toReference(FormValOpt).hasValue());
1453   EXPECT_TRUE(toSigned(FormValOpt).hasValue());
1454   EXPECT_FALSE(toAddress(FormValOpt).hasValue());
1455   EXPECT_FALSE(toSectionOffset(FormValOpt).hasValue());
1456   EXPECT_FALSE(toBlock(FormValOpt).hasValue());
1457   EXPECT_EQ(nullptr, toString(FormValOpt, nullptr));
1458   EXPECT_EQ((uint64_t)SData8, toUnsigned(FormValOpt, InvalidU64));
1459   EXPECT_EQ(InvalidU64, toReference(FormValOpt, InvalidU64));
1460   EXPECT_EQ(InvalidU64, toAddress(FormValOpt, InvalidU64));
1461   EXPECT_EQ(InvalidU64, toSectionOffset(FormValOpt, InvalidU64));
1462   EXPECT_EQ(SData8, toSigned(FormValOpt, InvalidU64));
1463 
1464   // Test successful and unsuccessful block decoding.
1465   uint8_t Data[] = { 2, 3, 4 };
1466   ArrayRef<uint8_t> Array(Data);
1467   FormVal.setForm(DW_FORM_block1);
1468   FormVal.setBlockValue(Array);
1469   FormValOpt = FormVal;
1470 
1471   EXPECT_FALSE(toString(FormValOpt).hasValue());
1472   EXPECT_FALSE(toUnsigned(FormValOpt).hasValue());
1473   EXPECT_FALSE(toReference(FormValOpt).hasValue());
1474   EXPECT_FALSE(toSigned(FormValOpt).hasValue());
1475   EXPECT_FALSE(toAddress(FormValOpt).hasValue());
1476   EXPECT_FALSE(toSectionOffset(FormValOpt).hasValue());
1477   auto BlockOpt = toBlock(FormValOpt);
1478   EXPECT_TRUE(BlockOpt.hasValue());
1479   EXPECT_EQ(*BlockOpt, Array);
1480   EXPECT_EQ(nullptr, toString(FormValOpt, nullptr));
1481   EXPECT_EQ(InvalidU64, toUnsigned(FormValOpt, InvalidU64));
1482   EXPECT_EQ(InvalidU64, toReference(FormValOpt, InvalidU64));
1483   EXPECT_EQ(InvalidU64, toAddress(FormValOpt, InvalidU64));
1484   EXPECT_EQ(InvalidU64, toSectionOffset(FormValOpt, InvalidU64));
1485   EXPECT_EQ(InvalidS64, toSigned(FormValOpt, InvalidU64));
1486 
1487   // Test
1488 }
1489 
1490 TEST(DWARFDebugInfo, TestFindAttrs) {
1491   // Test the DWARFDie::find() and DWARFDie::findRecursively() that take an
1492   // ArrayRef<dwarf::Attribute> value to make sure they work correctly.
1493   uint16_t Version = 4;
1494 
1495   const uint8_t AddrSize = sizeof(void *);
1496   initLLVMIfNeeded();
1497   Triple Triple = getHostTripleForAddrSize(AddrSize);
1498   auto ExpectedDG = dwarfgen::Generator::create(Triple, Version);
1499   if (HandleExpectedError(ExpectedDG))
1500     return;
1501   dwarfgen::Generator *DG = ExpectedDG.get().get();
1502   dwarfgen::CompileUnit &CU = DG->addCompileUnit();
1503 
1504   StringRef DieMangled("_Z3fooi");
1505   // Scope to allow us to re-use the same DIE names
1506   {
1507     auto CUDie = CU.getUnitDIE();
1508     auto FuncSpecDie = CUDie.addChild(DW_TAG_subprogram);
1509     auto FuncDie = CUDie.addChild(DW_TAG_subprogram);
1510     FuncSpecDie.addAttribute(DW_AT_MIPS_linkage_name, DW_FORM_strp, DieMangled);
1511     FuncDie.addAttribute(DW_AT_specification, DW_FORM_ref4, FuncSpecDie);
1512   }
1513 
1514   MemoryBufferRef FileBuffer(DG->generate(), "dwarf");
1515   auto Obj = object::ObjectFile::createObjectFile(FileBuffer);
1516   EXPECT_TRUE((bool)Obj);
1517   DWARFContextInMemory DwarfContext(*Obj.get());
1518 
1519   // Verify the number of compile units is correct.
1520   uint32_t NumCUs = DwarfContext.getNumCompileUnits();
1521   EXPECT_EQ(NumCUs, 1u);
1522   DWARFCompileUnit *U = DwarfContext.getCompileUnitAtIndex(0);
1523 
1524   // Get the compile unit DIE is valid.
1525   auto CUDie = U->getUnitDIE(false);
1526   EXPECT_TRUE(CUDie.isValid());
1527 
1528   auto FuncSpecDie = CUDie.getFirstChild();
1529   auto FuncDie = FuncSpecDie.getSibling();
1530 
1531   // Make sure that passing in an empty attribute list behave correctly.
1532   EXPECT_FALSE(FuncDie.find(ArrayRef<dwarf::Attribute>()).hasValue());
1533 
1534   // Make sure that passing in a list of attribute that are not contained
1535   // in the DIE returns nothing.
1536   EXPECT_FALSE(FuncDie.find({DW_AT_low_pc, DW_AT_entry_pc}).hasValue());
1537 
1538   const dwarf::Attribute Attrs[] = {DW_AT_linkage_name,
1539                                     DW_AT_MIPS_linkage_name};
1540 
1541   // Make sure we can't extract the linkage name attributes when using
1542   // DWARFDie::find() since it won't check the DW_AT_specification DIE.
1543   EXPECT_FALSE(FuncDie.find(Attrs).hasValue());
1544 
1545   // Make sure we can extract the name from the specification die when using
1546   // DWARFDie::findRecursively() since it should recurse through the
1547   // DW_AT_specification DIE.
1548   auto NameOpt = FuncDie.findRecursively(Attrs);
1549   EXPECT_TRUE(NameOpt.hasValue());
1550   EXPECT_EQ(DieMangled, toString(NameOpt, ""));
1551 }
1552 
1553 TEST(DWARFDebugInfo, TestImplicitConstAbbrevs) {
1554   uint16_t Version = 5;
1555 
1556   const uint8_t AddrSize = sizeof(void *);
1557   initLLVMIfNeeded();
1558   Triple Triple = getHostTripleForAddrSize(AddrSize);
1559   auto ExpectedDG = dwarfgen::Generator::create(Triple, Version);
1560   if (HandleExpectedError(ExpectedDG))
1561     return;
1562   dwarfgen::Generator *DG = ExpectedDG.get().get();
1563   dwarfgen::CompileUnit &CU = DG->addCompileUnit();
1564   dwarfgen::DIE CUDie = CU.getUnitDIE();
1565   const dwarf::Attribute Attr = DW_AT_lo_user;
1566   const int64_t Val1 = 42;
1567   const int64_t Val2 = 43;
1568 
1569   auto FirstVal1DIE = CUDie.addChild(DW_TAG_class_type);
1570   FirstVal1DIE.addAttribute(Attr, DW_FORM_implicit_const, Val1);
1571 
1572   auto SecondVal1DIE = CUDie.addChild(DW_TAG_class_type);
1573   SecondVal1DIE.addAttribute(Attr, DW_FORM_implicit_const, Val1);
1574 
1575   auto Val2DIE = CUDie.addChild(DW_TAG_class_type);
1576   Val2DIE.addAttribute(Attr, DW_FORM_implicit_const, Val2);
1577 
1578   MemoryBufferRef FileBuffer(DG->generate(), "dwarf");
1579   auto Obj = object::ObjectFile::createObjectFile(FileBuffer);
1580   EXPECT_TRUE((bool)Obj);
1581   DWARFContextInMemory DwarfContext(*Obj.get());
1582   DWARFCompileUnit *U = DwarfContext.getCompileUnitAtIndex(0);
1583   EXPECT_TRUE((bool)U);
1584 
1585   const auto *Abbrevs = U->getAbbreviations();
1586   EXPECT_TRUE((bool)Abbrevs);
1587 
1588   // Let's find implicit_const abbrevs and verify,
1589   // that there are exactly two of them and both of them
1590   // can be dumped correctly.
1591   typedef decltype(Abbrevs->begin()) AbbrevIt;
1592   AbbrevIt Val1Abbrev = Abbrevs->end();
1593   AbbrevIt Val2Abbrev = Abbrevs->end();
1594   for(auto it = Abbrevs->begin(); it != Abbrevs->end(); ++it) {
1595     if (it->getNumAttributes() == 0)
1596       continue; // root abbrev for DW_TAG_compile_unit
1597 
1598     auto A = it->getAttrByIndex(0);
1599     EXPECT_EQ(A, Attr);
1600 
1601     auto FormValue = it->getAttributeValue(/* offset */ 0, A, *U);
1602     EXPECT_TRUE((bool)FormValue);
1603     EXPECT_EQ(FormValue->getForm(), dwarf::DW_FORM_implicit_const);
1604 
1605     const auto V = FormValue->getAsSignedConstant();
1606     EXPECT_TRUE((bool)V);
1607 
1608     auto VerifyAbbrevDump = [&V](AbbrevIt it) {
1609       std::string S;
1610       llvm::raw_string_ostream OS(S);
1611       it->dump(OS);
1612       auto FormPos = OS.str().find("DW_FORM_implicit_const");
1613       EXPECT_NE(FormPos, std::string::npos);
1614       auto ValPos = S.find_first_of("-0123456789", FormPos);
1615       EXPECT_NE(ValPos, std::string::npos);
1616       int64_t Val = std::atoll(S.substr(ValPos).c_str());
1617       EXPECT_EQ(Val, *V);
1618     };
1619 
1620     switch(*V) {
1621     case Val1:
1622       EXPECT_EQ(Val1Abbrev, Abbrevs->end());
1623       Val1Abbrev = it;
1624       VerifyAbbrevDump(it);
1625       break;
1626     case Val2:
1627       EXPECT_EQ(Val2Abbrev, Abbrevs->end());
1628       Val2Abbrev = it;
1629       VerifyAbbrevDump(it);
1630       break;
1631     default:
1632       FAIL() << "Unexpected attribute value: " << *V;
1633     }
1634   }
1635 
1636   // Now let's make sure that two Val1-DIEs refer to the same abbrev,
1637   // and Val2-DIE refers to another one.
1638   auto DieDG = U->getUnitDIE(false);
1639   auto it = DieDG.begin();
1640   std::multimap<int64_t, decltype(it->getAbbreviationDeclarationPtr())> DIEs;
1641   const DWARFAbbreviationDeclaration *AbbrevPtrVal1 = nullptr;
1642   const DWARFAbbreviationDeclaration *AbbrevPtrVal2 = nullptr;
1643   for (; it != DieDG.end(); ++it) {
1644     const auto *AbbrevPtr = it->getAbbreviationDeclarationPtr();
1645     EXPECT_TRUE((bool)AbbrevPtr);
1646     auto FormValue = it->find(Attr);
1647     EXPECT_TRUE((bool)FormValue);
1648     const auto V = FormValue->getAsSignedConstant();
1649     EXPECT_TRUE((bool)V);
1650     switch(*V) {
1651     case Val1:
1652       AbbrevPtrVal1 = AbbrevPtr;
1653       break;
1654     case Val2:
1655       AbbrevPtrVal2 = AbbrevPtr;
1656       break;
1657     default:
1658       FAIL() << "Unexpected attribute value: " << *V;
1659     }
1660     DIEs.insert(std::make_pair(*V, AbbrevPtr));
1661   }
1662   EXPECT_EQ(DIEs.count(Val1), 2u);
1663   EXPECT_EQ(DIEs.count(Val2), 1u);
1664   auto Val1Range = DIEs.equal_range(Val1);
1665   for (auto it = Val1Range.first; it != Val1Range.second; ++it)
1666     EXPECT_EQ(it->second, AbbrevPtrVal1);
1667   EXPECT_EQ(DIEs.find(Val2)->second, AbbrevPtrVal2);
1668 }
1669 
1670 } // end anonymous namespace
1671