<p>How does a virtual machine generate native machine code on the fly and execute it?</p>

<p>Assuming you can figure out what are the native machine op-codes you want to emit, how do you go about actually running it?</p>

<p>Is it something as hacky as mapping the mnemonic instructions to binary codes, stuffing it into an char* pointer and casting it as a function and executing?</p>

<p>Or would you generate a temporary shared library (.dll or .so or whatever) and load it into memory using standard functions like <code>LoadLibrary</code> ?</p>

[{'answer_id': 45416, 'author': 'Erick Sgarbi', 'author_id': 4171, 'author_profile': 'https://Stackoverflow.com/users/4171', 'pm_score': 1, 'selected': False, 'text': '<p>As far as i know it compiles everything in memory because it has to run some heuristics to    to optimize the code (i.e.: inlining over time) but you can have a look at the <a href="http://www.microsoft.com/downloads/details.aspx?FamilyID=8c09fd61-3f26-4555-ae17-3121b4f51d4d&amp;displaylang=en" rel="nofollow noreferrer">Shared Source Common Language Infrastructure 2.0</a> rotor release. The whole codebase is identical to .NET except for the Jitter and the GC.</p>\n'}, {'answer_id': 45417, 'author': 'Chris de Vries', 'author_id': 3836, 'author_profile': 'https://Stackoverflow.com/users/3836', 'pm_score': 4, 'selected': True, 'text': '<p>You can just make the <a href="http://en.wikipedia.org/wiki/Program_counter" rel="noreferrer">program counter</a> point to the code you want to execute. Remember that data can be data or code. On x86 the program counter is the EIP register. The IP part of EIP stands for instruction pointer. The JMP instruction is called to jump to an address. After the jump EIP will contain this address.</p>\n\n<blockquote>\n  <p>Is it something as hacky as mapping the mnemonic instructions to binary codes, stuffing it into an char* pointer and casting it as a function and executing?</p>\n</blockquote>\n\n<p>Yes. This is one way of doing it. The resulting code would be cast to a <a href="http://en.wikipedia.org/wiki/Pointer_to_function" rel="noreferrer">pointer to function</a> in C.</p>\n'}, {'answer_id': 68221, 'author': 'Christopher Dolan', 'author_id': 9418, 'author_profile': 'https://Stackoverflow.com/users/9418', 'pm_score': 1, 'selected': False, 'text': '<p>As well as Rotor 2.0 - you could also take a look at the <a href="http://openjdk.java.net/groups/hotspot/" rel="nofollow noreferrer">HotSpot virtual machine</a> in the OpenJDK.</p>\n'}, {'answer_id': 68294, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 3, 'selected': False, 'text': "<blockquote>\n  <p>Is it something as hacky as mapping the mnemonic instructions to binary codes, stuffing it into an char* pointer and casting it as a function and executing?</p>\n</blockquote>\n\n<p>Yes, if you were doing it in C or C++ (or something similar), that's exactly what you'd do.</p>\n\n<p>It appears hacky, but that's actually an artifact of the language design. Remember, the actual algorithm you want to use is very simple: determine what instructions you want to use, load them into a buffer in memory, and jump to the beginning of that buffer.</p>\n\n<p>If you really try to do this, though, make sure you get the calling convention right when you return to your C program. I think if I wanted to generate code I'd look for a library to take care of that aspect for me. Nanojit's been in the news recently; you could look at that.</p>\n"}, {'answer_id': 91537, 'author': 'Brian', 'author_id': 17524, 'author_profile': 'https://Stackoverflow.com/users/17524', 'pm_score': 2, 'selected': False, 'text': "<p>Yup. You just build up a char* and execute it. However, you need to note a couple details. The char* must be in an executable section of memory and must have proper alignment.</p>\n\n<p>In addition to nanojit you can also check out LLVM which is another library that's capable of compiling various program representations down to a function pointer. It's interface is clean and the generated code tends to be efficient.</p>\n"}, {'answer_id': 445214, 'author': 'Blaisorblade', 'author_id': 53974, 'author_profile': 'https://Stackoverflow.com/users/53974', 'pm_score': 1, 'selected': False, 'text': '<p>About generating a DLL: the additional required I/O for that, plus linking, plus the complexity of generating the DLL format, would make that much more complicate, and above all they\'d kill performance; additionally, in the end you still call a function pointer to the loaded code, so...\nAlso, JIT compilation can happen one method at a time, and if you want to do that you\'d generate lots of small DLLs.</p>\n\n<p>About the "executable section" requirement, calling mprotect() on POSIX systems can fix the permissions (there\'s a similar API on Win32). You need to do that for a big memory segment instead that once per method since it\'d be too slow otherwise.</p>\n\n<p>On plain x86 you wouldn\'t notice the problem, on x86 with PAE or 64bit AMD64/Intel 64 bit machines you\'d get a segfault.</p>\n'}, {'answer_id': 3160622, 'author': 'Maruf Maniruzzaman', 'author_id': 381397, 'author_profile': 'https://Stackoverflow.com/users/381397', 'pm_score': 1, 'selected': False, 'text': '<blockquote>\n  <p>Is it something as hacky as mapping\n  the mnemonic instructions to binary\n  codes, stuffing it into an char*\n  pointer and casting it as a function\n  and executing?</p>\n</blockquote>\n\n<p>Yes, that works.</p>\n\n<p>To do this in windows you must set PAGE_EXECUTE_READWRITE to the allocated block:</p>\n\n<pre><code>void (*MyFunc)() = (void (*)()) VirtualAlloc(NULL, sizeofblock,  MEM_COMMIT, PAGE_EXECUTE_READWRITE);\n\n//Now fill up the block with executable code and issue-\n\nMyFunc();\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/45408', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/618/']