Thursday, February 12, 2009

Developing your custom kernel with qemu

I'm preparing a presentation that is hopefully going to be shown at an internal event at Sogeti. We're discussing the internals of Operating Systems. For this presentation, the intention is to compile a pre-created, very simple and basic kernel, which doesn't do much but print "Hello World!".

Well, if you're interested in doing kernel development yourself, there are plenty of resources around to help you get started. The not-so-easy thing is getting your development environment in order, so that you can actually run and debug the kernel. Here's a set of commands that help you do that. I'm using qemu as a VM emulator, gcc and nasm for development and Ubuntu as a host development system.
  1. qemu-img create myos.img 32M
  2. losetup /dev/loop1 ./myos.img
  3. fdisk -u -C65 -S63 -H16 /dev/loop1
  4. ( create a primary bootable partition across the entire disk)
  5. losetup -d /dev/loop1
  6. losetup -o32256 /dev/loop1 ./myos.img
  7. mkfs -t ext3 /dev/loop1
  8. mount -t ext3 /dev/loop1 /mnt/image
  9. df -Th
  10. losetup /dev/loop2 ./myos.img
  11. ln -s /dev/loop2 /dev/loop
  12. cd /mnt/image
  13. mkdir boot
  14. mkdir boot/grub
  15. cd boot/grub
  16. cp /boot/grub/stage1 ./
  17. cp /boot/grub/stage2 ./
  18. cp /boot/grub/e2fs_stage1_5 ./
  19. grub
  20. grub>device (hd0) /dev/loop
  21. grub>root (hd0,0)
  22. grub>setup (hd0)
  23. grub>quit
  24. vi /mnt/image/boot/grub/menu.lst
  25. menu.lst:
    timeout 0
    default 0
    title minimal­kernel
    root (hd0,0)
    kernel (hd0,0)/minimal­kernel
  26. rm /dev/loop
  27. losetup -d /dev/loop0
  28. losetup -d /dev/loop1
  29. mbchk kernel.bin
  30. cp kernel.bin /mnt/image/minimal-kernel
  31. umount /mnt/image
And then run it with:

qemu -m 100 -hda myos.img -boot c -no-kqemu

There you go! Of course, once the image is created and sorted, for development you only need to repeat step 30. You can remount the image in a build script:

mount -o loop,offset=32256 ./myos.img /mnt/image

Here are more resources:

No comments: