xref: /llvm-project/llvm/unittests/Object/ELFObjectFileTest.cpp (revision 23faa81d3f0b701aec3731a7fce4d65c57a752b9)
1 //===- ELFObjectFileTest.cpp - Tests for ELFObjectFile --------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "llvm/Object/ELFObjectFile.h"
10 #include "llvm/ADT/STLExtras.h"
11 #include "llvm/ObjectYAML/yaml2obj.h"
12 #include "llvm/Support/BlockFrequency.h"
13 #include "llvm/Support/MemoryBuffer.h"
14 #include "llvm/Support/YAMLTraits.h"
15 #include "llvm/Testing/Support/Error.h"
16 #include "gtest/gtest.h"
17 
18 #include "llvm/Support/thread.h"
19 #include "llvm/TargetParser/Host.h"
20 
21 using namespace llvm;
22 using namespace llvm::object;
23 
24 namespace {
25 
26 // A struct to initialize a buffer to represent an ELF object file.
27 struct DataForTest {
28   std::vector<uint8_t> Data;
29 
30   template <typename T>
31   std::vector<uint8_t> makeElfData(uint8_t Class, uint8_t Encoding,
32                                    uint16_t Machine, uint8_t OS,
33                                    uint16_t Flags) {
34     T Ehdr{}; // Zero-initialise the header.
35     Ehdr.e_ident[ELF::EI_MAG0] = 0x7f;
36     Ehdr.e_ident[ELF::EI_MAG1] = 'E';
37     Ehdr.e_ident[ELF::EI_MAG2] = 'L';
38     Ehdr.e_ident[ELF::EI_MAG3] = 'F';
39     Ehdr.e_ident[ELF::EI_CLASS] = Class;
40     Ehdr.e_ident[ELF::EI_DATA] = Encoding;
41     Ehdr.e_ident[ELF::EI_VERSION] = 1;
42     Ehdr.e_ident[ELF::EI_OSABI] = OS;
43     Ehdr.e_type = ELF::ET_REL;
44     Ehdr.e_machine = Machine;
45     Ehdr.e_version = 1;
46     Ehdr.e_flags = Flags;
47     Ehdr.e_ehsize = sizeof(T);
48 
49     bool IsLittleEndian = Encoding == ELF::ELFDATA2LSB;
50     if (sys::IsLittleEndianHost != IsLittleEndian) {
51       sys::swapByteOrder(Ehdr.e_type);
52       sys::swapByteOrder(Ehdr.e_machine);
53       sys::swapByteOrder(Ehdr.e_version);
54       sys::swapByteOrder(Ehdr.e_ehsize);
55     }
56 
57     uint8_t *EhdrBytes = reinterpret_cast<uint8_t *>(&Ehdr);
58     std::vector<uint8_t> Bytes;
59     std::copy(EhdrBytes, EhdrBytes + sizeof(Ehdr), std::back_inserter(Bytes));
60     return Bytes;
61   }
62 
63   DataForTest(uint8_t Class, uint8_t Encoding, uint16_t Machine,
64               uint8_t OS = ELF::ELFOSABI_NONE, uint16_t Flags = 0) {
65     if (Class == ELF::ELFCLASS64)
66       Data = makeElfData<ELF::Elf64_Ehdr>(Class, Encoding, Machine, OS, Flags);
67     else {
68       assert(Class == ELF::ELFCLASS32);
69       Data = makeElfData<ELF::Elf32_Ehdr>(Class, Encoding, Machine, OS, Flags);
70     }
71   }
72 };
73 
74 void checkFormatAndArch(const DataForTest &D, StringRef Fmt,
75                         Triple::ArchType Arch) {
76   Expected<std::unique_ptr<ObjectFile>> ELFObjOrErr =
77       object::ObjectFile::createELFObjectFile(
78           MemoryBufferRef(toStringRef(D.Data), "dummyELF"));
79   ASSERT_THAT_EXPECTED(ELFObjOrErr, Succeeded());
80 
81   const ObjectFile &File = *(*ELFObjOrErr).get();
82   EXPECT_EQ(Fmt, File.getFileFormatName());
83   EXPECT_EQ(Arch, File.getArch());
84 }
85 
86 std::array<DataForTest, 4> generateData(uint16_t Machine) {
87   return {DataForTest(ELF::ELFCLASS32, ELF::ELFDATA2LSB, Machine),
88           DataForTest(ELF::ELFCLASS32, ELF::ELFDATA2MSB, Machine),
89           DataForTest(ELF::ELFCLASS64, ELF::ELFDATA2LSB, Machine),
90           DataForTest(ELF::ELFCLASS64, ELF::ELFDATA2MSB, Machine)};
91 }
92 
93 } // namespace
94 
95 TEST(ELFObjectFileTest, MachineTestForNoneOrUnused) {
96   std::array<StringRef, 4> Formats = {"elf32-unknown", "elf32-unknown",
97                                       "elf64-unknown", "elf64-unknown"};
98   for (auto [Idx, Data] : enumerate(generateData(ELF::EM_NONE)))
99     checkFormatAndArch(Data, Formats[Idx], Triple::UnknownArch);
100 
101   // Test an arbitrary unused EM_* value (255).
102   for (auto [Idx, Data] : enumerate(generateData(255)))
103     checkFormatAndArch(Data, Formats[Idx], Triple::UnknownArch);
104 }
105 
106 TEST(ELFObjectFileTest, MachineTestForVE) {
107   std::array<StringRef, 4> Formats = {"elf32-unknown", "elf32-unknown",
108                                       "elf64-ve", "elf64-ve"};
109   for (auto [Idx, Data] : enumerate(generateData(ELF::EM_VE)))
110     checkFormatAndArch(Data, Formats[Idx], Triple::ve);
111 }
112 
113 TEST(ELFObjectFileTest, MachineTestForX86_64) {
114   std::array<StringRef, 4> Formats = {"elf32-x86-64", "elf32-x86-64",
115                                       "elf64-x86-64", "elf64-x86-64"};
116   for (auto [Idx, Data] : enumerate(generateData(ELF::EM_X86_64)))
117     checkFormatAndArch(Data, Formats[Idx], Triple::x86_64);
118 }
119 
120 TEST(ELFObjectFileTest, MachineTestFor386) {
121   std::array<StringRef, 4> Formats = {"elf32-i386", "elf32-i386", "elf64-i386",
122                                       "elf64-i386"};
123   for (auto [Idx, Data] : enumerate(generateData(ELF::EM_386)))
124     checkFormatAndArch(Data, Formats[Idx], Triple::x86);
125 }
126 
127 TEST(ELFObjectFileTest, MachineTestForMIPS) {
128   std::array<StringRef, 4> Formats = {"elf32-mips", "elf32-mips", "elf64-mips",
129                                       "elf64-mips"};
130   std::array<Triple::ArchType, 4> Archs = {Triple::mipsel, Triple::mips,
131                                            Triple::mips64el, Triple::mips64};
132   for (auto [Idx, Data] : enumerate(generateData(ELF::EM_MIPS)))
133     checkFormatAndArch(Data, Formats[Idx], Archs[Idx]);
134 }
135 
136 TEST(ELFObjectFileTest, MachineTestForAMDGPU) {
137   std::array<StringRef, 4> Formats = {"elf32-amdgpu", "elf32-amdgpu",
138                                       "elf64-amdgpu", "elf64-amdgpu"};
139   for (auto [Idx, Data] : enumerate(generateData(ELF::EM_AMDGPU)))
140     checkFormatAndArch(Data, Formats[Idx], Triple::UnknownArch);
141 }
142 
143 TEST(ELFObjectFileTest, MachineTestForIAMCU) {
144   std::array<StringRef, 4> Formats = {"elf32-iamcu", "elf32-iamcu",
145                                       "elf64-unknown", "elf64-unknown"};
146   for (auto [Idx, Data] : enumerate(generateData(ELF::EM_IAMCU)))
147     checkFormatAndArch(Data, Formats[Idx], Triple::x86);
148 }
149 
150 TEST(ELFObjectFileTest, MachineTestForAARCH64) {
151   std::array<StringRef, 4> Formats = {"elf32-unknown", "elf32-unknown",
152                                       "elf64-littleaarch64",
153                                       "elf64-bigaarch64"};
154   std::array<Triple::ArchType, 4> Archs = {Triple::aarch64, Triple::aarch64_be,
155                                            Triple::aarch64, Triple::aarch64_be};
156   for (auto [Idx, Data] : enumerate(generateData(ELF::EM_AARCH64)))
157     checkFormatAndArch(Data, Formats[Idx], Archs[Idx]);
158 }
159 
160 TEST(ELFObjectFileTest, MachineTestForPPC64) {
161   std::array<StringRef, 4> Formats = {"elf32-unknown", "elf32-unknown",
162                                       "elf64-powerpcle", "elf64-powerpc"};
163   std::array<Triple::ArchType, 4> Archs = {Triple::ppc64le, Triple::ppc64,
164                                            Triple::ppc64le, Triple::ppc64};
165   for (auto [Idx, Data] : enumerate(generateData(ELF::EM_PPC64)))
166     checkFormatAndArch(Data, Formats[Idx], Archs[Idx]);
167 }
168 
169 TEST(ELFObjectFileTest, MachineTestForPPC) {
170   std::array<StringRef, 4> Formats = {"elf32-powerpcle", "elf32-powerpc",
171                                       "elf64-unknown", "elf64-unknown"};
172   std::array<Triple::ArchType, 4> Archs = {Triple::ppcle, Triple::ppc,
173                                            Triple::ppcle, Triple::ppc};
174   for (auto [Idx, Data] : enumerate(generateData(ELF::EM_PPC)))
175     checkFormatAndArch(Data, Formats[Idx], Archs[Idx]);
176 }
177 
178 TEST(ELFObjectFileTest, MachineTestForRISCV) {
179   std::array<StringRef, 4> Formats = {"elf32-littleriscv", "elf32-littleriscv",
180                                       "elf64-littleriscv", "elf64-littleriscv"};
181   std::array<Triple::ArchType, 4> Archs = {Triple::riscv32, Triple::riscv32,
182                                            Triple::riscv64, Triple::riscv64};
183   for (auto [Idx, Data] : enumerate(generateData(ELF::EM_RISCV)))
184     checkFormatAndArch(Data, Formats[Idx], Archs[Idx]);
185 }
186 
187 TEST(ELFObjectFileTest, MachineTestForARM) {
188   std::array<StringRef, 4> Formats = {"elf32-littlearm", "elf32-bigarm",
189                                       "elf64-unknown", "elf64-unknown"};
190   for (auto [Idx, Data] : enumerate(generateData(ELF::EM_ARM)))
191     checkFormatAndArch(Data, Formats[Idx], Triple::arm);
192 }
193 
194 TEST(ELFObjectFileTest, MachineTestForS390) {
195   std::array<StringRef, 4> Formats = {"elf32-unknown", "elf32-unknown",
196                                       "elf64-s390", "elf64-s390"};
197   for (auto [Idx, Data] : enumerate(generateData(ELF::EM_S390)))
198     checkFormatAndArch(Data, Formats[Idx], Triple::systemz);
199 }
200 
201 TEST(ELFObjectFileTest, MachineTestForSPARCV9) {
202   std::array<StringRef, 4> Formats = {"elf32-unknown", "elf32-unknown",
203                                       "elf64-sparc", "elf64-sparc"};
204   for (auto [Idx, Data] : enumerate(generateData(ELF::EM_SPARCV9)))
205     checkFormatAndArch(Data, Formats[Idx], Triple::sparcv9);
206 }
207 
208 TEST(ELFObjectFileTest, MachineTestForSPARC) {
209   std::array<StringRef, 4> Formats = {"elf32-sparc", "elf32-sparc",
210                                       "elf64-unknown", "elf64-unknown"};
211   std::array<Triple::ArchType, 4> Archs = {Triple::sparcel, Triple::sparc,
212                                            Triple::sparcel, Triple::sparc};
213   for (auto [Idx, Data] : enumerate(generateData(ELF::EM_SPARC)))
214     checkFormatAndArch(Data, Formats[Idx], Archs[Idx]);
215 }
216 
217 TEST(ELFObjectFileTest, MachineTestForSPARC32PLUS) {
218   std::array<StringRef, 4> Formats = {"elf32-sparc", "elf32-sparc",
219                                       "elf64-unknown", "elf64-unknown"};
220   std::array<Triple::ArchType, 4> Archs = {Triple::sparcel, Triple::sparc,
221                                            Triple::sparcel, Triple::sparc};
222   for (auto [Idx, Data] : enumerate(generateData(ELF::EM_SPARC32PLUS)))
223     checkFormatAndArch(Data, Formats[Idx], Archs[Idx]);
224 }
225 
226 TEST(ELFObjectFileTest, MachineTestForBPF) {
227   std::array<StringRef, 4> Formats = {"elf32-unknown", "elf32-unknown",
228                                       "elf64-bpf", "elf64-bpf"};
229   std::array<Triple::ArchType, 4> Archs = {Triple::bpfel, Triple::bpfeb,
230                                            Triple::bpfel, Triple::bpfeb};
231   for (auto [Idx, Data] : enumerate(generateData(ELF::EM_BPF)))
232     checkFormatAndArch(Data, Formats[Idx], Archs[Idx]);
233 }
234 
235 TEST(ELFObjectFileTest, MachineTestForAVR) {
236   std::array<StringRef, 4> Formats = {"elf32-avr", "elf32-avr", "elf64-unknown",
237                                       "elf64-unknown"};
238   for (auto [Idx, Data] : enumerate(generateData(ELF::EM_AVR)))
239     checkFormatAndArch(Data, Formats[Idx], Triple::avr);
240 }
241 
242 TEST(ELFObjectFileTest, MachineTestForHEXAGON) {
243   std::array<StringRef, 4> Formats = {"elf32-hexagon", "elf32-hexagon",
244                                       "elf64-unknown", "elf64-unknown"};
245   for (auto [Idx, Data] : enumerate(generateData(ELF::EM_HEXAGON)))
246     checkFormatAndArch(Data, Formats[Idx], Triple::hexagon);
247 }
248 
249 TEST(ELFObjectFileTest, MachineTestForLANAI) {
250   std::array<StringRef, 4> Formats = {"elf32-lanai", "elf32-lanai",
251                                       "elf64-unknown", "elf64-unknown"};
252   for (auto [Idx, Data] : enumerate(generateData(ELF::EM_LANAI)))
253     checkFormatAndArch(Data, Formats[Idx], Triple::lanai);
254 }
255 
256 TEST(ELFObjectFileTest, MachineTestForMSP430) {
257   std::array<StringRef, 4> Formats = {"elf32-msp430", "elf32-msp430",
258                                       "elf64-unknown", "elf64-unknown"};
259   for (auto [Idx, Data] : enumerate(generateData(ELF::EM_MSP430)))
260     checkFormatAndArch(Data, Formats[Idx], Triple::msp430);
261 }
262 
263 TEST(ELFObjectFileTest, MachineTestForLoongArch) {
264   std::array<StringRef, 4> Formats = {"elf32-loongarch", "elf32-loongarch",
265                                       "elf64-loongarch", "elf64-loongarch"};
266   std::array<Triple::ArchType, 4> Archs = {
267       Triple::loongarch32, Triple::loongarch32, Triple::loongarch64,
268       Triple::loongarch64};
269   for (auto [Idx, Data] : enumerate(generateData(ELF::EM_LOONGARCH)))
270     checkFormatAndArch(Data, Formats[Idx], Archs[Idx]);
271 }
272 
273 TEST(ELFObjectFileTest, MachineTestForCSKY) {
274   std::array<StringRef, 4> Formats = {"elf32-csky", "elf32-csky",
275                                       "elf64-unknown", "elf64-unknown"};
276   for (auto [Idx, Data] : enumerate(generateData(ELF::EM_CSKY)))
277     checkFormatAndArch(Data, Formats[Idx], Triple::csky);
278 }
279 
280 TEST(ELFObjectFileTest, MachineTestForXtensa) {
281   std::array<StringRef, 4> Formats = {"elf32-xtensa", "elf32-xtensa",
282                                       "elf64-unknown", "elf64-unknown"};
283   for (auto [Idx, Data] : enumerate(generateData(ELF::EM_XTENSA)))
284     checkFormatAndArch(Data, Formats[Idx], Triple::xtensa);
285 }
286 
287 TEST(ELFObjectFileTest, CheckOSAndTriple) {
288   std::tuple<uint16_t, uint8_t, StringRef> Formats[] = {
289       {ELF::EM_AMDGPU, ELF::ELFOSABI_AMDGPU_HSA, "amdgcn-amd-amdhsa"},
290       {ELF::EM_X86_64, ELF::ELFOSABI_LINUX, "x86_64--linux"},
291       {ELF::EM_X86_64, ELF::ELFOSABI_NETBSD, "x86_64--netbsd"},
292       {ELF::EM_X86_64, ELF::ELFOSABI_HURD, "x86_64--hurd"},
293       {ELF::EM_X86_64, ELF::ELFOSABI_SOLARIS, "x86_64--solaris"},
294       {ELF::EM_X86_64, ELF::ELFOSABI_AIX, "x86_64--aix"},
295       {ELF::EM_X86_64, ELF::ELFOSABI_FREEBSD, "x86_64--freebsd"},
296       {ELF::EM_X86_64, ELF::ELFOSABI_OPENBSD, "x86_64--openbsd"},
297       {ELF::EM_CUDA, ELF::ELFOSABI_CUDA, "nvptx64-nvidia-cuda"}};
298   for (auto [Machine, OS, Triple] : Formats) {
299     const DataForTest D(ELF::ELFCLASS64, ELF::ELFDATA2LSB, Machine, OS,
300                         ELF::EF_AMDGPU_MACH_AMDGCN_LAST);
301     Expected<ELF64LEObjectFile> ELFObjOrErr = ELF64LEObjectFile::create(
302         MemoryBufferRef(toStringRef(D.Data), "dummyELF"));
303     ASSERT_THAT_EXPECTED(ELFObjOrErr, Succeeded());
304 
305     auto &ELFObj = *ELFObjOrErr;
306     llvm::Triple TheTriple = ELFObj.makeTriple();
307 
308     // The AMDGPU architecture will be unknown on big-endian testers.
309     if (TheTriple.getArch() == Triple::UnknownArch)
310       continue;
311 
312     EXPECT_EQ(Triple, TheTriple.getTriple());
313   }
314 }
315 
316 // ELF relative relocation type test.
317 TEST(ELFObjectFileTest, RelativeRelocationTypeTest) {
318   EXPECT_EQ(ELF::R_CKCORE_RELATIVE, getELFRelativeRelocationType(ELF::EM_CSKY));
319 }
320 
321 template <class ELFT>
322 static Expected<ELFObjectFile<ELFT>> toBinary(SmallVectorImpl<char> &Storage,
323                                               StringRef Yaml) {
324   raw_svector_ostream OS(Storage);
325   yaml::Input YIn(Yaml);
326   if (!yaml::convertYAML(YIn, OS, [](const Twine &Msg) {}))
327     return createStringError(std::errc::invalid_argument,
328                              "unable to convert YAML");
329   return ELFObjectFile<ELFT>::create(MemoryBufferRef(OS.str(), "dummyELF"));
330 }
331 
332 // Check we are able to create an ELFObjectFile even when the content of the
333 // SHT_SYMTAB_SHNDX section can't be read properly.
334 TEST(ELFObjectFileTest, InvalidSymtabShndxTest) {
335   SmallString<0> Storage;
336   Expected<ELFObjectFile<ELF64LE>> ExpectedFile = toBinary<ELF64LE>(Storage, R"(
337 --- !ELF
338 FileHeader:
339   Class: ELFCLASS64
340   Data:  ELFDATA2LSB
341   Type:  ET_REL
342 Sections:
343   - Name:    .symtab_shndx
344     Type:    SHT_SYMTAB_SHNDX
345     Entries: [ 0 ]
346     ShSize: 0xFFFFFFFF
347 )");
348 
349   ASSERT_THAT_EXPECTED(ExpectedFile, Succeeded());
350 }
351 
352 // Test that we are able to create an ELFObjectFile even when loadable segments
353 // are unsorted by virtual address.
354 // Test that ELFFile<ELFT>::toMappedAddr works properly in this case.
355 
356 TEST(ELFObjectFileTest, InvalidLoadSegmentsOrderTest) {
357   SmallString<0> Storage;
358   Expected<ELFObjectFile<ELF64LE>> ExpectedFile = toBinary<ELF64LE>(Storage, R"(
359 --- !ELF
360 FileHeader:
361   Class: ELFCLASS64
362   Data:  ELFDATA2LSB
363   Type:  ET_EXEC
364 Sections:
365   - Name:         .foo
366     Type:         SHT_PROGBITS
367     Address:      0x1000
368     Offset:       0x3000
369     ContentArray: [ 0x11 ]
370   - Name:         .bar
371     Type:         SHT_PROGBITS
372     Address:      0x2000
373     Offset:       0x4000
374     ContentArray: [ 0x99 ]
375 ProgramHeaders:
376   - Type:     PT_LOAD
377     VAddr:    0x2000
378     FirstSec: .bar
379     LastSec:  .bar
380   - Type:     PT_LOAD
381     VAddr:    0x1000
382     FirstSec: .foo
383     LastSec:  .foo
384 )");
385 
386   ASSERT_THAT_EXPECTED(ExpectedFile, Succeeded());
387 
388   std::string WarnString;
389   auto ToMappedAddr = [&](uint64_t Addr) -> const uint8_t * {
390     Expected<const uint8_t *> DataOrErr =
391         ExpectedFile->getELFFile().toMappedAddr(Addr, [&](const Twine &Msg) {
392           EXPECT_TRUE(WarnString.empty());
393           WarnString = Msg.str();
394           return Error::success();
395         });
396 
397     if (!DataOrErr) {
398       ADD_FAILURE() << toString(DataOrErr.takeError());
399       return nullptr;
400     }
401 
402     EXPECT_TRUE(WarnString ==
403                 "loadable segments are unsorted by virtual address");
404     WarnString = "";
405     return *DataOrErr;
406   };
407 
408   const uint8_t *Data = ToMappedAddr(0x1000);
409   ASSERT_TRUE(Data);
410   MemoryBufferRef Buf = ExpectedFile->getMemoryBufferRef();
411   EXPECT_EQ((const char *)Data - Buf.getBufferStart(), 0x3000);
412   EXPECT_EQ(Data[0], 0x11);
413 
414   Data = ToMappedAddr(0x2000);
415   ASSERT_TRUE(Data);
416   Buf = ExpectedFile->getMemoryBufferRef();
417   EXPECT_EQ((const char *)Data - Buf.getBufferStart(), 0x4000);
418   EXPECT_EQ(Data[0], 0x99);
419 }
420 
421 // This is a test for API that is related to symbols.
422 // We check that errors are properly reported here.
423 TEST(ELFObjectFileTest, InvalidSymbolTest) {
424   SmallString<0> Storage;
425   Expected<ELFObjectFile<ELF64LE>> ElfOrErr = toBinary<ELF64LE>(Storage, R"(
426 --- !ELF
427 FileHeader:
428   Class:   ELFCLASS64
429   Data:    ELFDATA2LSB
430   Type:    ET_DYN
431   Machine: EM_X86_64
432 Sections:
433   - Name: .symtab
434     Type: SHT_SYMTAB
435 )");
436 
437   ASSERT_THAT_EXPECTED(ElfOrErr, Succeeded());
438   const ELFFile<ELF64LE> &Elf = ElfOrErr->getELFFile();
439   const ELFObjectFile<ELF64LE> &Obj = *ElfOrErr;
440 
441   Expected<const typename ELF64LE::Shdr *> SymtabSecOrErr = Elf.getSection(1);
442   ASSERT_THAT_EXPECTED(SymtabSecOrErr, Succeeded());
443   ASSERT_EQ((*SymtabSecOrErr)->sh_type, ELF::SHT_SYMTAB);
444 
445   auto DoCheck = [&](unsigned BrokenSymIndex, const char *ErrMsg) {
446     ELFSymbolRef BrokenSym = Obj.toSymbolRef(*SymtabSecOrErr, BrokenSymIndex);
447 
448     // 1) Check the behavior of ELFObjectFile<ELFT>::getSymbolName().
449     //    SymbolRef::getName() calls it internally. We can't test it directly,
450     //    because it is protected.
451     EXPECT_THAT_ERROR(BrokenSym.getName().takeError(),
452                       FailedWithMessage(ErrMsg));
453 
454     // 2) Check the behavior of ELFObjectFile<ELFT>::getSymbol().
455     EXPECT_THAT_ERROR(Obj.getSymbol(BrokenSym.getRawDataRefImpl()).takeError(),
456                       FailedWithMessage(ErrMsg));
457 
458     // 3) Check the behavior of ELFObjectFile<ELFT>::getSymbolSection().
459     //    SymbolRef::getSection() calls it internally. We can't test it
460     //    directly, because it is protected.
461     EXPECT_THAT_ERROR(BrokenSym.getSection().takeError(),
462                       FailedWithMessage(ErrMsg));
463 
464     // 4) Check the behavior of ELFObjectFile<ELFT>::getSymbolFlags().
465     //    SymbolRef::getFlags() calls it internally. We can't test it directly,
466     //    because it is protected.
467     EXPECT_THAT_ERROR(BrokenSym.getFlags().takeError(),
468                       FailedWithMessage(ErrMsg));
469 
470     // 5) Check the behavior of ELFObjectFile<ELFT>::getSymbolType().
471     //    SymbolRef::getType() calls it internally. We can't test it directly,
472     //    because it is protected.
473     EXPECT_THAT_ERROR(BrokenSym.getType().takeError(),
474                       FailedWithMessage(ErrMsg));
475 
476     // 6) Check the behavior of ELFObjectFile<ELFT>::getSymbolAddress().
477     //    SymbolRef::getAddress() calls it internally. We can't test it
478     //    directly, because it is protected.
479     EXPECT_THAT_ERROR(BrokenSym.getAddress().takeError(),
480                       FailedWithMessage(ErrMsg));
481 
482     // Finally, check the `ELFFile<ELFT>::getEntry` API. This is an underlying
483     // method that generates errors for all cases above.
484     EXPECT_THAT_EXPECTED(
485         Elf.getEntry<typename ELF64LE::Sym>(**SymtabSecOrErr, 0), Succeeded());
486     EXPECT_THAT_ERROR(
487         Elf.getEntry<typename ELF64LE::Sym>(**SymtabSecOrErr, BrokenSymIndex)
488             .takeError(),
489         FailedWithMessage(ErrMsg));
490   };
491 
492   // We create a symbol with an index that is too large to exist in the symbol
493   // table.
494   DoCheck(0x1, "can't read an entry at 0x18: it goes past the end of the "
495                "section (0x18)");
496 
497   // We create a symbol with an index that is too large to exist in the object.
498   DoCheck(0xFFFFFFFF, "can't read an entry at 0x17ffffffe8: it goes past the "
499                       "end of the section (0x18)");
500 }
501 
502 // Tests for error paths of the ELFFile::decodeBBAddrMap API.
503 TEST(ELFObjectFileTest, InvalidDecodeBBAddrMap) {
504   StringRef CommonYamlString(R"(
505 --- !ELF
506 FileHeader:
507   Class: ELFCLASS64
508   Data:  ELFDATA2LSB
509   Type:  ET_EXEC
510 Sections:
511   - Type: SHT_LLVM_BB_ADDR_MAP
512     Name: .llvm_bb_addr_map
513     Entries:
514       - Address: 0x11111
515 )");
516 
517   auto DoCheck = [&](StringRef YamlString, const char *ErrMsg) {
518     SmallString<0> Storage;
519     Expected<ELFObjectFile<ELF64LE>> ElfOrErr =
520         toBinary<ELF64LE>(Storage, YamlString);
521     ASSERT_THAT_EXPECTED(ElfOrErr, Succeeded());
522     const ELFFile<ELF64LE> &Elf = ElfOrErr->getELFFile();
523 
524     Expected<const typename ELF64LE::Shdr *> BBAddrMapSecOrErr =
525         Elf.getSection(1);
526     ASSERT_THAT_EXPECTED(BBAddrMapSecOrErr, Succeeded());
527     EXPECT_THAT_ERROR(Elf.decodeBBAddrMap(**BBAddrMapSecOrErr).takeError(),
528                       FailedWithMessage(ErrMsg));
529   };
530 
531   // Check that we can detect unsupported versions.
532   SmallString<128> UnsupportedVersionYamlString(CommonYamlString);
533   UnsupportedVersionYamlString += R"(
534         Version: 3
535         BBEntries:
536           - AddressOffset: 0x0
537             Size:          0x1
538             Metadata:      0x2
539 )";
540 
541   {
542     SCOPED_TRACE("unsupported version");
543     DoCheck(UnsupportedVersionYamlString,
544             "unsupported SHT_LLVM_BB_ADDR_MAP version: 3");
545   }
546 
547   SmallString<128> CommonVersionedYamlString(CommonYamlString);
548   CommonVersionedYamlString += R"(
549         Version: 2
550         BBEntries:
551           - ID:            1
552             AddressOffset: 0x0
553             Size:          0x1
554             Metadata:      0x2
555 )";
556 
557   // Check that we can detect the malformed encoding when the section is
558   // truncated.
559   SmallString<128> TruncatedYamlString(CommonVersionedYamlString);
560   TruncatedYamlString += R"(
561     ShSize: 0xb
562 )";
563   {
564     SCOPED_TRACE("truncated section");
565     DoCheck(TruncatedYamlString,
566             "unable to decode LEB128 at offset 0x0000000b: "
567             "malformed uleb128, extends past end");
568   }
569 
570   // Check that we can detect when the encoded BB entry fields exceed the UINT32
571   // limit.
572   SmallVector<SmallString<128>, 3> OverInt32LimitYamlStrings(
573       3, CommonVersionedYamlString);
574   OverInt32LimitYamlStrings[0] += R"(
575           - ID:            1
576             AddressOffset: 0x100000000
577             Size:          0xFFFFFFFF
578             Metadata:      0xFFFFFFFF
579 )";
580 
581   OverInt32LimitYamlStrings[1] += R"(
582           - ID:            2
583             AddressOffset: 0xFFFFFFFF
584             Size:          0x100000000
585             Metadata:      0xFFFFFFFF
586 )";
587 
588   OverInt32LimitYamlStrings[2] += R"(
589           - ID:            3
590             AddressOffset: 0xFFFFFFFF
591             Size:          0xFFFFFFFF
592             Metadata:      0x100000000
593 )";
594 
595   {
596     SCOPED_TRACE("overlimit fields");
597     DoCheck(OverInt32LimitYamlStrings[0],
598             "ULEB128 value at offset 0x10 exceeds UINT32_MAX (0x100000000)");
599     DoCheck(OverInt32LimitYamlStrings[1],
600             "ULEB128 value at offset 0x15 exceeds UINT32_MAX (0x100000000)");
601     DoCheck(OverInt32LimitYamlStrings[2],
602             "ULEB128 value at offset 0x1a exceeds UINT32_MAX (0x100000000)");
603   }
604 
605   // Check the proper error handling when the section has fields exceeding
606   // UINT32 and is also truncated. This is for checking that we don't generate
607   // unhandled errors.
608   SmallVector<SmallString<128>, 3> OverInt32LimitAndTruncated(
609       3, OverInt32LimitYamlStrings[1]);
610   // Truncate before the end of the 5-byte field.
611   OverInt32LimitAndTruncated[0] += R"(
612     ShSize: 0x19
613 )";
614   // Truncate at the end of the 5-byte field.
615   OverInt32LimitAndTruncated[1] += R"(
616     ShSize: 0x1a
617 )";
618   // Truncate after the end of the 5-byte field.
619   OverInt32LimitAndTruncated[2] += R"(
620     ShSize: 0x1b
621 )";
622 
623   {
624     SCOPED_TRACE("overlimit fields, truncated section");
625     DoCheck(OverInt32LimitAndTruncated[0],
626             "unable to decode LEB128 at offset 0x00000015: malformed uleb128, "
627             "extends past end");
628     DoCheck(OverInt32LimitAndTruncated[1],
629             "ULEB128 value at offset 0x15 exceeds UINT32_MAX (0x100000000)");
630     DoCheck(OverInt32LimitAndTruncated[2],
631             "ULEB128 value at offset 0x15 exceeds UINT32_MAX (0x100000000)");
632   }
633 
634   // Check for proper error handling when the 'NumBlocks' field is overridden
635   // with an out-of-range value.
636   SmallString<128> OverLimitNumBlocks(CommonVersionedYamlString);
637   OverLimitNumBlocks += R"(
638         NumBlocks: 0x100000000
639 )";
640 
641   {
642     SCOPED_TRACE("overlimit 'NumBlocks' field");
643     DoCheck(OverLimitNumBlocks,
644             "ULEB128 value at offset 0xa exceeds UINT32_MAX (0x100000000)");
645   }
646 }
647 
648 // Test for the ELFObjectFile::readBBAddrMap API.
649 TEST(ELFObjectFileTest, ReadBBAddrMap) {
650   StringRef CommonYamlString(R"(
651 --- !ELF
652 FileHeader:
653   Class: ELFCLASS64
654   Data:  ELFDATA2LSB
655   Type:  ET_EXEC
656 Sections:
657   - Name: .llvm_bb_addr_map_1
658     Type: SHT_LLVM_BB_ADDR_MAP
659     Link: 1
660     Entries:
661       - Version: 2
662         Address: 0x11111
663         BBEntries:
664           - ID:            1
665             AddressOffset: 0x0
666             Size:          0x1
667             Metadata:      0x2
668   - Name: .llvm_bb_addr_map_2
669     Type: SHT_LLVM_BB_ADDR_MAP
670     Link: 1
671     Entries:
672       - Version: 2
673         Address: 0x22222
674         BBEntries:
675           - ID:            2
676             AddressOffset: 0x0
677             Size:          0x2
678             Metadata:      0x4
679   - Name: .llvm_bb_addr_map_3
680     Type: SHT_LLVM_BB_ADDR_MAP
681     Link: 2
682     Entries:
683       - Version: 1
684         Address: 0x33333
685         BBEntries:
686           - ID:            0
687             AddressOffset: 0x0
688             Size:          0x3
689             Metadata:      0x6
690   - Name: .llvm_bb_addr_map_4
691     Type: SHT_LLVM_BB_ADDR_MAP_V0
692   # Link: 0 (by default, can be overriden)
693     Entries:
694       - Version: 0
695         Address: 0x44444
696         BBEntries:
697           - ID:            0
698             AddressOffset: 0x0
699             Size:          0x4
700             Metadata:      0x18
701 )");
702 
703   BBAddrMap E1(0x11111, {{1, 0x0, 0x1, {false, true, false, false, false}}});
704   BBAddrMap E2(0x22222, {{2, 0x0, 0x2, {false, false, true, false, false}}});
705   BBAddrMap E3(0x33333, {{0, 0x0, 0x3, {false, true, true, false, false}}});
706   BBAddrMap E4(0x44444, {{0, 0x0, 0x4, {false, false, false, true, true}}});
707 
708   std::vector<BBAddrMap> Section0BBAddrMaps = {E4};
709   std::vector<BBAddrMap> Section1BBAddrMaps = {E3};
710   std::vector<BBAddrMap> Section2BBAddrMaps = {E1, E2};
711   std::vector<BBAddrMap> AllBBAddrMaps = {E1, E2, E3, E4};
712 
713   auto DoCheckSucceeds = [&](StringRef YamlString,
714                              std::optional<unsigned> TextSectionIndex,
715                              std::vector<BBAddrMap> ExpectedResult) {
716     SCOPED_TRACE("for TextSectionIndex: " +
717                  (TextSectionIndex ? llvm::Twine(*TextSectionIndex) : "{}") +
718                  " and object yaml:\n" + YamlString);
719     SmallString<0> Storage;
720     Expected<ELFObjectFile<ELF64LE>> ElfOrErr =
721         toBinary<ELF64LE>(Storage, YamlString);
722     ASSERT_THAT_EXPECTED(ElfOrErr, Succeeded());
723 
724     Expected<const typename ELF64LE::Shdr *> BBAddrMapSecOrErr =
725         ElfOrErr->getELFFile().getSection(1);
726     ASSERT_THAT_EXPECTED(BBAddrMapSecOrErr, Succeeded());
727     auto BBAddrMaps = ElfOrErr->readBBAddrMap(TextSectionIndex);
728     ASSERT_THAT_EXPECTED(BBAddrMaps, Succeeded());
729     EXPECT_EQ(*BBAddrMaps, ExpectedResult);
730   };
731 
732   auto DoCheckFails = [&](StringRef YamlString,
733                           std::optional<unsigned> TextSectionIndex,
734                           const char *ErrMsg) {
735     SCOPED_TRACE("for TextSectionIndex: " +
736                  (TextSectionIndex ? llvm::Twine(*TextSectionIndex) : "{}") +
737                  " and object yaml:\n" + YamlString);
738     SmallString<0> Storage;
739     Expected<ELFObjectFile<ELF64LE>> ElfOrErr =
740         toBinary<ELF64LE>(Storage, YamlString);
741     ASSERT_THAT_EXPECTED(ElfOrErr, Succeeded());
742 
743     Expected<const typename ELF64LE::Shdr *> BBAddrMapSecOrErr =
744         ElfOrErr->getELFFile().getSection(1);
745     ASSERT_THAT_EXPECTED(BBAddrMapSecOrErr, Succeeded());
746     EXPECT_THAT_ERROR(ElfOrErr->readBBAddrMap(TextSectionIndex).takeError(),
747                       FailedWithMessage(ErrMsg));
748   };
749 
750   {
751     SCOPED_TRACE("normal sections");
752     // Check that we can retrieve the data in the normal case.
753     DoCheckSucceeds(CommonYamlString, /*TextSectionIndex=*/std::nullopt,
754                     AllBBAddrMaps);
755     DoCheckSucceeds(CommonYamlString, /*TextSectionIndex=*/0,
756                     Section0BBAddrMaps);
757     DoCheckSucceeds(CommonYamlString, /*TextSectionIndex=*/2,
758                     Section1BBAddrMaps);
759     DoCheckSucceeds(CommonYamlString, /*TextSectionIndex=*/1,
760                     Section2BBAddrMaps);
761     // Check that when no bb-address-map section is found for a text section,
762     // we return an empty result.
763     DoCheckSucceeds(CommonYamlString, /*TextSectionIndex=*/3, {});
764   }
765 
766   // Check that we detect when a bb-addr-map section is linked to an invalid
767   // (not present) section.
768   SmallString<128> InvalidLinkedYamlString(CommonYamlString);
769   InvalidLinkedYamlString += R"(
770     Link: 10
771 )";
772 
773   DoCheckFails(InvalidLinkedYamlString, /*TextSectionIndex=*/4,
774                "unable to get the linked-to section for "
775                "SHT_LLVM_BB_ADDR_MAP_V0 section with index 4: invalid section "
776                "index: 10");
777   {
778     SCOPED_TRACE("invalid linked section");
779     // Linked sections are not checked when we don't target a specific text
780     // section.
781     DoCheckSucceeds(InvalidLinkedYamlString, /*TextSectionIndex=*/std::nullopt,
782                     AllBBAddrMaps);
783   }
784 
785   // Check that we can detect when bb-address-map decoding fails.
786   SmallString<128> TruncatedYamlString(CommonYamlString);
787   TruncatedYamlString += R"(
788     ShSize: 0x8
789 )";
790 
791   {
792     SCOPED_TRACE("truncated section");
793     DoCheckFails(TruncatedYamlString, /*TextSectionIndex=*/std::nullopt,
794                  "unable to read SHT_LLVM_BB_ADDR_MAP_V0 section with index 4: "
795                  "unable to decode LEB128 at offset 0x00000008: malformed "
796                  "uleb128, extends past end");
797 
798     // Check that we can read the other section's bb-address-maps which are
799     // valid.
800     DoCheckSucceeds(TruncatedYamlString, /*TextSectionIndex=*/2,
801                     Section1BBAddrMaps);
802   }
803 }
804 
805 // Tests for error paths of the ELFFile::decodeBBAddrMap with PGOAnalysisMap
806 // API.
807 TEST(ELFObjectFileTest, InvalidDecodePGOAnalysisMap) {
808   StringRef CommonYamlString(R"(
809 --- !ELF
810 FileHeader:
811   Class: ELFCLASS64
812   Data:  ELFDATA2LSB
813   Type:  ET_EXEC
814 Sections:
815   - Type: SHT_LLVM_BB_ADDR_MAP
816     Name: .llvm_bb_addr_map
817     Entries:
818       - Address: 0x11111
819 )");
820 
821   auto DoCheck = [&](StringRef YamlString, const char *ErrMsg) {
822     SmallString<0> Storage;
823     Expected<ELFObjectFile<ELF64LE>> ElfOrErr =
824         toBinary<ELF64LE>(Storage, YamlString);
825     ASSERT_THAT_EXPECTED(ElfOrErr, Succeeded());
826     const ELFFile<ELF64LE> &Elf = ElfOrErr->getELFFile();
827 
828     Expected<const typename ELF64LE::Shdr *> BBAddrMapSecOrErr =
829         Elf.getSection(1);
830     ASSERT_THAT_EXPECTED(BBAddrMapSecOrErr, Succeeded());
831 
832     std::vector<PGOAnalysisMap> PGOAnalyses;
833     EXPECT_THAT_ERROR(
834         Elf.decodeBBAddrMap(**BBAddrMapSecOrErr, nullptr, &PGOAnalyses)
835             .takeError(),
836         FailedWithMessage(ErrMsg));
837   };
838 
839   // Check that we can detect unsupported versions that are too old.
840   SmallString<128> UnsupportedLowVersionYamlString(CommonYamlString);
841   UnsupportedLowVersionYamlString += R"(
842         Version: 1
843         Feature: 0x4
844         BBEntries:
845           - AddressOffset: 0x0
846             Size:          0x1
847             Metadata:      0x2
848 )";
849 
850   {
851     SCOPED_TRACE("unsupported version");
852     DoCheck(UnsupportedLowVersionYamlString,
853             "version should be >= 2 for SHT_LLVM_BB_ADDR_MAP when PGO features "
854             "are enabled: version = 1 feature = 4");
855   }
856 
857   SmallString<128> CommonVersionedYamlString(CommonYamlString);
858   CommonVersionedYamlString += R"(
859         Version: 2
860         BBEntries:
861           - ID:            1
862             AddressOffset: 0x0
863             Size:          0x1
864             Metadata:      0x2
865 )";
866 
867   // Check that we fail when function entry count is enabled but not provided.
868   SmallString<128> MissingFuncEntryCount(CommonYamlString);
869   MissingFuncEntryCount += R"(
870         Version: 2
871         Feature: 0x01
872 )";
873 
874   {
875     SCOPED_TRACE("missing function entry count");
876     DoCheck(MissingFuncEntryCount,
877             "unable to decode LEB128 at offset 0x0000000b: malformed uleb128, "
878             "extends past end");
879   }
880 
881   // Check that we fail when basic block frequency is enabled but not provided.
882   SmallString<128> MissingBBFreq(CommonYamlString);
883   MissingBBFreq += R"(
884         Version: 2
885         Feature: 0x02
886         BBEntries:
887           - ID:            1
888             AddressOffset: 0x0
889             Size:          0x1
890             Metadata:      0x2
891 )";
892 
893   {
894     SCOPED_TRACE("missing bb frequency");
895     DoCheck(MissingBBFreq, "unable to decode LEB128 at offset 0x0000000f: "
896                            "malformed uleb128, extends past end");
897   }
898 
899   // Check that we fail when branch probability is enabled but not provided.
900   SmallString<128> MissingBrProb(CommonYamlString);
901   MissingBrProb += R"(
902         Version: 2
903         Feature: 0x04
904         BBEntries:
905           - ID:            1
906             AddressOffset: 0x0
907             Size:          0x1
908             Metadata:      0x6
909           - ID:            2
910             AddressOffset: 0x1
911             Size:          0x1
912             Metadata:      0x2
913           - ID:            3
914             AddressOffset: 0x2
915             Size:          0x1
916             Metadata:      0x2
917     PGOAnalyses:
918       - PGOBBEntries:
919          - Successors:
920             - ID:          2
921               BrProb:      0x80000000
922             - ID:          3
923               BrProb:      0x80000000
924          - Successors:
925             - ID:          3
926               BrProb:      0xF0000000
927 )";
928 
929   {
930     SCOPED_TRACE("missing branch probability");
931     DoCheck(MissingBrProb, "unable to decode LEB128 at offset 0x00000017: "
932                            "malformed uleb128, extends past end");
933   }
934 }
935 
936 // Test for the ELFObjectFile::readBBAddrMap API with PGOAnalysisMap.
937 TEST(ELFObjectFileTest, ReadPGOAnalysisMap) {
938   StringRef CommonYamlString(R"(
939 --- !ELF
940 FileHeader:
941   Class: ELFCLASS64
942   Data:  ELFDATA2LSB
943   Type:  ET_EXEC
944 Sections:
945   - Name: .llvm_bb_addr_map_1
946     Type: SHT_LLVM_BB_ADDR_MAP
947     Link: 1
948     Entries:
949       - Version: 2
950         Address: 0x11111
951         Feature: 0x1
952         BBEntries:
953           - ID:            1
954             AddressOffset: 0x0
955             Size:          0x1
956             Metadata:      0x2
957     PGOAnalyses:
958       - FuncEntryCount: 892
959   - Name: .llvm_bb_addr_map_2
960     Type: SHT_LLVM_BB_ADDR_MAP
961     Link: 1
962     Entries:
963       - Version: 2
964         Address: 0x22222
965         Feature: 0x2
966         BBEntries:
967           - ID:            2
968             AddressOffset: 0x0
969             Size:          0x2
970             Metadata:      0x4
971     PGOAnalyses:
972       - PGOBBEntries:
973          - BBFreq:         343
974   - Name: .llvm_bb_addr_map_3
975     Type: SHT_LLVM_BB_ADDR_MAP
976     Link: 2
977     Entries:
978       - Version: 2
979         Address: 0x33333
980         Feature: 0x4
981         BBEntries:
982           - ID:            0
983             AddressOffset: 0x0
984             Size:          0x3
985             Metadata:      0x6
986           - ID:            1
987             AddressOffset: 0x0
988             Size:          0x3
989             Metadata:      0x4
990           - ID:            2
991             AddressOffset: 0x0
992             Size:          0x3
993             Metadata:      0x0
994     PGOAnalyses:
995       - PGOBBEntries:
996          - Successors:
997             - ID:          1
998               BrProb:      0x11111111
999             - ID:          2
1000               BrProb:      0xeeeeeeee
1001          - Successors:
1002             - ID:          2
1003               BrProb:      0xffffffff
1004          - Successors:     []
1005   - Name: .llvm_bb_addr_map_4
1006     Type: SHT_LLVM_BB_ADDR_MAP
1007   # Link: 0 (by default, can be overriden)
1008     Entries:
1009       - Version: 2
1010         Address: 0x44444
1011         Feature: 0x7
1012         BBEntries:
1013           - ID:            0
1014             AddressOffset: 0x0
1015             Size:          0x4
1016             Metadata:      0x18
1017           - ID:            1
1018             AddressOffset: 0x0
1019             Size:          0x4
1020             Metadata:      0x0
1021           - ID:            2
1022             AddressOffset: 0x0
1023             Size:          0x4
1024             Metadata:      0x0
1025           - ID:            3
1026             AddressOffset: 0x0
1027             Size:          0x4
1028             Metadata:      0x0
1029     PGOAnalyses:
1030       - FuncEntryCount: 1000
1031         PGOBBEntries:
1032           - BBFreq:         1000
1033             Successors:
1034             - ID:          1
1035               BrProb:      0x22222222
1036             - ID:          2
1037               BrProb:      0x33333333
1038             - ID:          3
1039               BrProb:      0xaaaaaaaa
1040           - BBFreq:         133
1041             Successors:
1042             - ID:          2
1043               BrProb:      0x11111111
1044             - ID:          3
1045               BrProb:      0xeeeeeeee
1046           - BBFreq:         18
1047             Successors:
1048             - ID:          3
1049               BrProb:      0xffffffff
1050           - BBFreq:         1000
1051             Successors:    []
1052   - Name: .llvm_bb_addr_map_5
1053     Type: SHT_LLVM_BB_ADDR_MAP
1054   # Link: 0 (by default, can be overriden)
1055     Entries:
1056       - Version: 2
1057         Address: 0x55555
1058         Feature: 0x0
1059         BBEntries:
1060           - ID:            2
1061             AddressOffset: 0x0
1062             Size:          0x2
1063             Metadata:      0x4
1064     PGOAnalyses: [{}]
1065  )");
1066 
1067   BBAddrMap E1(0x11111, {{1, 0x0, 0x1, {false, true, false, false, false}}});
1068   PGOAnalysisMap P1 = {892, {}, {true, false, false}};
1069   BBAddrMap E2(0x22222, {{2, 0x0, 0x2, {false, false, true, false, false}}});
1070   PGOAnalysisMap P2 = {{}, {{BlockFrequency(343), {}}}, {false, true, false}};
1071   BBAddrMap E3(0x33333, {{0, 0x0, 0x3, {false, true, true, false, false}},
1072                          {1, 0x3, 0x3, {false, false, true, false, false}},
1073                          {2, 0x6, 0x3, {false, false, false, false, false}}});
1074   PGOAnalysisMap P3 = {{},
1075                        {{{},
1076                          {{1, BranchProbability::getRaw(0x1111'1111)},
1077                           {2, BranchProbability::getRaw(0xeeee'eeee)}}},
1078                         {{}, {{2, BranchProbability::getRaw(0xffff'ffff)}}},
1079                         {{}, {}}},
1080                        {false, false, true}};
1081   BBAddrMap E4(0x44444, {{0, 0x0, 0x4, {false, false, false, true, true}},
1082                          {1, 0x4, 0x4, {false, false, false, false, false}},
1083                          {2, 0x8, 0x4, {false, false, false, false, false}},
1084                          {3, 0xc, 0x4, {false, false, false, false, false}}});
1085   PGOAnalysisMap P4 = {
1086       1000,
1087       {{BlockFrequency(1000),
1088         {{1, BranchProbability::getRaw(0x2222'2222)},
1089          {2, BranchProbability::getRaw(0x3333'3333)},
1090          {3, BranchProbability::getRaw(0xaaaa'aaaa)}}},
1091        {BlockFrequency(133),
1092         {{2, BranchProbability::getRaw(0x1111'1111)},
1093          {3, BranchProbability::getRaw(0xeeee'eeee)}}},
1094        {BlockFrequency(18), {{3, BranchProbability::getRaw(0xffff'ffff)}}},
1095        {BlockFrequency(1000), {}}},
1096       {true, true, true}};
1097   BBAddrMap E5(0x55555, {{2, 0x0, 0x2, {false, false, true, false, false}}});
1098   PGOAnalysisMap P5 = {{}, {}, {false, false, false}};
1099 
1100   std::vector<BBAddrMap> Section0BBAddrMaps = {E4, E5};
1101   std::vector<BBAddrMap> Section1BBAddrMaps = {E3};
1102   std::vector<BBAddrMap> Section2BBAddrMaps = {E1, E2};
1103   std::vector<BBAddrMap> AllBBAddrMaps = {E1, E2, E3, E4, E5};
1104 
1105   std::vector<PGOAnalysisMap> Section0PGOAnalysisMaps = {P4, P5};
1106   std::vector<PGOAnalysisMap> Section1PGOAnalysisMaps = {P3};
1107   std::vector<PGOAnalysisMap> Section2PGOAnalysisMaps = {P1, P2};
1108   std::vector<PGOAnalysisMap> AllPGOAnalysisMaps = {P1, P2, P3, P4, P5};
1109 
1110   auto DoCheckSucceeds =
1111       [&](StringRef YamlString, std::optional<unsigned> TextSectionIndex,
1112           std::vector<BBAddrMap> ExpectedResult,
1113           std::optional<std::vector<PGOAnalysisMap>> ExpectedPGO) {
1114         SCOPED_TRACE(
1115             "for TextSectionIndex: " +
1116             (TextSectionIndex ? llvm::Twine(*TextSectionIndex) : "{}") +
1117             " and object yaml:\n" + YamlString);
1118         SmallString<0> Storage;
1119         Expected<ELFObjectFile<ELF64LE>> ElfOrErr =
1120             toBinary<ELF64LE>(Storage, YamlString);
1121         ASSERT_THAT_EXPECTED(ElfOrErr, Succeeded());
1122 
1123         Expected<const typename ELF64LE::Shdr *> BBAddrMapSecOrErr =
1124             ElfOrErr->getELFFile().getSection(1);
1125         ASSERT_THAT_EXPECTED(BBAddrMapSecOrErr, Succeeded());
1126 
1127         std::vector<PGOAnalysisMap> PGOAnalyses;
1128         auto BBAddrMaps = ElfOrErr->readBBAddrMap(
1129             TextSectionIndex, ExpectedPGO ? &PGOAnalyses : nullptr);
1130         ASSERT_THAT_EXPECTED(BBAddrMaps, Succeeded());
1131         EXPECT_EQ(*BBAddrMaps, ExpectedResult);
1132         if (ExpectedPGO) {
1133           EXPECT_EQ(BBAddrMaps->size(), PGOAnalyses.size());
1134           EXPECT_EQ(PGOAnalyses, *ExpectedPGO);
1135           for (auto &&[BB, PGO] : llvm::zip(*BBAddrMaps, PGOAnalyses)) {
1136             if (PGO.FeatEnable.BBFreq || PGO.FeatEnable.BrProb)
1137               EXPECT_EQ(BB.getBBEntries().size(), PGO.BBEntries.size());
1138           }
1139         }
1140       };
1141 
1142   auto DoCheckFails = [&](StringRef YamlString,
1143                           std::optional<unsigned> TextSectionIndex,
1144                           const char *ErrMsg) {
1145     SCOPED_TRACE("for TextSectionIndex: " +
1146                  (TextSectionIndex ? llvm::Twine(*TextSectionIndex) : "{}") +
1147                  " and object yaml:\n" + YamlString);
1148     SmallString<0> Storage;
1149     Expected<ELFObjectFile<ELF64LE>> ElfOrErr =
1150         toBinary<ELF64LE>(Storage, YamlString);
1151     ASSERT_THAT_EXPECTED(ElfOrErr, Succeeded());
1152 
1153     Expected<const typename ELF64LE::Shdr *> BBAddrMapSecOrErr =
1154         ElfOrErr->getELFFile().getSection(1);
1155     ASSERT_THAT_EXPECTED(BBAddrMapSecOrErr, Succeeded());
1156     std::vector<PGOAnalysisMap> PGOAnalyses;
1157     EXPECT_THAT_ERROR(
1158         ElfOrErr->readBBAddrMap(TextSectionIndex, &PGOAnalyses).takeError(),
1159         FailedWithMessage(ErrMsg));
1160   };
1161 
1162   {
1163     SCOPED_TRACE("normal sections");
1164     // Check that we can retrieve the data in the normal case.
1165     DoCheckSucceeds(CommonYamlString, /*TextSectionIndex=*/std::nullopt,
1166                     AllBBAddrMaps, std::nullopt);
1167     DoCheckSucceeds(CommonYamlString, /*TextSectionIndex=*/0,
1168                     Section0BBAddrMaps, std::nullopt);
1169     DoCheckSucceeds(CommonYamlString, /*TextSectionIndex=*/2,
1170                     Section1BBAddrMaps, std::nullopt);
1171     DoCheckSucceeds(CommonYamlString, /*TextSectionIndex=*/1,
1172                     Section2BBAddrMaps, std::nullopt);
1173 
1174     DoCheckSucceeds(CommonYamlString, /*TextSectionIndex=*/std::nullopt,
1175                     AllBBAddrMaps, AllPGOAnalysisMaps);
1176     DoCheckSucceeds(CommonYamlString, /*TextSectionIndex=*/0,
1177                     Section0BBAddrMaps, Section0PGOAnalysisMaps);
1178     DoCheckSucceeds(CommonYamlString, /*TextSectionIndex=*/2,
1179                     Section1BBAddrMaps, Section1PGOAnalysisMaps);
1180     DoCheckSucceeds(CommonYamlString, /*TextSectionIndex=*/1,
1181                     Section2BBAddrMaps, Section2PGOAnalysisMaps);
1182     // Check that when no bb-address-map section is found for a text section,
1183     // we return an empty result.
1184     DoCheckSucceeds(CommonYamlString, /*TextSectionIndex=*/3, {}, std::nullopt);
1185     DoCheckSucceeds(CommonYamlString, /*TextSectionIndex=*/3, {},
1186                     std::vector<PGOAnalysisMap>{});
1187   }
1188 
1189   // Check that we detect when a bb-addr-map section is linked to an invalid
1190   // (not present) section.
1191   SmallString<128> InvalidLinkedYamlString(CommonYamlString);
1192   InvalidLinkedYamlString += R"(
1193     Link: 10
1194 )";
1195 
1196   {
1197     SCOPED_TRACE("invalid linked section");
1198     DoCheckFails(InvalidLinkedYamlString, /*TextSectionIndex=*/5,
1199                  "unable to get the linked-to section for "
1200                  "SHT_LLVM_BB_ADDR_MAP section with index 5: invalid section "
1201                  "index: 10");
1202 
1203     // Linked sections are not checked when we don't target a specific text
1204     // section.
1205     DoCheckSucceeds(InvalidLinkedYamlString, /*TextSectionIndex=*/std::nullopt,
1206                     AllBBAddrMaps, std::nullopt);
1207     DoCheckSucceeds(InvalidLinkedYamlString, /*TextSectionIndex=*/std::nullopt,
1208                     AllBBAddrMaps, AllPGOAnalysisMaps);
1209   }
1210 
1211   // Check that we can detect when bb-address-map decoding fails.
1212   SmallString<128> TruncatedYamlString(CommonYamlString);
1213   TruncatedYamlString += R"(
1214     ShSize: 0xa
1215 )";
1216 
1217   {
1218     SCOPED_TRACE("truncated section");
1219     DoCheckFails(TruncatedYamlString, /*TextSectionIndex=*/std::nullopt,
1220                  "unable to read SHT_LLVM_BB_ADDR_MAP section with index 5: "
1221                  "unable to decode LEB128 at offset 0x0000000a: malformed "
1222                  "uleb128, extends past end");
1223     // Check that we can read the other section's bb-address-maps which are
1224     // valid.
1225     DoCheckSucceeds(TruncatedYamlString, /*TextSectionIndex=*/2,
1226                     Section1BBAddrMaps, std::nullopt);
1227     DoCheckSucceeds(TruncatedYamlString, /*TextSectionIndex=*/2,
1228                     Section1BBAddrMaps, Section1PGOAnalysisMaps);
1229   }
1230 }
1231 
1232 // Test for ObjectFile::getRelocatedSection: check that it returns a relocated
1233 // section for executable and relocatable files.
1234 TEST(ELFObjectFileTest, ExecutableWithRelocs) {
1235   StringRef HeaderString(R"(
1236 --- !ELF
1237 FileHeader:
1238   Class: ELFCLASS64
1239   Data:  ELFDATA2LSB
1240 )");
1241   StringRef ContentsString(R"(
1242 Sections:
1243   - Name:  .text
1244     Type:  SHT_PROGBITS
1245     Flags: [ SHF_ALLOC, SHF_EXECINSTR ]
1246   - Name:  .rela.text
1247     Type:  SHT_RELA
1248     Flags: [ SHF_INFO_LINK ]
1249     Info:  .text
1250 )");
1251 
1252   auto DoCheck = [&](StringRef YamlString) {
1253     SmallString<0> Storage;
1254     Expected<ELFObjectFile<ELF64LE>> ElfOrErr =
1255         toBinary<ELF64LE>(Storage, YamlString);
1256     ASSERT_THAT_EXPECTED(ElfOrErr, Succeeded());
1257     const ELFObjectFile<ELF64LE> &Obj = *ElfOrErr;
1258 
1259     bool FoundRela;
1260 
1261     for (SectionRef Sec : Obj.sections()) {
1262       Expected<StringRef> SecNameOrErr = Sec.getName();
1263       ASSERT_THAT_EXPECTED(SecNameOrErr, Succeeded());
1264       StringRef SecName = *SecNameOrErr;
1265       if (SecName != ".rela.text")
1266         continue;
1267       FoundRela = true;
1268       Expected<section_iterator> RelSecOrErr = Sec.getRelocatedSection();
1269       ASSERT_THAT_EXPECTED(RelSecOrErr, Succeeded());
1270       section_iterator RelSec = *RelSecOrErr;
1271       ASSERT_NE(RelSec, Obj.section_end());
1272       Expected<StringRef> TextSecNameOrErr = RelSec->getName();
1273       ASSERT_THAT_EXPECTED(TextSecNameOrErr, Succeeded());
1274       StringRef TextSecName = *TextSecNameOrErr;
1275       EXPECT_EQ(TextSecName, ".text");
1276     }
1277     ASSERT_TRUE(FoundRela);
1278   };
1279 
1280   // Check ET_EXEC file (`ld --emit-relocs` use-case).
1281   SmallString<128> ExecFileYamlString(HeaderString);
1282   ExecFileYamlString += R"(
1283   Type:  ET_EXEC
1284 )";
1285   ExecFileYamlString += ContentsString;
1286   DoCheck(ExecFileYamlString);
1287 
1288   // Check ET_REL file.
1289   SmallString<128> RelocatableFileYamlString(HeaderString);
1290   RelocatableFileYamlString += R"(
1291   Type:  ET_REL
1292 )";
1293   RelocatableFileYamlString += ContentsString;
1294   DoCheck(RelocatableFileYamlString);
1295 }
1296 
1297 TEST(ELFObjectFileTest, GetSectionAndRelocations) {
1298   StringRef HeaderString(R"(
1299 --- !ELF
1300 FileHeader:
1301   Class: ELFCLASS64
1302   Data:  ELFDATA2LSB
1303   Type:  ET_EXEC
1304 )");
1305 
1306   using Elf_Shdr = Elf_Shdr_Impl<ELF64LE>;
1307 
1308   auto DoCheckSucceeds = [&](StringRef ContentsString,
1309                              std::function<Expected<bool>(const Elf_Shdr &)>
1310                                  Matcher) {
1311     SmallString<0> Storage;
1312     SmallString<128> FullYamlString(HeaderString);
1313     FullYamlString += ContentsString;
1314     Expected<ELFObjectFile<ELF64LE>> ElfOrErr =
1315         toBinary<ELF64LE>(Storage, FullYamlString);
1316     ASSERT_THAT_EXPECTED(ElfOrErr, Succeeded());
1317 
1318     Expected<MapVector<const Elf_Shdr *, const Elf_Shdr *>> SecToRelocMapOrErr =
1319         ElfOrErr->getELFFile().getSectionAndRelocations(Matcher);
1320     ASSERT_THAT_EXPECTED(SecToRelocMapOrErr, Succeeded());
1321 
1322     // Basic verification to make sure we have the correct section types.
1323     for (auto const &[Sec, RelaSec] : *SecToRelocMapOrErr) {
1324       ASSERT_EQ(Sec->sh_type, ELF::SHT_PROGBITS);
1325       ASSERT_EQ(RelaSec->sh_type, ELF::SHT_RELA);
1326     }
1327   };
1328 
1329   auto DoCheckFails = [&](StringRef ContentsString,
1330                           std::function<Expected<bool>(const Elf_Shdr &)>
1331                               Matcher,
1332                           const char *ErrorMessage) {
1333     SmallString<0> Storage;
1334     SmallString<128> FullYamlString(HeaderString);
1335     FullYamlString += ContentsString;
1336     Expected<ELFObjectFile<ELF64LE>> ElfOrErr =
1337         toBinary<ELF64LE>(Storage, FullYamlString);
1338     ASSERT_THAT_EXPECTED(ElfOrErr, Succeeded());
1339 
1340     Expected<MapVector<const Elf_Shdr *, const Elf_Shdr *>> SecToRelocMapOrErr =
1341         ElfOrErr->getELFFile().getSectionAndRelocations(Matcher);
1342     ASSERT_THAT_ERROR(SecToRelocMapOrErr.takeError(),
1343                       FailedWithMessage(ErrorMessage));
1344   };
1345 
1346   auto DefaultMatcher = [](const Elf_Shdr &Sec) -> bool {
1347     return Sec.sh_type == ELF::SHT_PROGBITS;
1348   };
1349 
1350   StringRef TwoTextSections = R"(
1351 Sections:
1352   - Name: .text
1353     Type: SHT_PROGBITS
1354     Flags: [ SHF_ALLOC, SHF_EXECINSTR ]
1355   - Name: .rela.text
1356     Type: SHT_RELA
1357     Flags: [ SHF_INFO_LINK ]
1358     Info: .text
1359   - Name: .text2
1360     Type: SHT_PROGBITS
1361     Flags: [ SHF_ALLOC, SHF_EXECINSTR ]
1362   - Name: .rela.text2
1363     Type: SHT_RELA
1364     Flags: [ SHF_INFO_LINK ]
1365     Info: .text2
1366 )";
1367   DoCheckSucceeds(TwoTextSections, DefaultMatcher);
1368 
1369   StringRef OneTextSection = R"(
1370 Sections:
1371   - Name: .text
1372     Type: SHT_PROGBITS
1373     Flags: [ SHF_ALLOC, SHF_EXECINSTR ]
1374 )";
1375 
1376   auto ErroringMatcher = [](const Elf_Shdr &Sec) -> Expected<bool> {
1377     if (Sec.sh_type == ELF::SHT_PROGBITS)
1378       return createError("This was supposed to fail.");
1379     return false;
1380   };
1381 
1382   DoCheckFails(OneTextSection, ErroringMatcher, "This was supposed to fail.");
1383 
1384   StringRef MissingRelocatableContent = R"(
1385 Sections:
1386   - Name: .rela.text
1387     Type: SHT_RELA
1388     Flags: [ SHF_INFO_LINK ]
1389     Info: 0xFF
1390 )";
1391 
1392   DoCheckFails(MissingRelocatableContent, DefaultMatcher,
1393                "SHT_RELA section with index 1: failed to get a "
1394                "relocated section: invalid section index: 255");
1395 }
1396