Debian Codegraph @

llvm/unittests/Object/ELFObjectFileTest.cpp

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