Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Example of using run-time modified machine code to add two numbers.
#include <cstdio>
#include <sys/mman.h>
#include <sys/types.h>
#include <cstring>
#include <cctype>
#include <cstdlib>
int main(int argc, const char * argv[])
{
char a = '\0';
char b = '\0';
do{
printf("Enter a number.\n");
a = getc(stdin);
} while(!isdigit(a));
printf("OK, using %c.\n", a);
do{
printf("Enter a second number.\n");
b = getc(stdin);
} while(!isdigit(b));
printf("OK, using %c.\n", b);
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");
return EXIT_FAILURE;
}
memcpy(lPage, nop, sizeof(nop));
mprotect(lPage, sizeof(nop), PROT_READ|PROT_EXEC);
void (*func)(void);
func = (void (*)(void))lPage;
func();
printf("Successful memory test. Performing addition:\n");
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, 0xC0, (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 = %i.\n", a, b, r);
return EXIT_SUCCESS;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.