Tiny Trick: Embedded Filesystem in Kernel — Stuffing init Right Into the Kernel Binary!
When your kernel doesn’t yet support reading disks or filesystems, how do you support a simple filesystem in a temporary way? Today’s trick — compile the filesystem directly into the kernel! No disk needed, no driver needed, the kernel executes init on boot, maximally simple!
## Problem: The First Hurdle of a DIY OS — “How does the kernel find init?”
After writing your first custom OS kernel, you’ll always encounter this classic problem:
“My kernel is already running, but how do I load and execute the init process?”
Traditional approaches:
– Read from disk: requires implementing filesystem, block device driver, partition table parsing…
– Too complex: for beginners, this is a “hell-level” task.
Is there a simpler way? Of course!
## Core Idea: Stuff the “Filesystem” Right Into the Kernel Binary!
What is initramfs? In Linux, initramfs (Initial RAM Filesystem) is a root filesystem in memory, compressed and embedded into the kernel image. At boot, the kernel decompresses it into memory, mounts it as root, and executes /sbin/init.
We won’t do a complex initramfs, but a minimal “inline filesystem”: put the init program, config files, etc., directly as binary data compiled into the kernel!
## Implementation: Hardcode File Contents into the Kernel with Assembly or C
The approach:
1. Create a cpio archive of your files
2. Link the cpio blob into the kernel ELF
3. The kernel reads the embedded data at boot
cpio (copy in / copy out) is an archiving tool and format from Unix System III (1981), predating tar. It’s widely used in Linux kernel initramfs, RPM package manager, and other critical components.
This approach lets you bypass the chicken-and-egg problem of needing a filesystem driver to load your init program.
Comments