📄 elf.cpp
字号:
/** Read in an elf file
*/
#include "stdafx.h"
using namespace std;
ELF::ELF(const char* filename) {
input = fopen(filename, "rb+");
if (input == NULL) throw "Failed to open file";
try {
if (fread(&header, sizeof(header), 1, input) != 1) {
throw "Failed to read header";
}
ReadSectionHeaders();
ReadProgramHeaders();
}
catch (const char* ex) {
fclose(input);
throw ex;
}
}
/** Read the section headers
*/
void ELF::ReadSectionHeaders() {
sectionHeaders = new Elf32_Shdr[header.e_shnum];
for (int i = 0; i < header.e_shnum; i++) {
if (fseek(input, header.e_shoff + (i * header.e_shentsize), SEEK_SET)) {
throw "Failed to seek to section headers";
}
if (fread(§ionHeaders[i], sizeof(Elf32_Shdr), 1, input) != 1) {
throw "Failed to read a section header";
}
}
}
/** Read the program headers
*/
void ELF::ReadProgramHeaders() {
programHeaders = new Elf32_Phdr[header.e_phnum];
for (int i = 0; i < header.e_phnum; i++) {
if (fseek(input, header.e_phoff + (i * header.e_phentsize), SEEK_SET)) {
throw "Failed to see to program headers";
}
if (fread(&programHeaders[i], sizeof(Elf32_Phdr), 1, input) != 1) {
throw "Failed to read a program header";
}
}
}
/** Dump out the file
*/
void ELF::Dump() {
cout << "ELF file" << endl;
cout << "Number of sections: " << header.e_shnum << endl;
for (int i = 0; i < header.e_shnum; i++) {
cout << "Section[" << i << "] " << sectionHeaders[i].sh_name << endl;
}
cout << "Number of program segments: " << header.e_phnum << endl;
for (int i = 0; i < header.e_phnum; i++) {
cout << "Program[" << i << "]. Type " << programHeaders[i].p_type
<< " @ " << programHeaders[i].p_vaddr
<< " : " << programHeaders[i].p_memsz
<< endl;
}
}
/** Retrieve the program segment
@param index The index
@param size The output size
@return NULL or the heap allocated memory block
*/
void* ELF::ProgramSegment(int index) {
if ((index < 0) || (index >= header.e_phnum)) {
throw "Index out of range";
}
if (programHeaders[index].p_type != PT_LOAD) {
return NULL;
}
if (programHeaders[index].p_memsz == 0) {
return NULL;
}
void* buffer = new unsigned char[programHeaders[index].p_memsz];
if (buffer) {
if (fseek(input, programHeaders[index].p_offset, SEEK_SET)) {
throw "Failed to seek to program segment";
}
if (fread(buffer, programHeaders[index].p_memsz, 1, input) != 1) {
throw "Failed to read program segment";
}
}
return buffer;
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -