BusyBox:从空白系统开始
原片 01:05:16—01:10:58
接着实际看 Linux。我准备了两份都叫 init 的脚本,名字容易混淆,但内容不同。先看 initramfs 阶段:这里只有 BusyBox,可以加一个 shell。这个例子打包的初始文件系统中有 /init。
还有 /bin/busybox 和一些驱动。今天发现 QEMU 必须有这些驱动才能正确运行,就一起打包进 initramfs,此外没有别的内容。Linux 加载后,会解开 initramfs,将它作为文件系统,再执行里面的 init。

init 的开头:
#!/bin/busybox sh
# At this point, we only have:
# /bin/busybox - the binary
# /dev/console - the console device
BB=/bin/busybox
# Delete this file
# (Yes, we can do this on UNIX! The file is "removed"
# after the last reference, the fd, is gone.)
$BB rm /init
$BB sh

init 的解释器是 /bin/busybox sh,用 shell 解释脚本。它先删掉 /init,再启动一个 shell。编译、运行后,这次会出现图形界面。我用树莓派做全系统模拟,速度稍慢。

x86-64 的 QEMU 可能需要几秒才能启动。随后 Linux 正常运行,加载 initramfs,刚才的脚本也开始执行。

脚本启动后,用 find / 看,系统里只有 /bin/busybox、后续操作必需的一批驱动,以及 /dev/console。还有 /root,是 shell 创建的,最初并没有。

/bin/ls、/bin/sh 等二进制文件都不存在,只有 /bin/busybox。脚本尚未结束,现在运行到 13 行,停在 shell。退出后,会先打印一条 message,再执行一段脚本:for cmd in busybox --list。可以看一下 /bin/busybox --list,它列出 BusyBox 支持的全部命令。这么多功能都集成在一个二进制文件中。脚本会为它们创建符号链接。
例如 command 是 ls,就执行 BusyBox 的 ln,让 /bin/ls 链接到 BusyBox。三行脚本就能在 /bin 下创建一大批命令文件。

创建命令入口并挂载 procfs、sysfs:
for cmd in $($BB --list); do
$BB ln -s $BB /bin/$cmd
done
mkdir -p /proc && mount -t proc none /proc
mkdir -p /sys && mount -t sysfs none /sys
接着用 mkdir、mount 创建操作系统对象,包括 procfs 和 /sys;用 insmod 安装一批驱动;用 mknod 创建设备。最后打印 init-ok。
还有 Launch a shell、initramfs、busybox sh。现在退出当前 shell,脚本就继续完成剩余操作,打印这些日志。可以看到 insmod 成功,以及红色的 init-ok、Launch a shell、initramfs。


这时 procfs 已有内容,可以运行 ps。ls /bin 会列出现在的功能:每个文件都是指向 /bin/busybox 的符号链接,包括 word count,还有处理互联网功能的 wget。



系统已经有些可用了。有 pstree 吗?没有,只有 ps。ps 显示一号进程是 init,即 busybox sh /init,是 initramfs 阶段最早由操作系统加载的二进制文件,也是所有进程的祖先。还有一些操作系统自己的线程。

除此以外,就只有当前 busybox sh 和刚才运行的 ps。
