Skip to content

Instantly share code, notes, and snippets.

@sandip4n
Created May 11, 2020 03:43
Show Gist options
  • Save sandip4n/a5884269b9da82fe66c00593d50bd168 to your computer and use it in GitHub Desktop.
Save sandip4n/a5884269b9da82fe66c00593d50bd168 to your computer and use it in GitHub Desktop.
#ifndef __powerpc64__
#error "unsupported architecture"
#endif
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <unistd.h>
#include <sys/mman.h>
int main(void)
{
unsigned long pgsize, numinsns;
unsigned int *insns;
int i;
/* allocate a page for the executable image */
pgsize = sysconf(_SC_PAGESIZE);
numinsns = pgsize / sizeof(unsigned int);
insns = (unsigned int *) mmap(NULL, pgsize,
PROT_READ | PROT_WRITE | PROT_EXEC,
MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
if (insns == MAP_FAILED) {
perror("mmap");
return EXIT_FAILURE;
}
/* fill image with no-ops, not using any stack operations
for now so a callee stack frame is not created here */
for (i = 0; i < numinsns - 1; i++)
insns[i] = 0x60000000; /* nop */
/* last instruction in the image to return back
to the caller */
insns[numinsns - 1] = 0x4e800020; /* blr */
puts("jumping to mmap-ed region");
/* use a linked branch as that update the return address
automatically in LR and use an unconditional branch to
LR in the mmap-ed image to return back */
asm volatile("mtctr %0" : : "r"((unsigned long) insns));
asm volatile("bctrl");
puts("returned from mmap-ed region");
/* cleanup */
munmap((void *) insns, pgsize);
return EXIT_SUCCESS;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment