Skip to content

Instantly share code, notes, and snippets.

@heatblazer
Created December 21, 2020 19:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save heatblazer/2d0b8546fafab9ced6d4d875bf3cc401 to your computer and use it in GitHub Desktop.
Save heatblazer/2d0b8546fafab9ced6d4d875bf3cc401 to your computer and use it in GitHub Desktop.
#include <sys/mman.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <stdint.h>
/* from objdump - S
int foo(int a, int b)
{
401110: 55 push %rbp
401111: 48 89 e5 mov %rsp,%rbp
401114: 89 7d fc mov %edi,-0x4(%rbp)
401117: 89 75 f8 mov %esi,-0x8(%rbp)
return a+b;
40111a: 8b 45 fc mov -0x4(%rbp),%eax
40111d: 03 45 f8 add -0x8(%rbp),%eax
401120: 5d pop %rbp
401121: c3 retq
401122: 66 2e 0f 1f 84 00 00 nopw %cs:0x0(%rax,%rax,1)
401129: 00 00 00
40112c: 0f 1f 40 00 nopl 0x0(%rax)
*/
int foo(int a, int b)
{
return a+b;
}
int main()
{
unsigned char code[] =
{
0x55,
0x48, 0x89, 0xe5,
0x89, 0x7d, 0xfc,
0x89, 0x75, 0xf8,
0x8b, 0x45, 0xfc,
0x03, 0x45, 0xf8,
0x5d, 0xc3
};
size_t pagesize = sysconf(_SC_PAGESIZE);
uintptr_t pagestart = ((uintptr_t) &code) & -pagesize;
if(mprotect((void*) pagestart, pagesize, PROT_READ|PROT_WRITE|PROT_EXEC)){
perror("mprotect");
return 1;
}
int c = ((int(*)())code)(100, 200); //execute instruction
printf("Successfully executed![%d]\n", c);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment