Skip to content

Instantly share code, notes, and snippets.

Last active Aug 29, 2015
What would you like to do?
You can also modify actual instructions as well as data.
#include <cstdio>
#include <sys/mman.h>
#include <sys/types.h>
#include <cstring>
#include <cctype>
#include <cstdlib>
int main(int argc, const char * argv[])
bool Add = true;
char a = '\0';
char b = '\0';
printf("Enter a number.\n");
a = getc(stdin);
} while(!isdigit(a));
printf("OK, using %c.\n", a);
printf("Enter a second number.\n");
b = getc(stdin);
} while(!isdigit(b));
printf("OK, using %c.\n", b);
char t = '\0';
t = getc(stdin);
printf("Press 'a' to add, 's' to subtract.\n");
}while(t!='a' && t!='s');
Add = false;
printf("Running memory test.\n");
// What we want to execute.
unsigned char nop[] = {0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0xC3};
void *lPage = mmap(nullptr, 0xFF, PROT_READ|PROT_WRITE, MAP_ANON|MAP_SHARED, -1, 0);
if((lPage==NULL)||(lPage==(void *)(~NULL))){
printf("Memory map failed.\n");
memcpy(lPage, nop, sizeof(nop));
mprotect(lPage, sizeof(nop), PROT_READ|PROT_EXEC);
void (*func)(void);
func = (void (*)(void))lPage;
printf("Successful memory test. Performing %s:\n", Add?"addition":"subtraction");
char ac[] = {a, 0};
char bc[] = {b, 0};
unsigned char adds[] = {
0x48, 0xC7, 0xC0, (unsigned char)atoi(ac), /*put a in rax.*/
0, 0, 0, /*align*/
0x48, 0x83, (unsigned char)(Add?0xC0:0xE8), (unsigned char)atoi(bc), /*Add b to rax, storing result in rax.*/
0xC3, /*return. Return values are in rax in x86_64.*/
mprotect(lPage, sizeof(adds), PROT_READ|PROT_WRITE);
memcpy(lPage, adds, sizeof(adds));
mprotect(lPage, sizeof(adds), PROT_READ|PROT_EXEC);
int (*ifunc)(void);
ifunc = (int (*)(void))lPage;
int r = ifunc();
printf("In program-modified machine code, %c %c %c = %i.\n", a, Add?'+':'-', b, r);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment