I’ve been messing around with elf files and the ELFIO library in C++ for a while. I understand how I can add a new section and add data to this particular section. But what if I want to modify the content of this particular section?
From what I understand, each section has a particular size and if the new data exceeds the size of the section it could corrupt other data in the elf file. Do I have to find the offset of this section and its size then try to modify the data in memory? Is this something I could achieve by using the ELFIO library?
This is my code for adding a new section and data into an elf file:
void writeToELF(std::string& filePath, std::string& str) {
ELFIO::elfio writer;
if (!writer.load(filePath)) {
throw std::runtime_error("Can't find or load ELF file.");
}
const std::string sectionName = ".random";
ELFIO::section* newSection = writer.sections.add(sectionName.c_str());
newSection->set_type(ELFIO::SHT_PROGBITS);
newSection->set_flags(ELFIO::SHF_WRITE | ELFIO::SHF_ALLOC);
newSection->set_addr_align(0x4);
newSection->set_data(str.data(), str.size());
writer.set_entry(newSection->get_address());
const std::string modifiedELF = "modified_" + filePath;
if (!writer.save(modifiedELF.c_str())) {
throw std::runtime_error("Error saving modified file.");
}
std::cout << "Modified ELF saved successfully. " << std::endl;
}
I set the flags to SHF_WRITE and SHF_ALLOC because I want this data to be modifiable and be loaded into memory when executed.
I tried updating the content of my custom section using the following code:
void updateSectionData(std::string& filePath, std::string& sectionName) {
ELFIO::elfio writer;
if (!writer.load(filePath)) {
std::cerr << "Error loading file: " << filePath << std::endl;
exit(1);
}
ELFIO::section* custom_section = writer.sections[sectionName];
if (!custom_section) {
std::cerr << "Section not found." << std::endl;
exit(1);
}
std::string newData = "This is a new string";
custom_section->set_data(newData.data(), newData.size());
if (!writer.save("modified_" + filePath)) {
std::cerr << "Failed to save modified ELF file." << std::endl;
exit(1);
}
std::cout << "Content has been updated." << std::endl;
}
This code just gives me an error “Failed to save modified ELF file.” I have no clue what is wrong.