Writing an GRUB module
Recently I’m writing a GRUB module. And to be honest, the GRUB documentation is really bad. Usually OSS project like GCC would have detailed compiling/debugging notes for other developers. But in GRUB I can find nothing. Googling shows almost NOTHING. But eventually I finished my module, so I’m here leaving some notes for others.
Module template
Usually grub module are compiled in-the-tree, so you’ll need to have a grub code base and bootstrap it. However there’re some helper scripts to simplify the process: https://github.com/jesusdf/grub-msr
Noticing grub-msr is already being merged into upstream, so that module is surely of high quality. Using those scripts will simply give you a GRUB building environment. And then you can simply use that repo as a template to implement your own feature
Caveats
A good module name is very crucial. If the module name is too long, or contains hyphen( “-” ), you may have successful builds, but you will then experience many random crashes.
Debugging
Debugging is quite easy. First we need to setup the grub installtion
- make install
- dd if=/dev/zero of=testgrub bs=1M count=100
- fdisk testgrub # init MS-DOS partition map and create a partition
- sudo kpartx -c -v testgrub
- sudo mkfs.ext4 /dev/mapper/loopXXp1
- sudo mount /dev/mapper/loopXXp1 tt
-
grub-install -v –target=i386-pc –boot-directory=tt/boot testgrub
-
sudo umount tt
-
sudo kpartx -d testgrub
- qemu-img convert testgrub testgrub.img -O qcow2
Then you can run it in the qemu using qemu-system-i386 testgrub.img -s -S.
After the qemu boots up, cd into the grub/grub-core directory, and execute gdb -x gdb_grub , the gdb will automatically hooks up something and loads symbol when a module is loaded.