Skip to content

Instantly share code, notes, and snippets.

@0x5742
Created May 20, 2016 21:05
Show Gist options
  • Select an option

  • Save 0x5742/38599ae52987b79db92bd38af681d9bb to your computer and use it in GitHub Desktop.

Select an option

Save 0x5742/38599ae52987b79db92bd38af681d9bb to your computer and use it in GitHub Desktop.
some JIT tests
/+ Found in an old backup. I'm almost scared of what I was doing here... +/
import std.stdio;
import std.string;
import dlfcn;
import std.c.posix.posix;
import std.c.stdio;
/+
void *ptr = dlopen(null, RTLD_NOW);
writefln("%x", ptr);
dlclose(ptr);
+/
typedef int (*funcptr)(...);
int main(char[][] args) {
uint memsz = 655360; // 640k should be enough for anybody
ubyte* mem = cast(ubyte*) mmap(null, memsz,
PROT_READ | PROT_WRITE | PROT_EXEC,
MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
if (mem == MAP_FAILED) {
perror("mmap");
return 1;
}
// fcall result goes into eax
ubyte* p = mem;
ubyte* f1, f2;
// standard function definition
f1 = p;
*p++ = 0x55; // push ebp
*p++ = 0x8b; *p++ = 0xec; // mov ebp, esp
// (body goes here)
*p++ = 0xc9; // leave
*p++ = 0xc3; // ret
// trivial function
// why bother with that ebp/esp stuff if you don't need it?
f2 = p;
*p++ = 0xc3;
// 40+r inc
// 50+r push/pop (+r+8 for pop)
// b0+r+8 movl
// registers:
// 0 eax 2 edx 4 esp 6 esi
// 1 ecx 3 ebx 5 ebp 7 edi
// 74 N je +N
// 75 N jne +N
// eb N jmp +N
// N=0 is a no-op, N=-2 would cause an infinite loop
// ff 25 D C B A jmp dword
// 31 c0 xor eax, eax
// 90 nop
// c9 leave
// c3 ret
writefln((cast(funcptr) f1)());
writefln((cast(funcptr) f2)());
munmap(mem, memsz);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment