1 /* 2 * Copyright (C) 2023 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 #pragma once 18 19 #include <libelf64/elf64.h> 20 21 #include <fstream> 22 23 namespace android { 24 namespace elf64 { 25 26 // Class to parse ELF64 binaries. 27 // 28 // The class will parse the 4 parts if present: 29 // 30 // - Executable header (Elf64_Ehdr). 31 // - Program headers (Elf64_Phdr - present in executables or shared libraries). 32 // - Section headers (Elf64_Shdr) 33 // - Sections (.interp, .init, .plt, .text, .rodata, .data, .bss, .shstrtab, etc). 34 // 35 // The basic usage of the library is: 36 // 37 // android::elf64::Elf64Binary elf64Binary; 38 // std::string fileName("new_binary.so"); 39 // // The content of the elf file will be populated in elf64Binary. 40 // android::elf64::Elf64Parser::ParseElfFile(fileName, elf64Binary); 41 // 42 class Elf64Parser { 43 public: 44 // Parse the elf file and populate the elfBinary object. 45 // Returns true if the parsing was successful, otherwise false. 46 [[nodiscard]] static bool ParseElfFile(const std::string& fileName, Elf64Binary& elfBinary); 47 static bool IsElf64(const std::string& fileName); 48 49 private: 50 std::ifstream elf64stream; 51 Elf64Binary* elfBinaryPtr; 52 53 Elf64Parser(const std::string& fileName, Elf64Binary& elfBinary); 54 bool ParseExecutableHeader(); 55 bool ParseProgramHeaders(); 56 bool ParseSections(); 57 bool ParseSectionHeaders(); 58 }; 59 60 } // namespace elf64 61 } // namespace android 62