The kernel does not have a main function. main is a concept of the C language. The kernel is written in C and assembly. The entry code of the kernel is written by assembly.
The boot sequence is organized as follows:
- The BIOS usually loads a boot loader from a boot block device. A popular boot loader right now is grub.
- Grub loads a kernel image into ram, possible with an initial root device (
initrd). Then code at some address is executed.
- The kernel image has some kernel modules, for example: filesystem modules, device drivers. The kernel image use the filesystem module to mount the root filesystem. Now the kernel can load and run all kernel modules from disk.
- The kernel runs initialization tasks. For example: traverse PCI bus and find all PCI devices, initialize all device drivers.
- Finally the kernel creates process 0 and process 1 (the
init process), switches the context of CPU from ring 0 to ring 3, and starts the init process (the process id is 1). Now the kernel boot is finished!
- The
init program runs all init scripts. All services are started. Shell is called. Users can login.
The main function is a C function. Actually main method is not the entry point of C programs. The C runtime calls many functions before main.
GCC has a extend feature: constructors. Functions declared "constructor" are called before main.
For example:
/* This should not be used directly. Use block_init etc. instead. */
#define module_init(function, type) \
static void _attribute__((constructor)) do_qemu_init ## function(void) { \
register_module_init(function, type); \
}
This macro is from the qemu project.