views:

232

answers:

7

It came to my attention some emulators and virtual machines use dynamic recompilation. How do they do that? In C i know how to call a function in ram using typecasting (although i never tried) but how does one read opcodes and generate code for it? Does the person need to have premade assembly chunks and copy/batch them together? is the assembly written in C? If so how do you find the length of the code? How do you account for system interrupts?

-edit-

system interrupts and how to (re)compile the data is what i am most interested in. Upon more research i heard of one person (no source available) used js, read the machine code, output js source and use eval to 'compile' the js source. Interesting.

A: 

IIS does this by shadow copying: after compilation it copies assemblies to some temporary place and runs them from temp.

Imagine, that user change some files. Then IIS will recompile asseblies in next steps:

  1. Recompile (all requests handled by old code)
  2. Copies new assemblies (all requests handled by old code)
  3. All new requests will be handled by new code, all requests - by old.

I hope this'd be helpful.

Aen Sidhe
Thats not what i am talking about. I am talking about taking in raw bytes that is not source code IE you need to write the compiler and have it load in code naively. I saw a bad example with inline assembly which i think is batch together but it doesnt appear to work it was a bad example.
acidzombie24
+1  A: 

It's quite possible - though obviously not trivial - to disassemble code from a memory pointer, optimize the code in some way, and then write back the optimized code - either to the original location or to a new location with a jump patched into the original location.

Of course, emulators and VMs don't have to RE-write, they can do this at load-time.

500 - Internal Server Error
i dont think it is possible to disassemble code from a memory pointer without knowing the processor your on IE processor specific.
acidzombie24
@acidzombie: Everything you are talking about is processor specific.
BlueRaja - Danny Pflughoeft
@acidzombie: Correct - this will be very platform specific. Is there something in particular that you're trying to accomplish?
500 - Internal Server Error
Per Larsen: No but i dont understand how you can do system interrupts with dynamic recompilation and also i dont know is it possible or not to do this without knowing the machine code of the processor and i dont know is there is some kind of OS problem where you cannot execute code on ram. (or even read assembly code compiled in a C function)
acidzombie24
If you are an emulator or VM, there's usually no restrictions on what you can do to the code - though on Windows and some other OSes you'll have to (temporarily) change the page protection attributes to patch code. If you're the application itself, you may crash if you modify code that's already being executed by another thread, so you have to take precautions to prevent that from happening.As previously discussed, there is no platform-agnostic way to do this sort of thing.
500 - Internal Server Error
+1. I am waiting until the last hour to select
acidzombie24
A: 

A virtual Machine loads "byte code" or "intermediate language" and not machine code therefore, I suppose, that it just recompiles the byte code more efficiently once it has more runtime data.

http://en.wikipedia.org/wiki/Just-in-time_compilation

Yaneeve
Really? I never heard of VMs using bytecode instead of machine code. Are you positive? I cant think of how VMs may have windows XP/7/server as bytecode before applying JIT.
acidzombie24
@acidzombie: ah, you're confusing two related meanings of the term VM. The Java Virtual Machine is an entirely different beast from the VMWare virtual machine. The first simulates a virtual Java architecture, the second a real (x86) architecture. "Byte code" is merely the assembler of a virtual architecture.
MSalters
@MSalters: Oh i see what you mean. Now what i want to know is HOW does one recompile. It sounds like i MUST have knowledge of the target platform machine code to dynamically recompile. I am still interested in how interrupts are handled
acidzombie24
+1  A: 

It sounds like i MUST have knowledge of the target platform machine code to dynamically recompile

Yes, absolutely. That is why parts of the Java Virtual Machine must be rewritten (namely, the JIT) for every architecture.

When you write a virtual machine, you have a particular host-architecture in mind, and a particular guest-architecture. A portable VM is better called an emulator, since you would be emulating every instruction of the guest-architecture (guest-registers would be represented as host-variables, rather than host-registers).

When the guest- and host-architectures are the same, like VMWare, there are a ton of (pretty neat) optimizations you can do to speed up the virtualization - today we are at the point that this type of virtual machine is BARELY slower than running directly on the processor. Of course, it is extremely architecture-dependent - you would probably be better off rewriting most of VMWare from scratch than trying to port it.

BlueRaja - Danny Pflughoeft
A: 

Here's an explaination of how they are doing dynamic recompilation for the 'Rubinius' Ruby interpteter:

http://www.engineyard.com/blog/2010/making-ruby-fast-the-rubinius-jit/

AShelly
A: 

This approach is typically used by environments with an intermediate byte code representation (like Java, .net). The byte code contains enough "high level" structures (high level in terms of higher level than machine code) so that the VM can take chunks out of the byte code and replace it by a compiled memory block. The VM typically decide which part is getting compiled by counting how many times the code was already interpreted, since the compilation itself is a complex and time-consuming process. So it is usefull to only compile the parts which get executed many times.

but how does one read opcodes and generate code for it?

The scheme of the opcodes is defined by the specification of the VM, so the VM opens the program file, and interprets it according to the spec.

Does the person need to have premade assembly chunks and copy/batch them together? is the assembly written in C?

This process is an implementation detail of the VM, typically there is a compiler embedded, which is capable to transform the VM opcode stream into machine code.

How do you account for system interrupts?

Very simple: none. The code in the VM can't interact with real hardware. The VM interact with the OS, and transfer OS events to the code by jumping/calling specific parts inside the interpreted code. Every event in the code or from the OS must pass the VM.

Also hardware virtualization products can use some kind of JIT. A typical use cases in the X86 world is the translation of 16bit real mode code to 32 or 64bit protected mode code to not to be forced to emulate a CPU in real mode. Also a software-only VM replaces jump instructions in the executing code by jumps into the VM control software, which at each branch the following code path for jump instructions scans and them replace, before it jumps to the real code destination. But I doubt if the jump replacement qualifies as JIT compilation.

Rudi
+1  A: 

This is a wide open question, not sure where you want to go with it. Wikipedia covers the generic topic with a generic answer. The native code being emulated or virtualized is replaced with native code. The more the code is run the more is replaced.

I think you need to do a few things, first decide if you are talking about an emulation or a virtual machine like a vmware or virtualbox. An emulation the processor and hardware is emulated using software, so the next instruction is read by the emulator, the opcode pulled apart by code and you determine what to do with it. I have been doing some 6502 emulation and static binary translation which is dynamic recompilation but pre processed instead of real time. So your emulator may take a LDA #10, load a with immediate, the emulator sees the load A immediate instruction, knows it has to read the next byte which is the immediate the emulator has a variable in the code for the A register and puts the immediate value in that variable. Before completing the instruction the emulator needs to update the flags, in this case the Zero flag is clear the N flag is clear C and V are untouched. But what if the next instruction was a load X immediate? No big deal right? Well, the load x will also modify the z and n flags, so the next time you execute the load a instruction you may figure out that you dont have to compute the flags because they will be destroyed, it is dead code in the emulation. You can continue with this kind of thinking, say you see code that copies the x register to the a register then pushes the a register on the stack then copies the y register to the a register and pushes on the stack, you could replace that chunk with simply pushing the x and y registers on the stack. Or you may see a couple of add with carries chained together to perform a 16 bit add and store the result in adjacent memory locations. Basically looking for operations that the processor being emulated couldnt do but is easy to do in the emulation. Static binary translation which I suggest you look into before dynamic recompilation, performs this analysis and translation in a static manner, as in, before you run the code. Instead of emulating you translate the opcodes to C for example and remove as much dead code as you can (a nice feature is the C compiler can remove more dead code for you).

Once the concept of emulation and translation are understood then you can try to do it dynamically, it is certainly not trivial. I would suggest trying to again doing a static translation of a binary to the machine code of the target processor, which a good exercise. I wouldnt attempt dynamic run time optimizations until I had succeeded in performing them statically against a/the binary.

virtualization is a different story, you are talking about running the same processor on the same processor. So x86 on an x86 for example. the beauty here is that using non-old x86 processors, you can take the program being virtualized and run the actual opcodes on the actual processor, no emulation. You setup traps built into the processor to catch things, so loading values in AX and adding BX, etc these all happen at real time on the processor, when AX wants to read or write memory it depends on your trap mechanism if the addresses are within the virtual machines ram space, no traps, but lets say the program writes to an address which is the virtualized uart, you have the processor trap that then then vmware or whatever decodes that write and emulates it talking to a real serial port. That one instruction though wasnt realtime it took quite a while to execute. What you could do if you chose to is replace that instruction or set of instructions that write a value to the virtualized serial port and maybe have then write to a different address that could be the real serial port or some other location that is not going to cause a fault causing the vm manager to have to emulate the instruction. Or add some code in the virtual memory space that performs a write to the uart without a trap, and have that code instead branch to this uart write routine. The next time you hit that chunk of code it now runs at real time.

Another thing you can do is for example emulate and as you go translate to a virtual intermediate bytcode, like llvm's. From there you can translate from the intermediate machine to the native machine, eventually replacing large sections of program if not the whole thing. You still have to deal with the peripherals and I/O.

dwelch

related questions