From ee18ec019ef6f0ef9d7cd3b4cf0314291814cab0 Mon Sep 17 00:00:00 2001 From: Roland Reichwein Date: Sat, 28 Mar 2020 22:27:01 +0100 Subject: Add ELF handling (WIP) --- elf.cpp | 89 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 89 insertions(+) (limited to 'elf.cpp') diff --git a/elf.cpp b/elf.cpp index c94f2f5..9a835ff 100644 --- a/elf.cpp +++ b/elf.cpp @@ -1 +1,90 @@ #include "elf.h" + +#include "file.h" + +//#include + +#include + +// Helper Functions +namespace { + void AddFileHeader(std::vector& data, const std::vector& code) + { + Elf::FileHeader fh; + + fh.e_shoff = sizeof(fh) + sizeof(Elf::ProgramHeader) + code.size() + 16; + + size_t old_size {data.size()}; + data.resize(old_size + sizeof(fh)); + std::memcpy(data.data() + old_size, reinterpret_cast(&fh), sizeof(fh)); + } + + void AddProgramHeader(std::vector& data, const std::vector& code) + { + Elf::ProgramHeader ph; + + ph.p_offset = sizeof(Elf::FileHeader) + sizeof(Elf::ProgramHeader); + ph.p_filesz = code.size(); + ph.p_memsz = code.size(); + + size_t old_size {data.size()}; + data.resize(old_size + sizeof(ph)); + std::memcpy(data.data() + old_size, reinterpret_cast(&ph), sizeof(ph)); + } + + void AddSectionHeaderText(std::vector& data, const std::vector& code) + { + Elf::SectionHeader sh; + + sh.sh_name = 0; // offset in section + sh.sh_size = code.size(); + sh.sh_type = 1; // program + + size_t old_size {data.size()}; + data.resize(old_size + sizeof(sh)); + std::memcpy(data.data() + old_size, reinterpret_cast(&sh), sizeof(sh)); + } + + void AddSectionHeaderSectionNames(std::vector& data, const std::vector& code) + { + Elf::SectionHeader sh; + + sh.sh_name = 0; // offset in section + sh.sh_size = 16; + sh.sh_type = 3; // section names + sh.sh_flags = 0; + + size_t old_size {data.size()}; + data.resize(old_size + sizeof(sh)); + std::memcpy(data.data() + old_size, reinterpret_cast(&sh), sizeof(sh)); + } +} + +void Elf::Write(const std::filesystem::path& path, const std::vector& code) +{ + std::vector data; + + AddFileHeader(data, code); + AddProgramHeader(data, code); + + data.insert(data.end(), code.begin(), code.end()); + + std::string section_names(".text\0.shstrtab\0", 16); + size_t old_size {data.size()}; + data.resize(old_size + section_names.size()); + std::memcpy(data.data() + old_size, section_names.data(), section_names.size()); + + AddSectionHeaderText(data, code); + AddSectionHeaderSectionNames(data, code); + + File::setFile(path, data); +} + +std::vector Elf::Read(const std::filesystem::path& path) +{ + std::vector result; + + // TODO + + return result; +} -- cgit v1.2.3