Thursday, January 10, 2019

Using QEMU to run Linux kernel

We can use qemu to run linux kernel. I ll describe two cases one for arm and other for x86

If you want to use the latest qemu, clone and compile as follows,

To clone and compile qemu for arm64:

$ git clone git://git.qemu.org/qemu.git
$ cd qemu
$ sudo apt-get install libpixman-1-dev
$ ./configure --target-list=aarch64-softmmu
$ make -j4


Second step is to get a initrd. You can create one using the below steps,

## Build Busybox

To make Linux useful, it needs a shell. These following instructions will
construct a file system for the Linux RAM disk with the BusyBox shell as the
init process.


Install prerequisites:

$ sudo apt install make binutils-aarch64-linux-gnu


$ git clone git://busybox.net/busybox.git
$ cd busybox
$ ARCH=arm64 CROSS_COMPILE=aarch64-linux-gnu- make defconfig
$ ARCH=arm64 CROSS_COMPILE=aarch64-linux-gnu- make menuconfig

At this point you should ensure that the option `Settings > Build static binary
(no shared libs)` is selected. Then you can proceed with the following commands:

ARCH=arm64 CROSS_COMPILE=aarch64-linux-gnu- make -j24
ARCH=arm64 CROSS_COMPILE=aarch64-linux-gnu- make install
cd _install
mkdir proc
mkdir sys
mkdir -p etc/init.d
cat < etc/init.d/rcS
#!bin/sh
mount -t proc none /proc
mount -t sysfs none /sys
EOF
chmod u+x etc/init.d/rcS
grep -v tty ../examples/inittab > ./etc/inittab


## Create a RAM disk for Linux

find . | cpio -o -H newc | gzip > ../initrd.img

To run qemu for arm64:

qemu/aarch64-softmmu/qemu-system-aarch64 -M virt -m 1G -cpu cortex-a57 -nographic -kernel arch/arm64/boot/Image -initrd initrd.img -append "rdinit=/sbin/init

To run qemu for x86_64:
qemu-system-x86_64 -m 1G -nographic -kernel arch/x86/boot/bzImage -initrd initrd.img -append "console=ttyS0 rdinit=/sbin/init"