1

Let's say you compile a C program into an executable and run it. (Assume code running on x86 architecture)

When the CPU is executing the machine code, it will inevitably need to execute instructions outside of ring-3 (user-mode). When executing some instructions, it will need to jump down to ring-0.

But how does the CPU know it needs to change modes? My first guess was that when the CPU fetches an instruction from RAM, it decodes it and a register value gets set. Depending on the register value during the execution of that instruction, the CPU will change modes.

But if this is the case, couldn't someone write malicious code to purposefully tell the CPU to switch modes so that it always executes in Kernel mode for the desired instructions?

Thank you!

Also, if there's a good resource/textbook for the intro/learning about CPU-modes, I would love to check that out. I can't find any good ones so far.

katie1245
  • 1,127
  • 8
  • 10
  • You have read about x86 instructions, haven't you? Any instruction which switches the mode from user to kernel jumps into preset address inside the kernel. – Tsyvarev Jan 28 '21 at 23:54
  • The CPU is a state machine. It works by keeping an internal state. Instruction modifies this state. Some instructions allow for a controlled switch of that part of the state that keeps track of the current privilege level. One can tell the CPU to switch mode (eg `syscall`) but only to execute the OS code, not its own code. You can find more info in the Intel manuals. – Margaret Bloom Jan 29 '21 at 09:58

0 Answers0