xref: /aosp_15_r20/external/stg/elf_loader.h (revision 9e3b08ae94a55201065475453d799e8b1378bea6)
1 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
2 // -*- mode: C++ -*-
3 //
4 // Copyright 2022 Google LLC
5 //
6 // Licensed under the Apache License v2.0 with LLVM Exceptions (the
7 // "License"); you may not use this file except in compliance with the
8 // License.  You may obtain a copy of the License at
9 //
10 //     https://llvm.org/LICENSE.txt
11 //
12 // Unless required by applicable law or agreed to in writing, software
13 // distributed under the License is distributed on an "AS IS" BASIS,
14 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 // See the License for the specific language governing permissions and
16 // limitations under the License.
17 //
18 // Author: Aleksei Vetrov
19 
20 #ifndef STG_ELF_LOADER_H_
21 #define STG_ELF_LOADER_H_
22 
23 #include <libelf.h>
24 
25 #include <cstddef>
26 #include <cstdint>
27 #include <ostream>
28 #include <string_view>
29 #include <vector>
30 
31 #include "graph.h"
32 
33 namespace stg {
34 namespace elf {
35 
36 struct SymbolTableEntry {
37   enum class SymbolType {
38     NOTYPE = 0,
39     OBJECT,
40     FUNCTION,
41     SECTION,
42     FILE,
43     COMMON,
44     TLS,
45     GNU_IFUNC
46   };
47 
48   enum class ValueType {
49     UNDEFINED = 0,
50     ABSOLUTE,
51     COMMON,
52     RELATIVE_TO_SECTION,
53   };
54 
55   using Binding = ElfSymbol::Binding;
56   using Visibility = ElfSymbol::Visibility;
57 
58   std::string_view name;
59   uint64_t value;
60   uint64_t size;
61   SymbolType symbol_type;
62   Binding binding;
63   Visibility visibility;
64   size_t section_index;
65   ValueType value_type;
66 };
67 
68 std::ostream& operator<<(std::ostream& os, SymbolTableEntry::SymbolType type);
69 
70 std::ostream& operator<<(std::ostream& os, SymbolTableEntry::ValueType type);
71 
72 std::string_view UnwrapCFISymbolName(std::string_view cfi_name);
73 
74 class ElfLoader final {
75  public:
76   explicit ElfLoader(Elf& elf);
77 
78   std::string_view GetSectionRawData(const char* name) const;
79   std::vector<SymbolTableEntry> GetElfSymbols() const;
80   std::vector<SymbolTableEntry> GetCFISymbols() const;
81   ElfSymbol::CRC GetElfSymbolCRC(const SymbolTableEntry& symbol) const;
82   std::string_view GetElfSymbolNamespace(const SymbolTableEntry& symbol) const;
83   size_t GetAbsoluteAddress(const SymbolTableEntry& symbol) const;
84   bool IsLinuxKernelBinary() const;
85   bool IsLittleEndianBinary() const;
86 
87  private:
88   void InitializeElfInformation();
89 
90   Elf* elf_;
91   bool is_linux_kernel_binary_;
92   bool is_relocatable_;
93   bool is_little_endian_binary_;
94 };
95 
96 }  // namespace elf
97 }  // namespace stg
98 
99 #endif  // STG_ELF_LOADER_H_
100