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:
- mmap() a block of memory, setting access to PROT_EXEC
- write the native code into the block
- store the current registers (stack pointer, et al.) someplace cozy
- modify the current registers to point into the native code block in the mapped region
- the native code would now get executed by the machine
- 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.
See Question&Answers more detail:os