Created
January 7, 2020 05:46
-
-
Save classilla/2eaa978de3ee7434bd989a93d67fff0d to your computer and use it in GitHub Desktop.
Simple ppc64/ppc64le generated machine code example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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