A system, method and computer program product for optimizing handling of
guest code in a Virtual Machine include code for identifying, in the
guest code, a predetermined pattern that includes privileged but unsafe
instructions and an instruction that raises an exception; code for
executing the guest code in a native mode; code for, upon encountering
the instruction that raise the exception, transferring control to a
Virtual Machine Monitor; code for emulating the pattern in the Virtual
Machine Monitor; and code for rolling back the effects of privileged but
unsafe instructions and any intervening instructions to ensure correct
Virtual Machine Monitor context. The pattern can include, for example, a
privileged but unsafe instruction, followed by safe instructions,
followed by an exception raising instruction, followed by safe
instructions, followed by a privileged but unsafe instruction.
Optionally, the most frequently occurring patterns can be placed in a
cache, for use by the Virtual Machine Monitor to verify their presence in
the guest code.