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.