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 "base/base_export.h" 11 #include "base/containers/span.h" 12 #include "base/hash/sha1.h" 13 #include "base/strings/string_piece.h" 14 #include "third_party/abseil-cpp/absl/types/optional.h" 15 16 // Functions for querying metadata from ELF binaries. All functions are signal 17 // safe and require that the file be fully memory mapped. 18 19 #if __SIZEOF_POINTER__ == 4 20 using Phdr = Elf32_Phdr; 21 #else 22 using Phdr = Elf64_Phdr; 23 #endif 24 25 namespace base { 26 namespace debug { 27 28 // Hex-encodes the build ID from the ELF binary located at |elf_mapped_base|. 29 // Returns the length of the build ID in bytes, or zero if the build ID couldn't 30 // be read. 31 // When |uppercase| is |true|, the output string is written using uppercase hex 32 // characters. Otherwise, the output is lowercased. 33 constexpr size_t kMaxBuildIdStringLength = kSHA1Length * 2; 34 using ElfBuildIdBuffer = char[kMaxBuildIdStringLength + 1]; 35 size_t BASE_EXPORT ReadElfBuildId(const void* elf_mapped_base, 36 bool uppercase, 37 ElfBuildIdBuffer build_id); 38 39 // Returns the library name from the ELF file mapped at |elf_mapped_base|. 40 // Returns an empty result if the name could not be read. 41 absl::optional<StringPiece> BASE_EXPORT 42 ReadElfLibraryName(const void* elf_mapped_base); 43 44 // Returns a span of ELF program headers for the ELF file mapped at 45 // |elf_mapped_base|, or an empty span if the header couldn't be read. 46 span<const Phdr> BASE_EXPORT GetElfProgramHeaders(const void* elf_mapped_base); 47 48 // Returns the offset to add to virtual addresses in the image to compute the 49 // mapped virtual address. This value must be added to the p_vaddr field in the 50 // Phdrs to obtain the mapped virtual address. 51 size_t BASE_EXPORT GetRelocationOffset(const void* elf_mapped_base); 52 53 } // namespace debug 54 } // namespace base 55 56 #endif // BASE_DEBUG_ELF_READER_H_ 57