How do I detect programmatically in which ring (-1, 0, 1, 2, 3) I am running?
views:
319answers:
3Unless you're a device driver, you'll always be running in Ring 3 (for systems that have "rings", per se).
The easiest way is, to just run the (x86) command and catch the corresponding error.
E.g. (SEH, Windows, kernel mode)
bool ring_lower_0 = false;
__try
{
__asm { <cmd> };
ring_lower_0 = true;
}
__except( GetExceptionCode() == EXCEPTION_PRIV_INSTRUCTION )
{
ring_lower_0 = false;
}
Notes:
cmd, is an assembler command. See the Intel Architecture Reference Manuals for a list of commands and their respective Ring levels.
Linux has a slightly different concept.
But remember that VMs residing on a lower level may mask the result by emulating the call.
(NB: The Job of the VM is to translate the invalid instruction into an meaningful call)
If you really want to check if your a virtualized and want to stop execution because of this, you should read what has been written about 'Red pill'.
Normally i would write that you should read about "protected mode programming". There is an article about how to intertact with ring 0 using windows XP SP2. Note that it will change for others windows versions and for sure others operational systems.
http://www.codeproject.com/KB/threads/MinimalisticRingZero.aspx
If you just want to detect if you are running inside of a virtual machine, to avoid that people debug your application, for example, you can check here: