coperating-systemprogramming-languages

What code is user mode code and what code is kernel mode code?


I am having a question for myself while taking operating system course.

If I type in any C code to my text editor or though IDE and execute it with the compiler it translates the code into machine code.

Then I would guess if I run the program, the OS will allocate a memory address to the code which is done by kernel code.

And if there was IO interrupt typed into my code, the kernel code executes.

And so...which bit is the user mode code then?


Solution

  • Kernel mode versus user mode actually reflects how the processor is running.

    With modern operating systems, code only runs (with the processor) in kernel mode if it is trusted by the operating system, and all other code runs in user mode.

    The functional difference, under modern operating systems, is that kernel mode code runs in a single (virtual) address space that represents all system resources, so all functions in kernel mode can affect each other directly. For example, all actions by a kernel mode driver can directly affect functioning of the operating system itself and of any other kernel mode driver. (The specific implementation details vary somewhat between operating system types, for example between windows, linux, BSD, etc but the basic principles are the same)

    Which means that, if you are writing code that will execute within the internal workings of the operating system or within a kernel mode driver, then it might be said to be kernel mode code. Otherwise, it will be user-mode code. Code that attempts some action that can only be executed in kernel mode will be prevented from doing so by the processor itself, unless the processor itself is in kernel mode. The operating system mediates when the processor enters kernel mode, which is why a program or driver needs to be recognised by the operating system (or installed, in the case of kernel mode drivers) in order to be permitted do things that can only be done in kernel mode. User mode code can't arbitrarily escalate the processor to kernel mode, without the help of some code that is already recognised by the operating system.

    Practically, modern operating systems also supply a set of functions (e.g. in an API) that can be called from user mode. A lot of those functions are, themselves, executed solely in user mode. Some, however, result in the the processor being switched into kernel mode to perform some specific actions, and then the processor is switched back to user mode by the time control returns to the caller. Which code, within the OS itself, executes in user mode or kernel mode depends both on the design of the operating system and administrative settings (e.g. only suitably privileged users (aka administrators) can, for example, install kernel mode drivers).