aboutsummaryrefslogblamecommitdiffhomepage
path: root/content/2021-12-02-toying-with-virtio/build_initramfs.sh
blob: c30fa5e155322b3fd8f86074d88c96c25668c92c (plain) (tree)

























































































                                                                                   
#!/bin/bash

set -e

BUSYBOX=busybox-1.34.1
INITRAMFS=$PWD/initramfs.cpio.gz

## Build busybox (static).

test -f $BUSYBOX.tar.bz2 || wget -nc https://busybox.net/downloads/$BUSYBOX.tar.bz2
test -d $BUSYBOX || tar xf $BUSYBOX.tar.bz2

cd $BUSYBOX
make defconfig
sed -i 's/[# ]*CONFIG_STATIC[ =].*/CONFIG_STATIC=y/' .config
make -j$(nproc) busybox
make install

## Create initramfs.

cd _install

# 1. Create initramfs folder structure.

mkdir -p bin sbin etc/init.d proc sys usr/bin usr/sbin dev mnt

# 2. Prepare init.

# By default, initramfs executes /init.
# Optionally change with rdinit= kernel parameter.
ln -sfn sbin/init init

cat <<EOF > etc/inittab
# Initialization after boot.
::sysinit:/etc/init.d/rcS

# Shell on console after user presses key.
::askfirst:/bin/cttyhack /bin/sh -l

# Spawn getty on first virtio console.
::respawn:/sbin/getty hvc0 9600 vt100
EOF

cat <<EOF > etc/init.d/rcS
#!/bin/sh

# Mount devtmpfs, which automatically populates /dev with devices nodes.
# So no mknod for our experiments :}
mount -t devtmpfs none /dev

# Mount procfs and sysfs.
mount -t proc none /proc
mount -t sysfs none /sys

# Set hostname.
hostname virtio-box
EOF
chmod +x etc/init.d/rcS

cat <<EOF > etc/profile
export PS1="\[\e[31m\e[1m\]\u@\h\[\e[0m\] \w # "
EOF

# 3. Create minimal passwd db with 'root' user and password '1234'.
#    Mainly used for login on virtual console in this experiments.
echo "root:x:0:0:root:/:/bin/sh" > etc/passwd
echo "root:$(openssl passwd -crypt 1234):0::::::" > etc/shadow

# 4. Create minimal setup for basic networking.

# Virtul DNS from qemu user network.
echo "nameserver 10.0.2.3" > etc/resolv.conf

# Assign static IP address, bring-up interface and define default route.
cat <<EOF >> etc/init.d/rcS
# Assign static IP address to eth0 interface.
ip addr add 10.0.2.15/24 dev eth0

# Bring up eth0 interface.
ip link set dev eth0 up

# Add default route via the host (qemu user networking exposes host at this
# address by default).
ip route add default via 10.0.2.2
EOF

# 5. Created cpio compressed initramfs.
find . -print0                      \
    | cpio --null -ov --format=newc \
    | gzip -9 > $INITRAMFS