tags:

views:

311

answers:

3

How does JVM/CLR execute JIT compiled native code? Is it by some code injection or by copying code to executable memory? What are the system calls that allows dynamic code execution?

+1  A: 

I don't know specifically how Java does it, but in general you'd insert "trap" opcodes into the interpreter's instruction stream. There are two opcodes in the JVM spec that seem tailor-made for this purpose.

If you want to know for sure, there's no better answer than the source: http://download.java.net/jdk6/source/

kdgregory
+1  A: 

The Common Language Runtime has a methodtable for each type with entries pointing to native code or a native stub to JIT managed code and then fixup the methodtable with the pointer to the just created native code.

MSDN has a more in depth explanation in the MethodDesc section

This blog entry by Dave Notario explains how the CLR JIT compiler works.

David Silva Smith
+2  A: 

I can explain how we do it in CACAO VM (a research JIT-only JVM). First, the machine code for a method is generated into some heap-allocated memory block. After compilation, the final code length is known, and a chunk of executable memory is allocated using mmap and the PROT_EXEC flag (relevant CACAO code here). Then, the machine code is copied into the mmapped area. After that, many architectures require some machine-specific cache flushing mechanism. As an example, have a look at the cache-flushing function for PowerPC 64. Notably, on i386 and x86_64, there is nothing to do. After this step, the processor is ready to execute the newly-generated code. Alternatively, already allocated memory pages can be marked executable with mprotect. Note that mmap/mprotect are Unix facilities.

Ringding
Considering DEP and the clear separation of data and executable code and that executable memory cannot be written to and data memory cannot be jumped/executed to, I'd be still very interested in how it's done on Win32 systems with CLR/JIT.
Abel