GNU GRUB(Install and Boot)
To maintain modularity while being lightweight grub has divided itself into 2 parts. 1st is the bootloader itself and 2nd is the folder containing modules which is called the prefix folder.
Grub Boot Process:
To modify grub’s boot we 1st need to understand it. Let's start from the BIOS. The BIOS after doing a system check looks for the bootloader and executes it. This is the MBR(1st 512B of disk) or the default efi entry in NVRAM or the efi file in /efi/boot/bootx64.efi for removable disks. After taking over grub tries to find the prefix folder which was hardcoded into it as the “prefix” variable during installation. Grub then tries to load the normal.mod from the respective architecture folder. If Grub fails to do so it will change to rescue mode and wait for the user to fix. The normal mod will load the config from the prefix folder or show the Grub terminal.
Grub fails to find the prefix folder for 2 reasons. Either because the “prefix” variable is wrong or Grub was not compiled with the appropriate file system driver.
Since adding the file system driver inside the MBR 512B is not possible, Grub breaks it’s 1st step into 2 parts. The 1st part is the executable containing the physical address of the file so it doesn't need to understand the file system. The 2nd part is of course the file which usually contains modules to load the normal.mod from the prefix folder. For this reason any file shift on the HDD will cause grub to break.
Grub Install Process:
The grub-install is just a script which calls 2 sub programs. These are “grub-mkimage” and “grub-bios-setup”. The mkimage compiles necessary modules,prefix variables…. to to a core.img. The bios-setup is for MBR. It marges the core.img with pre compiled kernel files located in the architecture folder and puts them in the MBR part if possible or splits them with physical addresses. For UEFI the mkimage directly makes the efi file.
The grub-mkimage syntax is
grub-mkimage options -o core.img
Some important options of grub-mkimage
-c: The path to a config file. This will be used as soon as grub starts. This can be used to help grub find the prefix folder in some complex cases.
-O: The target architecture.
-p:The path of prefix(The partition also needs to be specified.More more portable system use the pre-config).
Some programs like UNetBootIn add grub to windows bootloader. This is possible via the lnxboot.img kernel. This was meant to create a grub bootloader which can be booted from other linux bootloaders like LILO. But the windows bootloader boot sector boot feature also supports this. Simply create a core.img with grub-mkimage and merge it with the lnxboot.img under i386-pc folder. For windows you can use the copy command in binary mode.
copy /b lnxboot.img+core.img grub.mbr