xref: /aosp_15_r20/external/cronet/base/debug/elf_reader.h (revision 6777b5387eb2ff775bb5750e3f5d96f37fb7352b)
1 // Copyright 2018 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #ifndef BASE_DEBUG_ELF_READER_H_
6 #define BASE_DEBUG_ELF_READER_H_
7 
8 #include <elf.h>
9 
10 #include <optional>
11 #include <string_view>
12 
13 #include "base/base_export.h"
14 #include "base/containers/span.h"
15 #include "base/hash/sha1.h"
16 
17 // Functions for querying metadata from ELF binaries. All functions are signal
18 // safe and require that the file be fully memory mapped.
19 
20 #if __SIZEOF_POINTER__ == 4
21 using Phdr = Elf32_Phdr;
22 #else
23 using Phdr = Elf64_Phdr;
24 #endif
25 
26 namespace base {
27 namespace debug {
28 
29 // Hex-encodes the build ID from the ELF binary located at |elf_mapped_base|.
30 // Returns the length of the build ID in bytes, or zero if the build ID couldn't
31 // be read.
32 // When |uppercase| is |true|, the output string is written using uppercase hex
33 // characters. Otherwise, the output is lowercased.
34 constexpr size_t kMaxBuildIdStringLength = kSHA1Length * 2;
35 using ElfBuildIdBuffer = char[kMaxBuildIdStringLength + 1];
36 size_t BASE_EXPORT ReadElfBuildId(const void* elf_mapped_base,
37                                   bool uppercase,
38                                   ElfBuildIdBuffer build_id);
39 
40 // Returns the library name from the ELF file mapped at |elf_mapped_base|.
41 // Returns an empty result if the name could not be read.
42 std::optional<std::string_view> BASE_EXPORT
43 ReadElfLibraryName(const void* elf_mapped_base);
44 
45 // Returns a span of ELF program headers for the ELF file mapped at
46 // |elf_mapped_base|, or an empty span if the header couldn't be read.
47 span<const Phdr> BASE_EXPORT GetElfProgramHeaders(const void* elf_mapped_base);
48 
49 // Returns the offset to add to virtual addresses in the image to compute the
50 // mapped virtual address. This value must be added to the p_vaddr field in the
51 // Phdrs to obtain the mapped virtual address.
52 size_t BASE_EXPORT GetRelocationOffset(const void* elf_mapped_base);
53 
54 }  // namespace debug
55 }  // namespace base
56 
57 #endif  // BASE_DEBUG_ELF_READER_H_
58