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