minecraft-pi-reborn/libreborn/include/libreborn/elf.h

64 lines
1.9 KiB
C
Raw Normal View History

2021-06-17 21:32:24 +00:00
#pragma once
#include <unistd.h>
#include <string.h>
#include <sys/mman.h>
#include <elf.h>
2021-09-12 03:18:12 +00:00
#include <link.h>
2021-06-17 21:32:24 +00:00
#include "log.h"
2021-08-16 03:11:03 +00:00
#include "exec.h"
2021-06-17 21:32:24 +00:00
// Find And Iterate Over All .text Sections In Current Binary
2021-09-12 03:18:12 +00:00
typedef void (*text_section_callback_t)(ElfW(Addr) section, ElfW(Word) size, void *data);
2021-06-17 21:32:24 +00:00
static inline void iterate_text_sections(text_section_callback_t callback, void *data) {
// Load Main Binary
2022-03-09 23:47:31 +00:00
FILE *file_obj = fopen(getenv("MCPI_EXECUTABLE_PATH"), "rb");
2021-06-17 21:32:24 +00:00
// Verify Binary
if (!file_obj) {
2021-09-12 03:18:12 +00:00
ERR("%s", "Unable To Open Current Binary");
2021-06-17 21:32:24 +00:00
}
// Get File Size
fseek(file_obj, 0L, SEEK_END);
2021-09-12 03:18:12 +00:00
long int file_size = ftell(file_obj);
2021-06-17 21:32:24 +00:00
fseek(file_obj, 0L, SEEK_SET);
// Map File To Pointer
2021-09-12 03:18:12 +00:00
unsigned char *file_map = (unsigned char *) mmap(0, file_size, PROT_READ, MAP_PRIVATE, fileno(file_obj), 0);
2021-06-17 21:32:24 +00:00
// Parse ELF
2021-09-12 03:18:12 +00:00
ElfW(Ehdr) *elf_header = (ElfW(Ehdr) *) file_map;
ElfW(Shdr) *elf_section_headers = (ElfW(Shdr) *) (file_map + elf_header->e_shoff);
2021-06-17 21:32:24 +00:00
int elf_section_header_count = elf_header->e_shnum;
// Locate Section Names
2021-09-12 03:18:12 +00:00
ElfW(Shdr) elf_shstrtab = elf_section_headers[elf_header->e_shstrndx];
unsigned char *elf_shstrtab_p = file_map + elf_shstrtab.sh_offset;
2021-06-17 21:32:24 +00:00
// Track .text Sections
int text_sections = 0;
// Iterate Sections
for (int i = 0; i < elf_section_header_count; ++i) {
2021-09-12 03:18:12 +00:00
ElfW(Shdr) header = elf_section_headers[i];
char *name = (char *) (elf_shstrtab_p + header.sh_name);
2021-06-17 21:32:24 +00:00
// Check Section Type
if (strcmp(name, ".text") == 0) {
// .text Section
2021-08-16 03:11:03 +00:00
(*callback)(header.sh_addr, header.sh_size, data);
2021-06-17 21:32:24 +00:00
text_sections++;
}
}
// Ensure At Least .text Section Was Scanned
if (text_sections < 1) {
2021-09-12 03:18:12 +00:00
ERR("%s", "Unable To Find .text Sectons");
2021-06-17 21:32:24 +00:00
}
// Unmap And Close File
2021-09-12 03:18:12 +00:00
munmap(file_map, file_size);
2021-06-17 21:32:24 +00:00
fclose(file_obj);
}