From c86c0f2ae6edadfcda7a3529a85c1d2b32257145 Mon Sep 17 00:00:00 2001 From: "Justin C. Miller" Date: Sat, 5 Aug 2023 17:37:45 -0700 Subject: [PATCH] [elf] Allow checking for different file types Previously `elf::file::valid()` only returned true for ELF files of type `ET_EXEC`, now allow passing in of an expected file type. --- src/libraries/elf/file.cpp | 13 ++++++++++--- src/libraries/elf/include/elf/file.h | 10 ++++++++-- 2 files changed, 18 insertions(+), 5 deletions(-) diff --git a/src/libraries/elf/file.cpp b/src/libraries/elf/file.cpp index 2bb0dd3..6a5bcb3 100644 --- a/src/libraries/elf/file.cpp +++ b/src/libraries/elf/file.cpp @@ -20,22 +20,29 @@ file::file(util::const_buffer data) : } bool -file::valid() const +file::valid(elf::filetype type) const { if (m_data.count < sizeof(file_header)) return false; const file_header *fheader = header(); - return + bool abi_valid = fheader->magic == expected_magic && fheader->word_size == wordsize::bits64 && fheader->endianness == encoding::lsb && fheader->os_abi == osabi::sysV && - fheader->file_type == filetype::executable && fheader->machine_type == machine::x64 && fheader->ident_version == 1 && fheader->version == 1; + + if (!abi_valid) + return false; + + if (type != filetype::none && fheader->file_type != type) + return false; + + return true; } uintptr_t diff --git a/src/libraries/elf/include/elf/file.h b/src/libraries/elf/include/elf/file.h index 1b1c151..7489a25 100644 --- a/src/libraries/elf/include/elf/file.h +++ b/src/libraries/elf/include/elf/file.h @@ -2,6 +2,7 @@ #include #include +#include #include #include @@ -42,8 +43,9 @@ public: file(util::const_buffer data); /// Check the validity of the ELF data - /// \returns true for valid ELF data - bool valid() const; + /// \arg type Expected file type of the data + /// \returns true for valid ELF data + bool valid(elf::filetype type = elf::filetype::executable) const; /// Get the entrypoint address of the program image /// \returns A pointer to the entrypoint of the program @@ -60,10 +62,14 @@ public: /// Get the ELF section headers inline const subheaders & sections() const { return m_sections; } + /// Get the ELF file header inline const file_header * header() const { return reinterpret_cast(m_data.pointer); } + /// Get the ELF file type from the header + inline filetype type() const { return header()->file_type; } + private: subheaders m_segments; subheaders m_sections;