#include #include #include #include #include #include #include #include int main (void) { char *start, *p; int x; start = (char*)mmap(0, getpagesize(), PROT_READ | PROT_WRITE | PROT_EXEC, MAP_ANON | MAP_PRIVATE | MAP_JIT, 0, 0); if (start == (char*)-1) { perror("mmap"); exit(1); } #ifdef PTHREAD_JIT_WRITE_ALLOW_CALLBACKS_NP pthread_jit_write_protect_np(0); #endif p = start; #define W(type, x) do{ *(type*)(p) = (x); p += sizeof(type); }while(0) #if defined(__amd64) W(uint8_t, 0xB8); /* mov eax, ... */ W(uint32_t, 42); W(uint8_t, 0xC3); /* ret */ #elif defined(__arm64) W(uint32_t, 0x52800540); /* mov w0, #0x2a */ W(uint32_t, 0xd65f03c0); /* ret */ #else #error Funny CPU that you have there #endif #ifdef PTHREAD_JIT_WRITE_ALLOW_CALLBACKS_NP pthread_jit_write_protect_np(1); #endif // __builtin___clear_cache(p, p + 2 * sizeof(uint32_t)); sys_icache_invalidate(start, p - start); x = ((int(*)(void))start)(); printf("We got %d\n", x); return 0; }