".
you can start kernel with init=/path/to/myapp parameter defined in your bootloader.
init=/path/to/myapp
Minimal init hello world program step-by-step
Compile a hello world without any dependencies that ends in an infinite loop. main.S:
main.S
.global _start
_start:
mov $1, %rax
mov $1, %rdi
mov $message, %rsi
mov $message_len, %rdx
syscall
jmp .
message: .ascii "hello world\n"
.equ message_len, . - message
We cannot use sys_exit, or else the kernel panics.
sys_exit
Then:
as --64 -o main.o main.S
ld -o init main.o
mkdir d
cd d
find . | cpio -o -H newc | gzip > ../rootfs.cpio.gz
ROOTFS_PATH="$(pwd)/../rootfs.cpio.gz"
This creates a filesystem with our hello world at /init, which is the first userland program that the kernel will run. We could also have added more files to d/ and they would be accessible from the /init program when the kernel runs.
/init
d/
Then cd into the Linux kernel tree, build is as usual, and run it in QEMU:
cd
git clone git://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git
cd linux
git checkout v4.2
make mrproper
make defconfig
make -j5
qemu-system-x86_64 -kernel arch/x86/boot/bzImage -initrd "$ROOTFS_PATH"
And you should see a line:
hello world
on the emulator screen! Note that it is not the last line, so you have to look a bit further up.
Tested on Ubuntu 14.04.
You can also use C programs if you link them statically:
#include <stdio.h>
#include <unistd.h>
int main() {
printf("hello world\n");
sleep(0xFFFFFFFF);
return 0;
}
with:
gcc -static main.c -o init
You can run on real hardware with a USB on /dev/sdX and:
/dev/sdX
make isoimage FDINITRD="$ROOTFS_PATH"
sudo dd if=arch/x86/boot/image.iso of=/dev/sdX
Great source on this subject:
Landley also explains how to use gen_initramfs_list.sh, which is a script from the Linux kernel source tree to help automate the process.
gen_initramfs_list.sh
Next step: setup BusyBox so you can interact with the system:
By posting your answer, you agree to the privacy policy and terms of service.
asked
4 years ago
viewed
1781 times
active
3 months ago