Skip to content

Instantly share code, notes, and snippets.

@classilla classilla/jitlab1.c
Created Jan 7, 2020

Embed
What would you like to do?
Simple ppc64/ppc64le generated machine code example
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <inttypes.h>
#include <sys/mman.h>
#include <sys/syscall.h>
#include <linux/memfd.h>
uint32_t* jitcode;
uint32_t* jitcode_x;
int (*calljit)();
// op comes right out of the PowerISA 3.0 documentation
#define IMM(op, regsd, rega, imm) (uint32_t)(((op)<<26)|((regsd)<<21)|((rega)<<16)| (((uint64_t)(imm))&0xFFFF))
int main(int argc, char** argv) {
int fd, rv = 0;
size_t pagesize;
pagesize = sysconf(_SC_PAGE_SIZE);
/*
if (posix_memalign((void **)&jitcode, pagesize, rv) != 0) {
perror("posix_memalign");
return -1;
}
if (mprotect(jitcode, pagesize, PROT_READ|PROT_WRITE|PROT_EXEC)) {
perror("mprotect");
return -1;
}
*/
/*
fd = memfd_create("jitlab", MFD_CLOEXEC);
*/
fd = syscall(__NR_memfd_create, "jitlab", MFD_CLOEXEC);
ftruncate(fd, pagesize);
jitcode = (uint32_t*)mmap(NULL, pagesize,
PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
jitcode[0] = IMM(14, 3, 0, 2020); // li r3, 2020
jitcode[1] = IMM(19, 20, 0, 32); // blr
fprintf(stdout, "jitcode at 0x%llx\n", (uint64_t)jitcode);
asm volatile(
"dcbst %y0\n"
"sync\n"
"icbi %y0\n"
"isync\n"
:: "Z"(*jitcode));
jitcode_x = (uint32_t*)mmap(NULL, pagesize,
PROT_READ|PROT_EXEC, MAP_SHARED, fd, 0);
calljit = (int (*)())jitcode_x;
rv = calljit();
fprintf(stdout, "result = %d\n", rv);
munmap(jitcode, pagesize);
munmap(jitcode_x, pagesize);
close(fd);
return 0;
}
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.