39

I'd like to write a very small proof-of-concept JIT compiler for a toy language processor I've written (purely academic), but I'm having some trouble in the middle-altitudes of design. Conceptually, I'm familiar with how JIT works - you compile bytecode into (machine or assembly?) code to run. At the nuts-and-bolts level however, I'm not quite gripping how you actually go about doing that.

My (very "newb") knee-jerk reaction, since I haven't the first clue where to start, would be to try something like the following:

  1. mmap() a block of memory, setting access to PROT_EXEC
  2. write the native code into the block
  3. store the current registers (stack pointer, et al.) someplace cozy
  4. modify the current registers to point into the native code block in the mapped region
  5. the native code would now get executed by the machine
  6. restore the previous registers

Is that even close to a/the correct algorithm? I've tried perusing different projects that I know have JIT compilers to study (such as V8) but these codebases turn out to be difficult to consume because of their size, and I've little idea where to start looking.

Chris Tonkinson
  • 13,823
  • 14
  • 58
  • 90
  • 9
    You can probably simplify things further: you can often just take the starting address of your code within the `mmap`'ed block and cast it to a function pointer. In that case, the code would need to save and restore its own registers and such. You would want to look at the calling conventions in your platforms ABI (Application Binary Interface) for exactly what you need to save (and how to get arguments from C code, call C functions, etc.). – Jeremiah Willcock Feb 06 '11 at 06:54
  • Not that I have that much experience with this, but you might way to check out PiPi's python interpreter. I've looked through the CPython interpreter and it's pretty good to read. – Falmarri Feb 06 '11 at 07:21
  • 1
    @Jeremiah Willcock: It seems to me like that's roughly the technique demonstrated by @Shelwien below, am I correct? – Chris Tonkinson Feb 06 '11 at 16:27
  • 3
    mmap to PROT_EXEC will probably not work. I don't believe current versions of Linux allow any memory to be both writable and executable at the same time. You need to map it writable, write it, then map it executable. Or so I believe. – Zan Lynx Feb 07 '11 at 23:13
  • 1
    Actually it seems to be working just fine in my experiment thus far. I'm using a recent build of the kernel (2.6.35) and setting my `mmap()` access rights with `PROT_READ | PROT_WRITE | PROT_EXEC` – Chris Tonkinson Feb 07 '11 at 23:21
  • 2
    @Chris: I guess it works for you. I know it didn't work for me. It might have been a Gentoo secure kernel. You might run into trouble on some systems. – Zan Lynx Feb 08 '11 at 00:04
  • 4
    Not that you're targeting non-x86, but beware that self modifying code (or on-the-fly generated code) requires explicit cache synchronization on other platforms. It's pretty much just x86 which does it transparently (which means loads of silicon). Just call msync() on the buffer after finishing writing and before executing it. – John Ripley Feb 08 '11 at 02:35
  • 1
    @John Ripley: Thanks for the advice. That'd be a tough one to debug! – Chris Tonkinson Feb 08 '11 at 13:03

7 Answers7

34

Not sure about linux, but this works on x86/windows.
Update: http://codepad.org/sQoF6kR8

#include <stdio.h>
#include <windows.h>

typedef unsigned char byte;

int arg1;
int arg2;
int res1;

typedef void (*pfunc)(void);

union funcptr {
  pfunc x;
  byte* y;
};

int main( void ) {

  byte* buf = (byte*)VirtualAllocEx( GetCurrentProcess(), 0, 1<<16, MEM_COMMIT, PAGE_EXECUTE_READWRITE );

  if( buf==0 ) return 0;

  byte* p = buf;

  *p++ = 0x50; // push eax
  *p++ = 0x52; // push edx

  *p++ = 0xA1; // mov eax, [arg2]
  (int*&)p[0] = &arg2; p+=sizeof(int*);

  *p++ = 0x92; // xchg edx,eax

  *p++ = 0xA1; // mov eax, [arg1]
  (int*&)p[0] = &arg1; p+=sizeof(int*);

  *p++ = 0xF7; *p++ = 0xEA; // imul edx

  *p++ = 0xA3; // mov [res1],eax
  (int*&)p[0] = &res1; p+=sizeof(int*);

  *p++ = 0x5A; // pop edx
  *p++ = 0x58; // pop eax
  *p++ = 0xC3; // ret

  funcptr func;
  func.y = buf;

  arg1 = 123; arg2 = 321; res1 = 0;

  func.x(); // call generated code

  printf( "arg1=%i arg2=%i arg1*arg2=%i func(arg1,arg2)=%i\n", arg1,arg2,arg1*arg2,res1 );

}
Shelwien
  • 2,160
  • 15
  • 17
  • 1
    @Shelwien: It was most definitely not portable before, since most modern OS's would not accept execution of the stack. – Puppy Feb 06 '11 at 11:23
  • 1
    Thanks for the great example! I very nearly didn't catch that `funcptr` was a `union` at first - after that it made perfect sense. – Chris Tonkinson Feb 06 '11 at 16:27
  • First version used a simple typecast there, like ((pfunc)(void*)buf)(); , but codepad said something about ISO C++ not allowing to cast random stuff to functions, so i had to replace it with a union. – Shelwien Feb 06 '11 at 16:46
  • 1
    What would be the modification(s) required to work on x64? I'm not an assembly expert, but I don't see anything that x64 wouldn't find reverse-compatible. – Chris Tonkinson Feb 06 '11 at 19:23
  • I meant that the generated code there is 32-bit, x64 code would be different. I can make a x64 version if necessary, but is it? – Shelwien Feb 07 '11 at 11:09
  • No, not at all - it was simply my [mis]understanding that 32 bit code could run on a 64 bit machine with little or no modification. – Chris Tonkinson Feb 07 '11 at 15:29
  • Anyway, updated to a "universal" version. Previous one wasn't compatible because x64 doesn't have PUSHA/POPA, nor IMUL r32,[m64] – Shelwien Feb 07 '11 at 20:00
  • I see. I translated this code for Linux (basically just swapped your `VirtualAllocEx` for an `mmap`) and she works like a charm! – Chris Tonkinson Feb 07 '11 at 21:05
  • @Shelwien: I have thought that tricks like above should only be available for system to block polymorphic viruses. But on the other side virtual machines won't be able to make translation of the program being interpreted into machine codes on the fly. – dma_k Mar 26 '11 at 22:34
  • Polymorphic viruses don't have to execute generated code in memory, generated code is used to infect another machine, so blocking of data execution won't help much. – Shelwien Mar 26 '11 at 23:54
5

Youmay want to have a look at libjit which provides exactly the infrastructure you're looking for:

The libjit library implements just-in-time compilation functionality. Unlike other JITs, this one is designed to be independent of any particular virtual machine bytecode format or language.

http://freshmeat.net/projects/libjit

datenwolf
  • 159,371
  • 13
  • 185
  • 298
4

How to JIT - an introduction is a new article (from today!) that addresses some of these issues and describes the bigger picture as well.

Eli Bendersky
  • 263,248
  • 89
  • 350
  • 412
4

The Android Dalvik JIT compiler might also be worth looking at. It is supposed to be fairly small and lean (not sure if this helps understanding it or makes things more complicated). It targets Linux as well.

If things are getting more serious, looking at LLVM might be a good choice as well.

The function pointer approach suggested by Jeremiah sounds good. You may want to use the caller's stack anyway and there will probably only be a few registers left (on x86) which you need to preserve or not touch. In this case, it is probably easiest if your compiled code (or the entry stub) saves them on the stack before proceeding. In the end, it all boils down to writing an assembler function and interfacing to it from C.

sstn
  • 3,050
  • 19
  • 32
2

The answer depends on your compiler and where you put the code. See http://encode.ru/threads/1273-Just-In-Time-Compilation-Improvement-For-ZPAQ?p=24902&posted=1#post24902

Testing in 32 bit Vista, Visual C++ gives a DEP (data execution prevention) error whether the code is put on the stack, heap, or static memory. g++, Borland, and Mars can be made to work sometimes. Data accessed by the JIT code needs to be declared volatile.

1

In addition to the techniques suggested so far, it might be worthwhile to look into the thread creation functions. If you create a new thread, with the starting address set to your generated code, you know for sure that there are no old registers that need saving or restoring, and the OS handles the setup of the relevant registers for you. I.e you eliminate steps 3, 4 and 6 of your list.

MSalters
  • 173,980
  • 10
  • 155
  • 350
  • The only thing I would hesitate on here is that with threads, you then have to deal with synchronization, et al. - otherwise (if synchronization can be ignored and/or deferred) that's a pretty clever idea. – Chris Tonkinson Feb 07 '11 at 17:20
0

You may be interested in why the lucky stiff's Potion programming language. It's a small, incomplete language that features just-in-time compilation. Potion's small size makes it easier to understand. The repository includes a description of the language's internals (JIT content starts at heading "~ the jit ~").

The implementation is complicated by the fact it runs in the context of Potion's VM. Don't let this scare you off, though. It doesn't take long to see what he's up to. Basically, using a small set of VM opcodes allows some actions to be modeled as optimized assembly.

Corbin March
  • 25,526
  • 6
  • 73
  • 100