Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <errno.h>
- #include <stdio.h>
- #include <string.h>
- #include <limits.h>
- #ifndef PAGESIZE
- #define PAGESIZE 4096
- #endif
- #include <sys/mman.h>
- const unsigned char code[] = {
- 0x55, // push %rbp
- 0x48, 0x89, 0xe5, // mov %rsp,%rbp
- 0x89, 0x7d, 0xfc, // mov %edi,-0x4(%rbp)
- 0x89, 0x75, 0xf8, // mov %esi,-0x8(%rbp)
- 0x8b, 0x55, 0xfc, // mov -0x4(%rbp),%edx
- 0x8b, 0x45, 0xf8, // mov -0x8(%rbp),%eax
- 0x01, 0xd0, // add %edx,%eax
- 0x5d, // pop %rbp
- 0xc3 // ret
- };
- struct _foo {
- unsigned char lpad[PAGESIZE - (2 << 6)];
- unsigned char code[sizeof(code)];
- unsigned char rpad[(2 << 6) - sizeof(code)];
- } __attribute__((packed));
- struct _foo foo;
- int main(void)
- {
- memcpy(foo.code, code, sizeof(code));
- size_t mask = PAGESIZE - 1;
- unsigned char *foo_p = (unsigned char *)(((long) &foo + mask) & ~mask);
- int (*f) (int, int) = (int (*) (int, int)) foo_p;
- int x = 2;
- int y = 2;
- if (mprotect(foo_p, sizeof(code), PROT_EXEC) < 0) {
- printf("%s\n", strerror(errno));
- return 1;
- }
- int z = f(x, y);
- printf("%d + %d = %d\n", x, y, z);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement