Debian Codegraph @

libcextract/ElfCXX.hh

raw
1 //===- ElfCXX.hh- C++ Wrapper for libelf -----------------------*- C++ -*-===//
2 //
3 // This project is licensed 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 /// \file
10 /// A C++ wrapper for libelf.
11 //
12 //===----------------------------------------------------------------------===//
13
14
15 /** ElfCXX: Wrapper class for libelf.
16 *
17 * Libelf is a library for handling ELF files written in C. It provides a
18 * basic API for handling ELF files which IMHO is not straightfoward.
19 * Those classes tries to make things easier by collapsing many structures
20 * together (e.g. Section, Section Header and Section Data into a single class).
21 *
22 * Author: Giuliano Belinassi, Marcos Paulo de Souza
23 */
24
25 #pragma once
26
27 #include "Parser.hh"
28
29 #include <elf.h>
30 #include <libelf.h>
31 #include <gelf.h>
32 #include <link.h>
33 #include <string>
34 #include <iterator>
35 #include <unordered_map>
36
37 class ElfObject;
38 class ElfSection;
39 class ElfSymbol;
40
41
42 /** The symbol table in which this symbol was found. */
43 enum ElfSymtabType {
44 TAB_NONE = 0,
45 SYMTAB = SHT_SYMTAB,
46 DYNSYM = SHT_DYNSYM,
47 };
48
49 /** @brief ELF symbol.
50 *
51 * An ELF executable may contain multiple symbols (variables, functions, ...).
52 * This class represent this.
53 *
54 * NOTE: run $ readelf -sW <binary> to show the symbols.
55 */
56 class ElfSymbol
57 {
58 public:
59 inline ElfSymbol(ElfObject &eo, ElfW(Word) shlink, GElf_Sym &symbol)
60 : ElfObj(eo),
61 Shlink(shlink),
62 Symbol(symbol)
63 {
64 }
65
66 /** Get name of the symbol. */
67 const char *Get_Name(void);
68
69 /** Get original Elf_Sym object from libelf. */
70 inline GElf_Sym *Get_Wrapped_Object(void)
71 {
72 return &Symbol;
73 }
74
75 /** Get ELF object from which this symbol is from. */
76 inline ElfObject &Get_Elf_Object(void)
77 {
78 return ElfObj;
79 }
80
81 /** Get symbol `info` (packs `type` and `bind`). */
82 [[gnu::pure]] inline unsigned char Get_Info(void)
83 {
84 return Symbol.st_info;
85 }
86
87 /** Get the symbol `type` (func, object, ...). */
88 inline unsigned char Get_Type(void)
89 {
90 return ELF64_ST_TYPE(Get_Info());
91 }
92
93 /** Get the symbol `bind` (global, weak, ...). */
94 inline unsigned char Get_Bind(void)
95 {
96 return ELF64_ST_BIND(Get_Info());
97 }
98
99 static unsigned char Type_Of(unsigned char info)
100 {
101 return ELF64_ST_TYPE(info);
102 }
103
104 static unsigned char Bind_Of(unsigned char info)
105 {
106 return ELF64_ST_BIND(info);
107 }
108
109 /** Get type as string. */
110 static const char *Type_As_String(unsigned info);
111 /** Get bind as string. */
112 static const char *Bind_As_String(unsigned link);
113
114 /** Get type as string. */
115 inline const char *Get_Type_As_String(void)
116 {
117 return Type_As_String(Get_Type());
118 }
119
120 /** Get bind as string. */
121 inline const char *Get_Bind_As_String(void)
122 {
123 return Bind_As_String(Get_Bind());
124 }
125
126 private:
127
128 /** Reference to the ELF object (file). */
129 ElfObject &ElfObj;
130
131 /** Shared Header link number. Used to compute the symbol name. */
132 ElfW(Word) Shlink;
133
134 /** Original libelf symbol object. */
135 GElf_Sym Symbol;
136 };
137
138 /** @brief ELF section.
139 *
140 * An ELF executable may contain multiple section (.plt, .symtab, .dynamic, ...)
141 * This class represent this.
142 *
143 * NOTE: run $ readelf -S <binary> to show all sections in a binary.
144 */
145 class ElfSection
146 {
147 public:
148 inline ElfSection(ElfObject &eo, Elf_Scn *section)
149 : ElfObj(eo),
150 Section(section)
151 {
152 /** Get Section Header from the Section. */
153 gelf_getshdr(Section, &SectionHeader);
154 }
155
156 /** Get Section Data. */
157 inline Elf_Data *Get_Data(void)
158 {
159 return elf_getdata(Section, nullptr);
160 }
161
162 /** Get the next section. */
163 ElfSection Get_Next_Section(void);
164
165 /** Move this class to the next section object. */
166 void To_Next_Section(void);
167
168 /** Check if this section is a symbol table (dynsym, symtab). */
169 inline bool Is_Symbol_Table(void)
170 {
171 ElfW(Word) type = SectionHeader.sh_type;
172 return type == SHT_SYMTAB || type == SHT_DYNSYM;
173 }
174
175 inline ElfW(Word) Get_Section_Type(void)
176 {
177 return SectionHeader.sh_type;
178 }
179
180 /** Get name of this section. */
181 const char *Get_Name(void);
182
183 /** Get the number of symbols in this section, if it is a symbol table. */
184 inline size_t Get_Num_Symbols(void)
185 {
186 return SectionHeader.sh_size / SectionHeader.sh_entsize;
187 }
188
189 /** Get the i-th symbol in this section. */
190 inline ElfSymbol Get_Symbol(unsigned i)
191 {
192 GElf_Sym sym;
193 gelf_getsym(Get_Data(), i, &sym);
194 return ElfSymbol(ElfObj, SectionHeader.sh_link, sym);
195 }
196
197 /** Get the original Elf_Scn object from libelf. */
198 inline Elf_Scn *Get_Wrapped_Object(void)
199 {
200 return Section;
201 }
202
203 /** Check if two sections are equal. */
204 inline friend bool operator==(const ElfSection &a, const ElfSection &b)
205 {
206 return a.Section == b.Section;
207 }
208
209 /** Check if two sections are not equal. */
210 inline friend bool operator!=(const ElfSection &a, const ElfSection &b)
211 {
212 return a.Section != b.Section;
213 }
214
215 private:
216 /** Reference to the ELF object (file). */
217 ElfObject &ElfObj;
218
219 /** Header of this section. */
220 GElf_Shdr SectionHeader;
221
222 /** Section object from libelf. */
223 Elf_Scn *Section;
224 };
225
226 /** @brief ELF object.
227 *
228 * This class wraps the `struct Elf` object from libelf, also carring the file
229 * descriptor used to open the file. It provies automatic destructor so that
230 * there is no need to close the fd or destroy the ELF object manually.
231 */
232 class ElfObject : public Parser
233 {
234 public:
235 /** Open ELF object. */
236 ElfObject(const char *path);
237 inline ElfObject(const std::string &path)
238 : ElfObject(path.c_str())
239 {
240 }
241
242 ~ElfObject(void);
243
244 /** Get original `struct Elf` from libelf. */
245 inline Elf *Get_Wrapped_Object(void)
246 {
247 return ElfObj;
248 }
249
250 Elf *decompress_gz(void);
251 Elf *decompress_zstd(void);
252
253 /** Iterator class for ELF sections. With this one can use C++ iterators
254 * to iterate through all sections of the ELF file. Like this:
255 * ```
256 * for (auto it = EO.section_begin(); it != EO.section_end(); ++it)
257 * ```
258 **/
259
260 struct SectionIterator
261 {
262 public:
263 SectionIterator(ElfObject &eo, Elf_Scn *scn)
264 : ElfScn(eo, scn)
265 {
266 }
267
268 SectionIterator(ElfSection section)
269 : ElfScn(section)
270 {
271 }
272
273 SectionIterator(ElfObject &eo)
274 : SectionIterator(eo, elf_nextscn(eo.Get_Wrapped_Object(), nullptr))
275 {
276 }
277
278 /** Doing `*it` should access the Elf Section object. */
279 ElfSection &operator*()
280 {
281 return ElfScn;
282 }
283
284 /** Doing `*it` should access the Elf Section object. */
285 const ElfSection &operator*() const
286 {
287 return ElfScn;
288 }
289
290 /** Prefix iterator (++it). */
291 SectionIterator &operator++(void)
292 {
293 ElfScn.To_Next_Section();
294 return *this;
295 }
296
297 /** Comparison must compare the underlying Section objects. */
298 inline friend bool operator==(const SectionIterator &a, const SectionIterator &b)
299 {
300 return a.ElfScn == b.ElfScn;
301 }
302
303 /** Comparison must compare the underlying Section objects. */
304 inline friend bool operator!=(const SectionIterator &a, const SectionIterator &b)
305 {
306 return a.ElfScn != b.ElfScn;
307 }
308
309 private:
310 /** Wrap the ElfSection class. */
311 ElfSection ElfScn;
312 };
313
314 /** First element of the Section list. */
315 SectionIterator section_begin(void)
316 {
317 return SectionIterator(*this);
318 }
319
320 /** Invalid element of the Section list. */
321 SectionIterator section_end(void)
322 {
323 return SectionIterator(*this, nullptr);
324 }
325
326 private:
327 /** Wrapped libelf object. */
328 struct Elf *ElfObj;
329
330 /* Memory allocated to hold the decompressed ELF images */
331 unsigned char *DecompressedObj;
332
333 /** File descriptor used by libelf object. */
334 int ElfFd;
335 };
336
337 /** ElfSymbolCache -- Cache ELF symbols content for fast access.
338 *
339 * Very often we have to check if a given symbol is available in the debuginfo
340 * file. This is a fast way of doing this instead of reparse the ELF
341 * structure.
342 **/
343 class ElfSymbolCache
344 {
345 public:
346 /** Build cache from ElfObject). */
347 ElfSymbolCache(ElfObject &eo);
348
349 /** Build empty cache to be filled later. */
350 ElfSymbolCache(void)
351 : DynsymMap(),
352 SymtabMap(),
353 Mod(""),
354 DebuginfoPath(""),
355 ObjectPath("")
356 {};
357
358 /** Analyze ELF object. */
359 void Analyze_ELF(ElfObject &eo);
360
361 /* Get symbol if available in the Dynsym table. Or 0 if not available. */
362 inline unsigned char Get_Symbol_Info_Dynsym(const std::string &sym)
363 {
364 auto container = DynsymMap.find(sym);
365 if (container != DynsymMap.end()) {
366 return container->second;
367 }
368 return 0;
369 }
370
371 /** Get symbol if available in Symtab table. Or 0 if not available. */
372 inline unsigned char Get_Symbol_Info_Symtab(const std::string &sym)
373 {
374 auto container = SymtabMap.find(sym);
375 if (container != SymtabMap.end()) {
376 return container->second;
377 }
378 return 0;
379 }
380
381 /** Get symbol if available in either symtab. Returns in which symtab this
382 symbo was found. */
383 std::pair<unsigned char, ElfSymtabType> Get_Symbol_Info(const std::string &sym);
384
385 std::string Get_Symbol_Module(const std::string &)
386 {
387 return Mod;
388 }
389
390 std::vector<std::string> Get_All_Symbols(void);
391
392 inline const std::string &Get_Debuginfo_Path(void) const
393 {
394 return DebuginfoPath;
395 }
396
397 inline const std::string &Get_Object_Path(void) const
398 {
399 return ObjectPath;
400 }
401
402 /** Dump for debugging reasons. */
403 void Dump_Cache(void);
404
405 private:
406 /** The hash. */
407 typedef std::unordered_map<std::string, unsigned char> SymbolTableHash;
408 void Insert_Symbols_Into_Hash(SymbolTableHash &map, ElfSection &section);
409
410 /** Hash symbols from dynsym into their value. */
411 SymbolTableHash DynsymMap;
412
413 /** Hash symbols from symtab into their value. */
414 SymbolTableHash SymtabMap;
415
416 /** Kernel module name, if .modinfo section is present. */
417 std::string Mod;
418
419 /** Path to the debuginfo object (contains .symtab section). */
420 std::string DebuginfoPath;
421
422 /** Path to the .so file object (contains .dynsym section). */
423 std::string ObjectPath;
424 };