Skip to content

Instantly share code, notes, and snippets.

@pablogsal
Created January 2, 2024 18:04
Show Gist options
  • Save pablogsal/2f11bbb5662b15f03f119b92ae20b9d9 to your computer and use it in GitHub Desktop.
Save pablogsal/2f11bbb5662b15f03f119b92ae20b9d9 to your computer and use it in GitHub Desktop.
#include <fcntl.h>
#include <gelf.h>
#include <libelf.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <gelf.h>
#include <libelf.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <unistd.h>
void
printProgramHeaderInfo(Elf* elf)
{
Elf64_Ehdr* ehdr = elf64_getehdr(elf);
if (!ehdr) {
fprintf(stderr, "elf64_getehdr() failed: %s\n", elf_errmsg(-1));
exit(EXIT_FAILURE);
}
for (size_t i = 0; i < ehdr->e_phnum; ++i) {
GElf_Phdr phdr;
if (gelf_getphdr(elf, i, &phdr) != &phdr) {
fprintf(stderr, "gelf_getphdr() failed: %s\n", elf_errmsg(-1));
exit(EXIT_FAILURE);
}
printf("Program Header %zu - Type: %lu, Alignment: %lu\n", i, phdr.p_type, phdr.p_align);
}
}
void
modifyElfAlignment(const char* filename)
{
int fd, elferr;
if (elf_version(EV_CURRENT) == EV_NONE) {
fprintf(stderr, "ELF library initialization failed: %s\n", elf_errmsg(-1));
exit(EXIT_FAILURE);
}
if ((fd = open(filename, O_RDWR)) == -1) {
perror("open");
exit(EXIT_FAILURE);
}
struct stat st;
if (fstat(fd, &st) == -1) {
perror("fstat");
exit(EXIT_FAILURE);
}
Elf* elf;
if ((elf = elf_begin(fd, ELF_C_RDWR_MMAP, NULL)) == NULL) {
fprintf(stderr, "elf_begin() failed: %s\n", elf_errmsg(-1));
exit(EXIT_FAILURE);
}
printf("Program Headers before modification:\n");
printProgramHeaderInfo(elf);
Elf64_Ehdr* ehdr = elf64_getehdr(elf);
if (!ehdr) {
fprintf(stderr, "elf64_getehdr() failed: %s\n", elf_errmsg(-1));
exit(EXIT_FAILURE);
}
for (size_t i = 0; i < ehdr->e_phnum; ++i) {
GElf_Phdr phdr;
if (gelf_getphdr(elf, i, &phdr) != &phdr) {
fprintf(stderr, "gelf_getphdr() failed: %s\n", elf_errmsg(-1));
exit(EXIT_FAILURE);
}
if (phdr.p_filesz == 0 && phdr.p_memsz == 0 && phdr.p_type == PT_LOAD) {
printf("Modifying Alignment of Program Header %zu\n", i);
phdr.p_align = 0;
phdr.p_type = PT_NULL;
if (gelf_update_phdr(elf, i, &phdr) == 0) {
fprintf(stderr, "gelf_update_phdr() failed: %s\n", elf_errmsg(-1));
exit(EXIT_FAILURE);
}
}
}
printf("\nProgram Headers after modification:\n");
printProgramHeaderInfo(elf);
close(fd);
}
int
main(int argc, char* argv[])
{
if (argc != 2) {
fprintf(stderr, "Usage: %s <elf_filename>\n", argv[0]);
exit(EXIT_FAILURE);
}
modifyElfAlignment(argv[1]);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment