From 55a485ee67440bf023a0676e5307ea381abcd9dd Mon Sep 17 00:00:00 2001 From: "Justin C. Miller" Date: Sun, 18 Feb 2024 17:22:23 -0800 Subject: [PATCH] [elf] Add get_section_by_name Add the get_section_by_name function to iterate sections and compare name strings. --- src/libraries/elf/file.cpp | 32 +++++++++++++++++++++++++--- src/libraries/elf/include/elf/file.h | 2 ++ 2 files changed, 31 insertions(+), 3 deletions(-) diff --git a/src/libraries/elf/file.cpp b/src/libraries/elf/file.cpp index 6a5bcb3..3ff8330 100644 --- a/src/libraries/elf/file.cpp +++ b/src/libraries/elf/file.cpp @@ -13,10 +13,11 @@ const T *convert(util::const_buffer data, size_t offset) { } file::file(util::const_buffer data) : - m_segments(convert(data, fh(data)->ph_offset), fh(data)->ph_entsize, fh(data)->ph_num), - m_sections(convert(data, fh(data)->sh_offset), fh(data)->sh_entsize, fh(data)->sh_num), - m_data(data) + m_segments {convert(data, fh(data)->ph_offset), fh(data)->ph_entsize, fh(data)->ph_num}, + m_sections {convert(data, fh(data)->sh_offset), fh(data)->sh_entsize, fh(data)->sh_num}, + m_data {data} { + } bool @@ -52,4 +53,29 @@ file::entrypoint() const } + +const section_header * +file::get_section_by_name(const char *name) +{ + if (!name) + return nullptr; + + const section_header &shstrtab = m_sections[header()->sh_str_idx]; + util::counted strings = { + reinterpret_cast(m_data.pointer) + shstrtab.offset, + shstrtab.size, + }; + + for (auto &sec : m_sections) { + const char *section_name = &strings[sec.name_offset]; + size_t i = 0; + + // Can't depend on libc, do our own basic strcmp here + while (name[i] && section_name[i] && name[i] == section_name[i]) ++i; + if (name[i] == section_name[i]) + return &sec; + } + return nullptr; +} + } // namespace elf diff --git a/src/libraries/elf/include/elf/file.h b/src/libraries/elf/include/elf/file.h index 7489a25..3efa5f7 100644 --- a/src/libraries/elf/include/elf/file.h +++ b/src/libraries/elf/include/elf/file.h @@ -67,6 +67,8 @@ public: return reinterpret_cast(m_data.pointer); } + const section_header * get_section_by_name(const char *); + /// Get the ELF file type from the header inline filetype type() const { return header()->file_type; }