3

In a custom OS running on an x86 in protected mode, is there a way to obtain the current privilege level, other than e.g. executing a privileged instruction and seeing if it crashes?

For instance, register CR0 contains the PE bit, which indicates if we are running on real mode or protected mode, and can be easily retrieved using assembly code.

Is there something equivalent for the privilege level?

The Intel architecture software developer manual mentions that the EFLAGS register contains two IOPL bits related to I/O privilege levels. Is this the same as the current privilege level (CPL)?

anol
  • 8,264
  • 3
  • 34
  • 78
  • Do you mean something like `mov ax, cs / and al, 03h`? –  Jul 23 '15 at 12:31
  • He didn't mention that what he's really trying to do is enable SSE: http://stackoverflow.com/questions/31563078/how-do-i-enable-sse-for-my-freestanding-bootable-code/, but modifying `CR0` and `CR4` wasn't working. – Peter Cordes Jul 24 '15 at 11:57

1 Answers1

5

No it's not the same. Those represent the io privilege level. Some instructions such as IN, OUT, CLI require io privileges which are determined using the IOPL and the CPL.

See also:

IOPL I/O privilege level field (bits 12 and 13) -- Indicates the I/O privilege level (IOPL) of the currently running program or task. The CPL of the currently running program or task must be less than or equal to the IOPL to access the I/O address space.

The CPL can be read simply from the CS selector as the two lowest bits:

mov ax, cs
and ax, 3

This of course only works in protected mode.

Jester
  • 56,577
  • 4
  • 81
  • 125
  • 1
    Indeed, very simple once you know it, but not obvious at all when searching for it in the 3603-page long manual. – anol Jul 23 '15 at 12:42