UP | HOME

构建 Linux 内核运行项目

Table of Contents

1. 下载内核源代码

配置编译环境

export ARCH=x86
make  x86_64_defconfig

通过如下路径开启 ramdisk 选项

make menuconfig
General setup  --->
       ----> [*] Initial RAM filesystem and RAM disk (initramfs/initrd) support
    Device Drivers  --->
       [*] Block devices  --->
               <*>   RAM block device support
               (65536) Default RAM disk size (kbytes)

编译内核

make

编译成功结果位于 arch/x8664/boot/bzImage

2. 编译 busybox 工具

下载 busybox 源码

开启静态链接编译选项

make menuconfig
Busybox Settings  --->
      Build Options  --->
            [*] Build BusyBox as a static binary (no shared libs)

编译并安装

make && make install

busybox 编译后的一下配置

# mkdir etc dev mnt
# mkdir -p proc sys tmp mnt
# mkdir -p etc/init.d/
# vim etc/fstab
proc  /proc     proc    defaults        0       0
tmpfs /tmp      tmpfs   defaults        0       0
sysfs /sys      sysfs   defaults        0       0
# vim etc/init.d/rcS
echo -e "Welcome to tinyLinux"
/bin/mount -a
echo -e "Remounting the root filesystem"
mount -o remount,rw /
mkdir -p /dev/pts
mount -t devpts devpts /dev/pts
echo /sbin/mdev > /proc/sys/kernel/hotplug
mdev -s
# chmod 755 etc/init.d/rcS
# vim etc/inittab
::sysinit:/etc/init.d/rcS
::respawn:-/bin/sh
::askfirst:-/bin/sh
::ctrlaltdel:/bin/umount -a -r
# chmod 755 etc/inittab
# cd dev
# mknod console c 5 1
# mknod null c 1 3
# mknod tty1 c 4 1

3. 构建根文件系统

构建思路

  1. 先制作一个空的镜像文件;
  2. 然后把此镜像文件格式化为 ext3 格式;
  3. 然后把此镜像文件挂载,并把根文件系统复制到挂载目录;
  4. 卸载该镜像文件。
  5. 打成 gzip 包
#!/bin/bash
rm -rf rootfs.ext3
rm -rf fs
dd if=/dev/zero of=./rootfs.ext3 bs=1M count=32
mkfs.ext3 rootfs.ext3
mkdir fs
mount -o loop rootfs.ext3 ./fs
cp -rf ./_install/* ./fs
umount ./fs
gzip --best -c rootfs.ext3 > rootfs.img.gz

4. qemu 启动

通过 qemu 启动

qemu-system-x86_64 \
  -kernel ./linux-4.9.229/arch/x86_64/boot/bzImage  \
  -initrd ./busybox-1.30.0/rootfs.img.gz   \
  -append "root=/dev/ram init=/linuxrc"  \
  -serial file:output.txt

Last Updated 2023-10-12 Thu 19:33. Created by Jinghui Hu at 2023-10-12 Thu 19:20.