如何構(gòu)建用戶態(tài) Linux
“用戶態(tài) Linux” 是什么?它是一種可以在用戶態(tài)運(yùn)行的 Linux 內(nèi)核。(用戶態(tài)是什么,這里就不解釋了)
它有什么用?它用于內(nèi)核隔離、替代 QEMU/Bochs 來調(diào)試 Linux 內(nèi)核,也可以在低性能設(shè)備上代替 KVM 進(jìn)行虛擬化。
但它也存在一些缺陷,比如不支持 ARM 架構(gòu)以及多核系統(tǒng)。
編譯 Linux 內(nèi)核
首先通過 git 下載 Linux 內(nèi)核源代碼:
git clone --depth 1 https://mirrors.tuna.tsinghua.edu.cn/git/linux.git
(這里使用了清華大學(xué)的鏡像站,kernel.org 也是可以的。)
然后采用如下步驟編譯它:
$ cd linux
$ export ARCH=um # 非常重要 設(shè)置架構(gòu)為用戶態(tài)
$ make defcongig
$ make -j8
LD .tmp_vmlinux.kallsyms1
KSYMS .tmp_vmlinux.kallsyms1.S
AS .tmp_vmlinux.kallsyms1.S
LD .tmp_vmlinux.kallsyms2
KSYMS .tmp_vmlinux.kallsyms2.S
AS .tmp_vmlinux.kallsyms2.S
LD vmlinux
SYSMAP System.map
LINK linux
MODPOST modules-only.symvers
GEN Module.symvers
經(jīng)過漫長(zhǎng)的編譯之后,你獲得了一個(gè) vmlinux 文件。它和正常的 Linux 內(nèi)核的區(qū)別是,這個(gè) vmlinux 可以在用戶態(tài)運(yùn)行。
準(zhǔn)備根文件系統(tǒng)
先別著急啟動(dòng),先來準(zhǔn)備內(nèi)核所使用的根文件系統(tǒng)。
以下內(nèi)容以 Debian Linux 為例。
首先安裝 debootstrap 軟件包:
sudo apt install debootstrap
以下命令皆需要 root 權(quán)限,先切換到 root 用戶:
$ sudo su
然后構(gòu)建根文件系統(tǒng),存放在 rootfs 文件中:
# dd if=/dev/zero of=rootfs seek=2G # 創(chuàng)建一個(gè) 2GB 大小的空 rootfs 文件
2000000000字節(jié)(2 GB,2 GB)已復(fù)制,0.137825 s,570 MB/s`
# mkfs.ext4 rootfs # 將其格式化為 ext4 格式
mke2fs 1.46.5 (30-Dec-2021)
Discarding device blocks: done
Creating filesystem with 76748 1k blocks and 19200 inodes
Filesystem UUID: 9dc7f1f6-8b16-4c64-9e22-94ede327c532
Superblock backups stored on blocks:
8193, 24577, 40961, 57345, 73729
Allocating group tables: done
Writing inode tables: done
Creating journal (4096 blocks): done
Writing superblocks and filesystem accounting information: done
然后掛載 rootfs 到 /mnt 下:
# mount rootfs /mnt
在其中創(chuàng)建 Debian Linux 的根文件系統(tǒng)(/):
# cd /mnt
# debootstrap sid ./ https://mirrors.tuna.tsinghua.edu.cn/debian
I: Configuring python-central
I: Configuring ubuntu-minimal
I: Configuring libc-bin
I: Configuring initramfs-tools
I: Base system installed successfully.
通過 chroot 將其改變?yōu)楦夸洠?/p>
# chroot ./
設(shè)置 root 密碼:
# passwd
New password:
Retype new password:
然后退出 chroot 環(huán)境,并卸載:
# exit # 退出 chroot 環(huán)境
# cd ..
# umount /mnt
# exit # 退出 sudo 環(huán)境
設(shè)置 rootfs 的所有權(quán)為普通用戶:
$ sudo chown `whoami` rootfs
這樣,這個(gè)用戶態(tài) Linux 的根文件系統(tǒng)就準(zhǔn)備好了。
測(cè)試用戶態(tài) Linux
然后就可以用這個(gè)內(nèi)核啟動(dòng)了,只需要一行命令:
$ screen ./vmlinux mem=1G root=/dev/root rootfstype=hostfs hostfs=./rootfs
con=null con0=null,fd:2 con1=fd:0,fd:1
啟動(dòng)后,使用你前面設(shè)置的 root 用戶/密碼登錄,便可以進(jìn)入到用戶態(tài) Linux 容器中了。
有別于 Docker,這個(gè)容器的內(nèi)核和宿主的內(nèi)核是隔離的,可以使用這個(gè)容器作為一個(gè)調(diào)試內(nèi)核的工具,如:
echo 1 > /proc/sys/kernel/sysrq
echo c > /proc/sysrq-trigger
即可手動(dòng)觸發(fā)一個(gè)“內(nèi)核恐慌Kernel Panic”錯(cuò)誤。
作者簡(jiǎn)介:calvinlin:一個(gè)普通的深圳初中生。