Skip to content

Instantly share code, notes, and snippets.

@the6p4c
Created Aug 27, 2020
Embed
What would you like to do?
hey! don't do this!
#include <stdio.h>
#include <string.h>
#include <stdint.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/io.h>
#include <sys/mman.h>
#include "elf.h"
void *address_of(char *elf, char *name) {
int fd = open(elf, O_RDONLY);
struct stat s;
fstat(fd, &s);
uint8_t *buf = mmap(0, s.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
Elf64_Ehdr *ehdr = (Elf64_Ehdr *) buf;
Elf64_Shdr *shdr = (Elf64_Shdr *) (buf + ehdr->e_shoff);
for (int i = 0; i < ehdr->e_shnum; ++i) {
if (shdr[i].sh_type == SHT_SYMTAB) {
char *strtab = (char *) (buf + shdr[shdr[i].sh_link].sh_offset);
Elf64_Sym *symtab = (Elf64_Sym *) (buf + shdr[i].sh_offset);
int symtab_len = shdr[i].sh_size / sizeof(Elf64_Sym);
for (int i = 0; i < symtab_len; ++i) {
if (strcmp(strtab + symtab[i].st_name, name) == 0) {
return (void *) symtab[i].st_value;
}
}
}
}
return NULL;
}
void *func_of(char *elf, char *name) {
int main(int argc, char *argv[]);
return address_of(elf, name) + ((void *) main - address_of(elf, "main"));
}
void foo() {
printf("welcome to foo\n");
}
int bar(int x) {
return 2 * x + 1;
}
int main(int argc, char *argv[]) {
void (*foo2)() = func_of(argv[0], "foo");
printf("foo (compiled) = %p\n", foo);
printf("foo (dynamic) = %p\n", foo2);
foo2();
int (*bar2)(int) = func_of(argv[0], "bar");
printf("bar (compiled) = %p\n", bar);
printf("bar (dynamic) = %p\n", bar2);
printf("bar(1) (compiled) = %d\n", bar(1));
printf("bar(1) (dynamic) = %d\n", bar2(1));
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment