• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 <memory>
28 #include <ostream>
29 #include <string>
30 #include <string_view>
31 #include <vector>
32 
33 #include "graph.h"
34 
35 namespace stg {
36 namespace elf {
37 
38 struct SymbolTableEntry {
39   enum class SymbolType {
40     NOTYPE = 0,
41     OBJECT,
42     FUNCTION,
43     SECTION,
44     FILE,
45     COMMON,
46     TLS,
47     GNU_IFUNC
48   };
49 
50   enum class ValueType {
51     UNDEFINED = 0,
52     ABSOLUTE,
53     COMMON,
54     RELATIVE_TO_SECTION,
55   };
56 
57   using Binding = ElfSymbol::Binding;
58   using Visibility = ElfSymbol::Visibility;
59 
60   std::string_view name;
61   uint64_t value;
62   uint64_t size;
63   SymbolType symbol_type;
64   Binding binding;
65   Visibility visibility;
66   size_t section_index;
67   ValueType value_type;
68 };
69 
70 std::ostream& operator<<(std::ostream& os, SymbolTableEntry::SymbolType type);
71 
72 std::ostream& operator<<(std::ostream& os, SymbolTableEntry::ValueType type);
73 
74 std::string_view UnwrapCFISymbolName(std::string_view cfi_name);
75 
76 class ElfLoader final {
77  public:
78   explicit ElfLoader(Elf* elf);
79 
80   std::string_view GetBtfRawData() const;
81   std::vector<SymbolTableEntry> GetElfSymbols() const;
82   std::vector<SymbolTableEntry> GetCFISymbols() const;
83   ElfSymbol::CRC GetElfSymbolCRC(const SymbolTableEntry& symbol) const;
84   std::string_view GetElfSymbolNamespace(const SymbolTableEntry& symbol) const;
85   size_t GetAbsoluteAddress(const SymbolTableEntry& symbol) const;
86   bool IsLinuxKernelBinary() const;
87   bool IsLittleEndianBinary() const;
88 
89  private:
90   void InitializeElfInformation();
91 
92   Elf* elf_;
93   bool is_linux_kernel_binary_;
94   bool is_relocatable_;
95   bool is_little_endian_binary_;
96 };
97 
98 }  // namespace elf
99 }  // namespace stg
100 
101 #endif  // STG_ELF_LOADER_H_
102