Created
August 27, 2020 02:23
-
-
Save the6p4c/d62d2f2184df9ea919b4be146a2955e9 to your computer and use it in GitHub Desktop.
hey! don't do this!
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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