Create a os kernel using limine
- User
Create a os kernel using limine
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Create a os kernel using limine
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Okay, let's create a very basic "Hello, World" OS kernel for the x86_64 architecture using the Limine bootloader. This will involve:
Prerequisites:
x86_64-elf-gccx86_64-elf-ldx86_64-elf-asgcc-x86-64-elf, binutils-x86-64-elf on Debian/Ubuntu, or built manually using tools like crosstool-ng).make, curl, tar.xorriso: To create the ISO image (sudo apt install xorriso or similar).qemu: To run the kernel (sudo apt install qemu-system-x86 or similar).Step 1: Project Structure
Create a directory for your project, e.g., myos. Inside it, create the following structure:
myos/
├── src/
│ └── kernel.c
├── limine.cfg
├── linker.ld
└── Makefile
Step 2: Get Limine Header (limine.h)
Limine provides a header file (limine.h) that defines the structures and macros needed to interact with the bootloader. We can fetch it directly. Add this step to the Makefile later, but for now, understand you'll need it. You can download it from the Limine GitHub repository or let the Makefile handle it.
Step 3: Kernel Code (src/kernel.c)
This is our minimal kernel. It will request a terminal from Limine and print "Hello, Kernel!" to it.
// src/kernel.c
#include <stddef.h> // For size_t, NULL
#include <stdint.h> // For standard integer types
// --- Limine Bootloader Header ---
// Normally you'd download this. The Makefile will handle it.
// We include a placeholder definition here just for clarity
// if limine.h isn't immediately available.
#ifndef LIMINE_H
#define LIMINE_H
// Placeholder structure - the real one is much more complex
typedef struct { uint64_t revision; } limine_terminal_request;
#endif
// Ensure you actually have the real limine.h file when compiling!
#include <limine.h>
// --- Limine Requests ---
// Request a terminal output feature from Limine.
// We VOLATILE this variable to prevent the compiler from optimizing it away,
// and mark it as USED so the linker doesn't discard it.
static volatile struct limine_terminal_request terminal_request = {
.id = LIMINE_TERMINAL_REQUEST, // Standard ID for terminal request
.revision = 0 // Request the latest revision
};
// Helper function to print to the terminal provided by Limine
static void kprint(const char *str) {
// Ensure the terminal request was successful
if (terminal_request.response == NULL || terminal_request.response->terminal_count < 1) {
// No terminal available, can't print. Halt.
for (;;) { asm volatile ("hlt"); }
}
// Get the first terminal provided
struct limine_terminal *terminal = terminal_request.response->terminals[0];
// Use the write function provided by Limine
// The revision check ensures the `write` function pointer exists.
// Note: The real limine.h guarantees .write exists if revision is supported.
terminal_request.response->write(terminal, str, strlen(str));
}
// A simple strlen implementation (we don't have libc)
size_t strlen(const char *str) {
size_t len = 0;
while (str[len]) {
len++;
}
return len;
}
// --- Kernel Entry Point ---
// This function is called by Limine after it sets up the environment.
void _start(void) {
// Ensure we got a response to the terminal request.
if (terminal_request.response == NULL) {
// Critical error: No terminal response. Halt.
goto hang;
}
// Ensure we have at least one terminal.
if (terminal_request.response->terminal_count < 1) {
// Critical error: No terminals available. Halt.
goto hang;
}
// Print our welcome message!
kprint("Hello, Kernel using Limine!\n");
kprint("We have a terminal.\n");
hang:
// Halt the CPU indefinitely.
for (;;) {
asm volatile ("hlt");
}
}
Explanation:
stddef.h for NULL/size_t. We need limine.h.static volatile struct limine_terminal_request.
static: Keeps it local to this file.volatile: Prevents the compiler from optimizing access to it away, as its value (response field) is set externally by Limine..id and .revision. Limine finds these request structures by scanning the kernel binary for the specific id pattern.kprint Function: A simple function to write strings using the function pointer provided in the Limine terminal response. It checks if a terminal is actually available.strlen Function: A basic implementation since we don't link against a standard C library._start Function: This is the kernel's entry point (specified in the linker script).
terminal_request.response is valid.kprint.hlt (Halt instruction) to stop the CPU, as there's nothing more to do.Step 4: Linker Script (linker.ld)
This tells the linker how to arrange the kernel code and data in the final executable file. Limine generally loads kernels to the higher half of the virtual address space (0xffffffff80000000 onwards) but can also load them lower. For simplicity, we'll link it to load at 0x100000 (1 MiB physical and virtual address).
/* linker.ld */
ENTRY(_start) /* Set the entry point */
OUTPUT_FORMAT(elf64-x86-64) /* Set the output format */
/* Define the kernel base address (physical and virtual for this simple case) */
KERNEL_BASE = 0x100000;
SECTIONS {
/* Start positioning sections at the KERNEL_BASE */
. = KERNEL_BASE;
/* Text section: code and read-only data */
.text : ALIGN(0x1000) {
*(.text .text.*) /* All code */
*(.rodata .rodata.*) /* All read-only data */
}
/* Limine requests must be discoverable */
/* Place them after code but before writable data */
.limine_reqs : ALIGN(8) {
KEEP(*(.limine_reqs)) /* Keep all symbols in .limine_reqs sections */
}
/* Data section: initialized writable data */
.data : ALIGN(0x1000) {
*(.data .data.*) /* All initialized data */
}
/* BSS section: uninitialized writable data */
.bss : ALIGN(0x1000) {
*(COMMON) /* Common symbols */
*(.bss .bss.*) /* All BSS sections */
}
/* Discard standard sections we don't need/want */
/DISCARD/ : {
*(.comment)
*(.eh_frame)
*(.note.gnu.build-id)
}
}
Explanation:
ENTRY(_start): Specifies _start (our C function) as the entry point.OUTPUT_FORMAT(elf64-x86-64): Sets the output file type.KERNEL_BASE = 0x100000;: Defines the address where the kernel expects to be loaded.. = KERNEL_BASE;: Sets the location counter..text Section: Contains executable code (.text.*) and read-only data (.rodata.*). Aligned to a 4K page boundary (0x1000)..limine_reqs Section: This is CRUCIAL. The limine.h header places request structures (like terminal_request) into a section named .limine_reqs. We use KEEP(*(.limine_reqs)) to ensure the linker doesn't discard this section, as Limine needs to find it. It's placed after code but before data, aligned to 8 bytes..data Section: Contains initialized global/static variables..bss Section: Contains uninitialized global/static variables. The OS loader (or in our case, Limine doesn't necessarily zero this by default, but good practice separates it)./DISCARD/: Throws away sections we don't need.Step 5: Limine Configuration (limine.cfg)
This file tells Limine how to boot our kernel. It needs to be present on the boot media (our ISO).
# limine.cfg
# Set a timeout (in seconds) for the boot menu. 5 seconds.
TIMEOUT=5
# Default entry. You can have multiple entries.
:MyOS
# We use the Limine protocol.
PROTOCOL=limine
# Path to the kernel binary on the boot media.
# 'boot:///' indicates the root of the boot drive.
KERNEL_PATH=boot:///kernel.elf
# Optional: Set kernel command line arguments (we don't use them yet)
# KERNEL_CMDLINE=foo=bar
Explanation:
TIMEOUT=5: Waits 5 seconds at the Limine menu before booting the default entry.:MyOS: Defines a boot menu entry named "MyOS".PROTOCOL=limine: Specifies that the kernel uses the Limine protocol.KERNEL_PATH=boot:///kernel.elf: Tells Limine where our kernel executable is located within the ISO's file system.Step 6: Makefile
This automates the build process: fetching Limine, compiling, linking, and creating the bootable ISO.
Explanation:
-ffreestanding, -nostdlib, -mno-red-zone, etc., are crucial for kernel development). -mcmodel=kernel is often needed for higher-half kernels, but good practice anyway. -I./limine tells GCC where to find limine.h.limine target uses curl to download the specified Limine release tarball and tar to extract only the necessary files (limine.sys, limine-cd.bin, limine-cd-efi.bin for booting, limine-deploy utility, and limine.h).%.o: %.c rule compiles .c files into .o object files. It depends on limine/limine.h.$(KERNEL_ELF): $(OBJ) rule links the object files using the linker script (-T linker.ld).$(ISO_FILE): ... rule:
iso_root directory.kernel.elf), limine.cfg, and limine.sys into it.xorriso with specific flags to create an ISO that is bootable on both BIOS (-b limine-cd.bin) and UEFI (--efi-boot limine-cd-efi.bin).limine-deploy (downloaded earlier) to install the Limine bootloader onto the ISO image, making it bootable.run Target: Executes the created ISO using qemu-system-x86_64. -serial stdio redirects serial output to the console, which can be useful for debugging later. -no-reboot -no-shutdown makes QEMU exit when the guest OS halts/triple faults.clean Target: Removes generated files..PHONY: Declares targets that don't represent actual files.Step 7: Build and Run
Open your terminal in the myos directory.
Run make:
make
This will:
limine/ subdirectory.src/kernel.c into src/kernel.o.src/kernel.o into kernel.elf using linker.ld.myos.iso.Run make run:
make run
QEMU should start, you'll briefly see the Limine boot menu, and then it will boot your kernel. You should see the following output in the QEMU window:
Hello, Kernel using Limine!
We have a terminal.
The QEMU window will then likely just show a blinking cursor or be static, as the CPU is halted in the hlt loop. You can close the QEMU window.
Clean up (optional):
make clean
You have now successfully created and booted a minimal x86_64 kernel using the Limine bootloader! This is the very first step. From here, you would typically explore:
kmalloc/kfree.# Makefile
# --- Configuration ---
ARCH := x86_64
TARGET := $(ARCH)-elf
LIMINE_VERSION := v5.20240704.0 # Use a recent stable version
# Tools (use your cross-compiler prefix)
PREFIX := $(TARGET)-
CC := $(PREFIX)gcc
LD := $(PREFIX)ld
AS := $(PREFIX)as
# Source files
C_SOURCES := $(wildcard src/*.c)
OBJ := ${C_SOURCES:.c=.o}
KERNEL_ELF := kernel.elf
ISO_FILE := myos.iso
# Build flags
CFLAGS := -Wall -Wextra -pedantic -std=c11 \
-ffreestanding -fno-stack-protector -fno-pie \
-mno-red-zone -mgeneral-regs-only \
-mcmodel=kernel \
-I./limine `# Include directory for limine.h` \
-g # Include debug symbols
LDFLAGS := -T linker.ld -nostdlib -static -z max-page-size=0x1000
# Limine tools and files needed for ISO creation
LIMINE_DEPLOY := ./limine/limine-deploy
LIMINE_SYS := ./limine/limine.sys
LIMINE_CD_BIN := ./limine/limine-cd.bin
LIMINE_CD_EFI_BIN := ./limine/limine-cd-efi.bin
LIMINE_TARBALL := limine-$(LIMINE_VERSION).tar.gz
LIMINE_URL := https://github.com/limine-bootloader/limine/releases/download/$(LIMINE_VERSION)/limine-$(LIMINE_VERSION).tar.gz
# --- Build Targets ---
.PHONY: all clean run limine iso
all: $(ISO_FILE)
# Rule to create the final ISO image
$(ISO_FILE): $(KERNEL_ELF) limine.cfg limine
@echo "Creating ISO image..."
@rm -rf iso_root
@mkdir -p iso_root/boot
@cp $(KERNEL_ELF) iso_root/boot/
@cp limine.cfg $(LIMINE_SYS) iso_root/
# Use xorriso to create a BIOS/EFI bootable ISO
@xorriso -as mkisofs -b limine-cd.bin \
-no-emul-boot -boot-load-size 4 -boot-info-table \
--efi-boot limine-cd-efi.bin \
-efi-boot-part --efi-boot-image \
-input-charset utf-8 \
-o $(ISO_FILE) iso_root/
# Deploy limine onto the ISO (makes it bootable)
@$(LIMINE_DEPLOY) $(ISO_FILE)
@rm -rf iso_root
@echo "ISO '$@' created successfully."
# Rule to link the kernel ELF file
$(KERNEL_ELF): $(OBJ) linker.ld
@echo "Linking kernel..."
@$(LD) $(LDFLAGS) -o $@ $(OBJ)
# Rule to compile C source files to object files
%.o: %.c limine/limine.h
@echo "Compiling $<..."
@mkdir -p $(@D) # Ensure output directory exists (e.g., src/ -> src/)
@$(CC) $(CFLAGS) -c $< -o $@
# Target to download and extract Limine (if not already present)
limine: $(LIMINE_TARBALL)
@echo "Extracting Limine..."
@tar -xzf $(LIMINE_TARBALL) --strip-components=1 -C ./limine limine-$(LIMINE_VERSION)/limine.sys \
limine-$(LIMINE_VERSION)/limine-cd.bin limine-$(LIMINE_VERSION)/limine-cd-efi.bin \
limine-$(LIMINE_VERSION)/limine-deploy limine-$(LIMINE_VERSION)/limine.h
@touch limine # Update timestamp
$(LIMINE_TARBALL):
@echo "Downloading Limine $(LIMINE_VERSION)..."
@mkdir -p ./limine
@curl -L -o $@ $(LIMINE_URL)
# Rule to run the kernel in QEMU
run: $(ISO_FILE)
@qemu-system-$(ARCH) -cdrom $(ISO_FILE) -m 128M -serial stdio -no-reboot -no-shutdown
# Rule to clean up build artifacts
clean:
@echo "Cleaning up..."
@rm -rf $(KERNEL_ELF) $(OBJ) $(ISO_FILE) iso_root limine $(LIMINE_TARBALL) src/*.o
# Include limine/limine.h as a prerequisite for C files if it exists
# This ensures recompilation if the header changes (e.g., after download)
ifneq ($(wildcard limine/limine.h),)
$(OBJ): limine/limine.h
endif