Search code examples
coperating-systemosdev

Writing an OS in C language


I would like to know if an operating system can be written in only a language such as C .Can it be done using only C or do I need to use the inline assembly with c?


Solution

  • There are parts of a typical kernel where it's necessary to do things that C doesn't support, including:

    • accessing CPU's special registers (e.g. control registers and MSRs on 80x86)
    • accessing CPU's special features (e.g. CPUID, LGDT, LIDT instructions on 80x86)
    • managing virtual address spaces (e.g. TLB invalidation)
    • saving and loading state during task switches
    • accessing special address spaces (e.g. the IO ports on 80x86)
    • supporting ways for CPU to switch privilege levels

    To write an OS in pure C you need to either avoid all of these things (which is likely to be severely limiting - e.g. single-tasking, single address space, no protection, no IRQs, ...) or cheat by adding "non-standard implementation defined extensions" to C.

    Note that the amount of assembly that you need is very little - e.g. a kernel consisting of 5 million lines of C might only need 100 lines of inline assembly, which works out to "0.00% of the code (with a little rounding error)".

    For boot code/boot loader; it depends on the boot environment. For example, if you booted from UEFI firmware then it's no problem (as its API is designed for high level languages), but if you booted from BIOS firmware then you can't use C alone (due to "unsupportable" calling conventions).