1 //===----------------------- ELFTypesTest.cpp -----------------------------===//
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 #include "llvm/Object/ELFTypes.h"
9 #include "gtest/gtest.h"
10 #include <iostream>
11 
12 using namespace llvm;
13 using namespace llvm::object;
14 
15 template <typename ELFT> using Elf_Note = typename ELFT::Note;
16 
17 template <class ELFT> struct NoteTestData {
18   std::vector<uint8_t> Data;
19 
getElfNoteNoteTestData20   const Elf_Note_Impl<ELFT> getElfNote(StringRef Name, uint32_t Type,
21                                        ArrayRef<uint8_t> Desc) {
22     Data.resize(sizeof(Elf_Nhdr_Impl<ELFT>) +
23                     alignTo<Elf_Nhdr_Impl<ELFT>::Align>(Name.size()) +
24                     alignTo<Elf_Nhdr_Impl<ELFT>::Align>(Desc.size()),
25                 0);
26 
27     Elf_Nhdr_Impl<ELFT> *Nhdr =
28         reinterpret_cast<Elf_Nhdr_Impl<ELFT> *>(Data.data());
29     Nhdr->n_namesz = (Name == "") ? 0 : Name.size() + 1;
30     Nhdr->n_descsz = Desc.size();
31     Nhdr->n_type = Type;
32 
33     auto NameOffset = Data.begin() + sizeof(*Nhdr);
34     std::copy(Name.begin(), Name.end(), NameOffset);
35 
36     auto DescOffset =
37         NameOffset + alignTo<Elf_Nhdr_Impl<ELFT>::Align>(Nhdr->n_namesz);
38     std::copy(Desc.begin(), Desc.end(), DescOffset);
39 
40     return Elf_Note_Impl<ELFT>(*Nhdr);
41   }
42 };
43 
TEST(ELFTypesTest,NoteTest)44 TEST(ELFTypesTest, NoteTest) {
45   static const uint8_t Random[] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
46   ArrayRef<uint8_t> RandomData = makeArrayRef(Random);
47   NoteTestData<ELF64LE> TestData;
48 
49   auto Note1 = TestData.getElfNote(StringRef("AMD"), ELF::NT_AMDGPU_METADATA,
50                                    RandomData);
51   EXPECT_EQ(Note1.getName(), "AMD");
52   EXPECT_EQ(Note1.getType(), ELF::NT_AMDGPU_METADATA);
53   EXPECT_EQ(Note1.getDesc(), RandomData);
54   EXPECT_EQ(Note1.getDescAsStringRef(),
55             StringRef(reinterpret_cast<const char *>(Random), sizeof(Random)));
56 
57   auto Note2 = TestData.getElfNote("", ELF::NT_AMDGPU_METADATA, RandomData);
58   EXPECT_EQ(Note2.getName(), "");
59 
60   auto Note3 =
61       TestData.getElfNote("AMD", ELF::NT_AMDGPU_METADATA, ArrayRef<uint8_t>());
62   EXPECT_EQ(Note3.getDescAsStringRef(), StringRef(""));
63 }
64