Skip to content

Instantly share code, notes, and snippets.

@igstan
Created November 30, 2022 20:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save igstan/d2b7bd19cb9540bfb36e1270a6eee00d to your computer and use it in GitHub Desktop.
Save igstan/d2b7bd19cb9540bfb36e1270a6eee00d to your computer and use it in GitHub Desktop.
Hello World JIT for Apple Silicon
#include <pthread.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <sys/mman.h>
static uint8_t code[] = {
0x40, 0x05, 0x80, 0x52, // mov w0, #3
0xc0, 0x03, 0x5f, 0xd6, // ret
};
int main(int argc, const char * argv[]) {
const int size = sizeof(code);
int map_flags = MAP_ANON | MAP_PRIVATE | MAP_JIT;
void* mem = (int *)mmap(NULL, size, PROT_READ | PROT_WRITE | PROT_EXEC, map_flags, -1, 0);
if (mem == MAP_FAILED || mem == NULL) {
printf("Failed to allocate executable memory\n");
return 1;
}
pthread_jit_write_protect_np(false);
memcpy(mem, code, size);
pthread_jit_write_protect_np(true);
int (*jitted_function)(void) = (int (*)(void))mem;
printf("JIT-ed code returned: %d\n", jitted_function());
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment