MinimalなLinux

ふと思いたってMinimalな構成のLinuxを作ってみた。

# cd /usr/src/linux
# make allnoconfig

から始めて、
起動に必要なものと、サイズが小さくなりそうな以下のオプションだけをつけた。

# make menuconfig
General setup  --->
  Kernel compression mode (LZMA)
  Initial RAM filesystem and RAM disk (initramfs/initrd) support
  Support initial ramdisks compressed using LZMA
  Optimize for size
  Configure standard kernel features (for small systems)
  Strip assembler-generated symbols during link

Executable file formats / Emulations  --->  
  Kernel support for ELF binaries  

あとは普通にコンパイル

# make -j4

シェルにはbusyboxのallnoconfigを使う。
まずはGentooのemergeで作業領域を残しつつインストールして、

# FEATURES=keepwork emerge -av busybox

作業領域に行ってコンフィグ。

# cd /var/tmp/portage/sys-apps/busybox-*/work/busybox-*
# make allnoconfig
# make menuconfig

static linkを選択。

Busybox Settings  --->
  Build Options  --->
    Build BusyBox as a static binary (no shared libs) 

生成物のサイズについて最適化しつつコンパイル

CFLAGS="-fomit-frame-pointer -Os -pipe" make -j4

生成物を適当なディレクトリに集める。

mkdir /tmp/minimal-linux
cp busybox /tmp/minimal-linux/
cd /tmp/minimal-linux
cp /usr/src/linux/arch/x86_64/boot/bzImage .

initramfsを作って準備完了。

mv busybox sh
echo sh | cpio -o -H newc | lzma -z > initramfs.cpio.lzma
rm sh

サイズを見てみるとこんなかんじ。

# ls -l bzImage initramfs.cpio.lzma
 -rw-r--r-- 1 root root 382576 Sep 16 17:42 bzImage
 -rw-r--r-- 1 root root 268988 Sep 16 17:53 initramfs.cpio.lzma

合計637KiB。今は亡きフロッピーに収まる大きさにできた。

早速動かしてみる。あらかじめ入れておいたkvm

# kvm -kernel bzImage -initrd initramfs -append "init=/sh"

と動かすと、無事起動し、busyboxのashのプロンプトが表示された。
BIOSの部分を除けば、起動には一秒かからないくらい。