Skip to content

Instantly share code, notes, and snippets.

@josephcsible
Last active December 15, 2021 21:41
Show Gist options
  • Save josephcsible/e360fdf34d0cb6b821f9e855b252abb5 to your computer and use it in GitHub Desktop.
Save josephcsible/e360fdf34d0cb6b821f9e855b252abb5 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stddef.h>
#include <string.h>
#include <sys/mman.h>
typedef int (delayed_puts_t)(void);
extern delayed_puts_t puts_helper;
extern size_t puts_helper_size;
__asm__ (
"puts_helper:\n"
"endbr64\n"
"mov puts_helper_size(%rip), %rdi\n"
"jmp *puts_helper_size+8(%rip)\n"
"puts_helper_size:\n"
".8byte .-puts_helper"
);
delayed_puts_t *delay_puts(const char *s) {
int (*fp)(const char *) = puts;
delayed_puts_t *mem = mmap(NULL, puts_helper_size + sizeof s + sizeof fp, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
memcpy(mem, &puts_helper, puts_helper_size);
memcpy(mem + puts_helper_size, &s, sizeof s);
memcpy(mem + puts_helper_size + sizeof s, &fp, sizeof fp);
mprotect(mem, puts_helper_size + sizeof s + sizeof fp, PROT_READ|PROT_EXEC);
return mem;
}
int main(void) {
delayed_puts_t *puts_world = delay_puts("world");
delayed_puts_t *puts_hello = delay_puts("hello");
puts_hello();
puts_world();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment