Kernel调试基础--制作initramfs

通过自己制作initramfs可以使用qemu启动自定义的内核, 可以用于调试或测试。这里记录一下制作简单的initramfs的脚本, 方便后续使用。

本文参考了链接:Building a minimal Linux / Busybox OS for Qemu

完整脚本如下:

 1#!/bin/bash
 2set -e
 3
 4CWD=`pwd`
 5BUSYBOX_FILE=busybox-1.28.1
 6BUSYBOX_SRC=/tmp/busybox
 7BUSYBOX_BUILD=/tmp/busybox-build
 8INITRAMFS_DIR=/tmp/initramfs
 9
10mkdir -p $BUSYBOX_SRC $BUSYBOX_BUILD $INITRAMFS_DIR
11if [ ! -e $BUSYBOX_FILE ]; then
12        wget http://busybox.net/downloads/${BUSYBOX_FILE}.tar.bz2
13fi
14tar -C $BUSYBOX_SRC -xvf ${BUSYBOX_FILE}.tar.bz2
15
16cd ${BUSYBOX_SRC}/${BUSYBOX_FILE} && make O=${BUSYBOX_BUILD} defconfig
17# enable busybox static build
18cd ${BUSYBOX_BUILD} && sed -i "s/# CONFIG_STATIC is not set/CONFIG_STATIC=y/" .config \
19        && make && make install
20
21cd $INITRAMFS_DIR && rm -rfv * && mkdir -p bin sbin etc proc sys usr/bin usr/sbin \
22        && cp -a $BUSYBOX_BUILD/_install/* .
23
24# if you want to add iozone binary and its linked .so, you can add command here:
25# cp iozone $INITRAMFS_DIR/bin
26
27cat > $INITRAMFS_DIR/init << 'EOF'
28#!/bin/sh
29
30mount -t proc none /proc
31mount -t sysfs none /sys
32
33cat <<!
34
35
36Boot took $(cut -d' ' -f1 /proc/uptime) seconds
37
38        _       _     __ _                  
39  /\/\ (_)_ __ (_)   / /(_)_ __  _   ___  __
40 /    \| | '_ \| |  / / | | '_ \| | | \ \/ /
41/ /\/\ \ | | | | | / /__| | | | | |_| |>  < 
42\/    \/_|_| |_|_| \____/_|_| |_|\__,_/_/\_\ 
43
44
45Welcome to mini_linux
46
47
48!
49exec /bin/sh
50EOF
51
52chmod +x init
53
54# package into a initramfs
55rm -fv /tmp/initramfs.cpio.gz || true
56find . -print0 | cpio --null -ov --format=newc \
57  | gzip -9 > /tmp/initramfs.cpio.gz
58
59echo "===========> initramfs is saved as /tmp/initramfs.cpio.gz"
60
61cd ${CWD}
62# boot with qemu
63# sudo qemu-system-x86_64 -enable-kvm -kernel build/kernel -initrd initramfs.cpio.gz -nographic -append "console=ttyS0"