Foreword

So, you fancy yourself to be an OS dev — Welcome to the Morgan temple.

First thing you should do is read this long list of warnings and get demotivated os dev welcome page.

You are a Persistent one if you are still continuing after reading that page. But that is what we need persistence, there are lots of warning in that page but let that not crush you as the only real requirement is persistence. So be prepared for your amazing OS wizard journey.

Every persistent journey needs a reason to exist. Mine is "To impress someone". What is yours ? Comment below.

Now let us pray for her majesty blessing and start our journey.

Image of morgan le fay from fgo lb6

This is not a polished tutorial series, I am learning OS dev as I am writing this blog. Since, making an OS is such lengthy task waiting for OS to finish before writing blog will do no good. Refer to the wiki as needed, treat wiki as an authorative source and please inform me of such contradictions.

_start

This OS series is being written in zig version 0.17.0. Since zig changes their API pretty fast, I will recommend you to follow the series using that compiler itself.

We will be writing a 64-bit kernel, using limine bootloader. We will not be writing our own bootloader. We will be developing this kernel on a Linux machine.

Before we get into writing our own kernel, there are few concepts that needs introduction.

Target Triplet: This refers to a three-part string which is used by compilers to identify the exact platform for which code is being built for.

ELF: Shorthand for Executable and Linkable format. This is the binary file format produced by compilers on UNIX-like OS.

Now we will see the code to write, I will try explain each part of code.

kernel/main.zig

Starting with main.zig.

Line: 1-11

const c = @import("c"); export var limine_base_revision: [3]u64 align(8) linksection(".limine_requests") = .{ 0xf9562b2d5c95a6c8, 0x6a7b384944536bdc, 6, }; export var framebuffer_request: c.limine_framebuffer_request linksection(".limine_requests") = .{ .id = .{ 0xc7b1dd30df4c8b88, 0x0a82e883a194f07b, 0x9d5827dcd881dd75, 0xa3148604f6fab11b }, .revision = 0, .response = null, }; 

The module c contains the limine protocol header file. We are setting the base revision to 6, first two numbers of the tuple represent magic number limine uses to identify the revision number.

Secondly we request the framebuffer from limine which limine has initialized for us already. The id is a tuple of magic numbers limine uses to identify the request. Revision number here is called "Request revision" this is different from base revision as it specifies which version of framebuffer we are asking for. Response is something limine will return which we are initializing to null for now.

Line: 13-15

export var limine_requests_start_marker: [4]u64 align(8) linksection(".limine_requests_start") = .{ 0xf6b8f4b39de7d1ae, 0xfab91a6940fcb9cf, 0x785c6ed015d3e316, 0x181e920a7852b9d9 }; export var limine_requests_start_end: [2]u64 align(8) linksection(".limine_requests_end") = .{ 0xadc0e0531bb10d03, 0x9572709f31764c62 }; 

These are 8-byte aligned markers which sets the boundaries for limine requests, request section should be between these start and end sections. I will later show you how to do that.
As you likely already guessed the tuple is filled with magic numbers.

Line: 17-28

fn fb_channel(value: u8, mask_size: u8, mask_shift: u8) u32 { const size: u6 = @intCast(mask_size); const shift: u6 = @intCast(mask_shift); const max = (@as(u64, 1) << size) - 1; const v: u64 = @intCast(value); const scaled = ((v * max) / 255); return @intCast(scaled << shift); } fn fb_pixel(fb: *c.limine_framebuffer, red: u8, green: u8, blue: u8) u32 { return fb_channel(red, fb.red_mask_size, fb.red_mask_shift) | fb_channel(green, fb.green_mask_size, fb.green_mask_shift) | fb_channel(blue, fb.blue_mask_size, fb.blue_mask_shift); } 

Our function fb_channel is a hardware agnostic channel packer, what it does is take a value(range: 0-255) and put it in the specified channel scaled to the format hardware understand.

fb_pixel just ORs all the channel to get the packed pixel format.

Line: 30-46

fn fb_pattern(fb: *c.limine_framebuffer) void { const address = fb.address orelse unreachable; const fb_ptr: [*]volatile u32 = @ptrCast(@alignCast(address)); for (0..fb.height) |y| { for (0..fb.width) |x| { const nX: u8 = @intCast(x * 255 / fb.width); const nY: u8 = @intCast(y * 255 / fb.height); fb_ptr[y * (fb.pitch / 4) + x] = fb_pixel(fb, 0, nY, nX); } } } fn hcf() noreturn { while (true) { asm volatile ("hlt"); } } 

Here in fb_pattern we first get the address of the memory location representing our framebuffer. If not found we raise unreachable as this should not happen normally.

We then convert the address into a pointer to 32-bit integers after aligning it to u32. It's volatile so that memory access actually happen.

We then iterate over row and column, scale the x and y to be between 0-255(8 bit) and then divide the pitch(number of bytes in row) with byte size of a pixel(4) to get the number of pixels in a row. Some math formula have us treat the matrix as 1d array and put a gradient of green and blue.

You can play around by making different gradient here.

hcf is an infinte loop with htl instruction which stops the program from further execution.

Line: 48-75

export fn kmain() callconv(.c) noreturn { const base_rev = @as(*const volatile u64, &limine_base_revision[2]).*; if (base_rev != 0) { hcf(); } const response = @as(*const volatile @TypeOf(framebuffer_request.response), &framebuffer_request.response).*; if (response == null) { hcf(); } const fb_response = response.*; if (fb_response.framebuffer_count == 0) { hcf(); } for (0..fb_response.framebuffer_count) |i| { const framebuffer: *c.limine_framebuffer = fb_response.framebuffers[i]; if ((framebuffer.memory_model != 1) or (framebuffer.bpp != 32)) { hcf(); } fb_pattern(framebuffer); } hcf(); } 

Here comes our kmain, we make it globally visible during link time, calling convention will be of c style (using callconv). The function will not be returning anything hence noreturn.

If limine supports the requested revsion base it overwrites it with 0. We confirm it's 0(otherwise hang).

We get the response of our framebuffer request, check it's not null, dereferences it confirm there is a monitor attached. Iterate over the number of display we have, get the address of the display framebuffer, confirm that it's LIMINE_FRAMBUFFER_RGB by checking if the memory_model is 1 and then confirming that framebuffer is 4byte(32bit) per pixel(bpp).

If everything is good and all we run our draw function and draw our gradient.

kernel/linker.ld

This is the source code which will specify the format of the binary which will be produced. I will go through this quicly, as you really can't learn much until I go deep into internals of elf which I will do for a separate post. If you can find that post read that first, will help you much here.

Line: 1-11

OUTPUT_FORMAT(elf64-x86-64) ENTRY(kmain) PHDRS { limine_requests PT_LOAD; text PT_LOAD; rodata PT_LOAD; data PT_LOAD; } 

We specify that we need an elf output for x86-64 arch. Set the initial entry point to be kmain. Set the program header layout.

Zig language hardcodes the entry point of a program so the line "ENTRY(kmain)" does not do anything by itself, we are writing this for completeness shake so the script stays same incase you are following this in C or C++.

Line: 13-53

SECTIONS { . = 0xffffffff80000000; .limine_requests : { KEEP(*(.limine_requests_start)) KEEP(*(.limine_requests)) KEEP(*(.limine_requests_end)) } :limine_requests . = ALIGN(CONSTANT(MAXPAGESIZE)); .text : { *(.text .text.*) } :text . = ALIGN(CONSTANT(MAXPAGESIZE)); .rodata : { *(.rodata .rodata.*) } :rodata .note.gnu.build-id : { *(.note.gnu.build-id) } :rodata . = ALIGN(CONSTANT(MAXPAGESIZE)); .data : { *(.data .data.*) } :data .bss : { *(.bss .bss.*) *(COMMON) } :data /DISCARD/ : { *(.eh_frame*) *(.note .note.*) } } 

First we jump to the higher half of the kernel, we do this because lower half is generally reserved for user space program and compilers spit out those address for the programs.

Then we first put the .limine_requests section. You can see how in the section all the requests are gathered up, this is done like this *(), since these sections are referenced by an external program(limine bootloader) we put then in KEEP() so it's not garbage collected.(unreferenced sections can be deleted during dead code elimination cycle). :limine_requests link it to the header of name limine_requests

Then we put an buffer of page size (4096 bytes for x86-64) between the sections. This is done because CPU enforces the RWX permission at page level rather than byte level so this keeps from permission mixup.

Then we put the .text section which contains all the instructions to be executed, .rodata for constants, .note for compiler to put unique hashes to identify that particular build, .data for all the global mutable values as well as static vars which are non-zero initialized and .bss stores all the zero initialized variables./DISCARD/ directive makes it so linker drops those sections.

build.zig

So this one is slightly tricky as I am still searching for some answers but let me show you.

Line: 1-20

const std = @import("std"); pub fn build(b: *std.Build) void { const optimize = b.standardOptimizeOption(.{}); const target = b.resolveTargetQuery(.{ .cpu_arch = .x86_64, .os_tag = .freestanding, .abi = .none, .cpu_features_add = std.Target.x86.featureSet(&.{ .sse, .sse2, }), .cpu_features_sub = std.Target.x86.featureSet(&.{ .avx, .avx2, }), }); 

First three line are standard thing, now remember the Triple Target we had talked about ? We specify those here.
Our target architecture is x86-64, there is no OS for us as we are writing it right now, haha, so it's freestanding and at last the ABI which we right now have none.(For example UNIX like system follows system V abi).

Now here comes some problem, you see it's advised to remove all the SIMD and hardware floating number feature in initialized phase of kernel development but here is the zig quirk. You have to have sse and sse2 enabled as disabling breaks the ABI with compiler_rt, similarly you can't enable .soft_float as that too breaks the ABI with compiler_rt, so uh yea it's language fault or maybe I haven't found the correct way yet.

Now it would have been a massive headache if we were on GRUB bootloader as executing SSE instructions before we make our kernel ready for it triggers invalid opcode and crashes our kernel. Thankfully limine enables SSE for us.

We for now disable what SIMD features we can, which being avx and avx2.

Yes this is a hack, I am aware of it. We will have cpu support this thing as soon as possible. Please don't execute me.

Line: 22-27

 const translate = b.addTranslateC(.{ .root_source_file = b.path("kernel/limine/limine.h"), .target = target, .optimize = optimize, .link_libc = false, }); 

zig 0.17.0 has removed the cImport so this is how you link to C headers. By default they try to link to libc but there is no libc for freestanding so we remove it.

You can download the limine.h like this

curl -O https://raw.githubusercontent.com/Limine-Bootloader/limine-protocol/refs/heads/trunk/include/limine.h

Line: 29-43

 const kernel = b.addExecutable(.{ // zig fmt: off .name = "morgan.elf", .root_module = b.createModule(.{ .root_source_file = b.path("kernel/main.zig"), .target = target, .optimize = optimize, .code_model = .kernel, .imports = &.{ .{ .name = "c", .module = translate.createModule() }, } }), .use_llvm = true, .use_lld = true, }); // zig fmt: on 

Standard stuff.

Line: 45-49

 kernel.setLinkerScript(b.path("kernel/linker.ld")); kernel.entry = .{ .symbol_name = "kmain" }; b.installArtifact(kernel); 

We setup the linker script, now remember what is said about zig hardcoding executable entrypoint ? Yes, that entry point is _start for linux and freestanding software. Here we manually change that to kmain. You can ofc also change the kmain function in main.zig to _start, doesn't really matter, I just like kmain more.

We then save the executable.

Line: 51-60

 const make_iso = b.addSystemCommand(&.{ "sh", "scripts/make_iso.sh", }); make_iso.step.dependOn(b.getInstallStep()); const iso_step = b.step("iso", "Build bootable ISO"); iso_step.dependOn(&make_iso.step); } 

We have a script make_iso.sh which makes the iso file for us. This is just that written.

limine.conf

timeout: 5 /morganOS protocol: limine path: boot():/boot/morgan.elf 

Just the limine configuration file. Pretty self-explanatory

scripts/make_iso.sh

#!/bin/sh set -eu # Download Limine curl -fL -o limine-binary.tar.gz \ https://github.com/Limine-Bootloader/Limine/releases/latest/download/limine-binary.tar.gz # Extract and build rm -rf limine-binary tar -xzf limine-binary.tar.gz make -C limine-binary # Prepare ISO directory rm -rf iso_root mkdir -p iso_root/boot/limine mkdir -p iso_root/EFI/BOOT # Copy kernel cp zig-out/bin/morgan.elf iso_root/boot/ # Copy Limine files cp limine.conf \ limine-binary/limine-bios.sys \ limine-binary/limine-bios-cd.bin \ limine-binary/limine-uefi-cd.bin \ iso_root/boot/limine/ # Copy EFI executables cp limine-binary/BOOTX64.EFI \ limine-binary/BOOTIA32.EFI \ iso_root/EFI/BOOT/ # Generate ISO xorriso -as mkisofs -R -r -J \ -b boot/limine/limine-bios-cd.bin \ -no-emul-boot -boot-load-size 4 -boot-info-table \ -hfsplus -apm-block-size 2048 \ --efi-boot boot/limine/limine-uefi-cd.bin \ -efi-boot-part --efi-boot-image \ --protective-msdos-label \ iso_root -o image.iso # Install BIOS stages ./limine-binary/limine bios-install image.iso 

This is the bash script which is gonna make iso for us. I have commented it for you, should be easy to follow. If don't get it ask in comments.

How to run it ?

Compile it zig build iso. This should produce image.iso for you to run on qemu.

Here is the qemu command I am using

qemu-system-x86_64 \ -m 1G \ -serial stdio \ -cdrom image.iso \ -boot d 

If your cursor is stuck in qemu, try pressing C-M-g to free your cursor.

AND THAT IS IT.

Enjoy your first milestone in OS development, hahah you should be happy right now. I am sure you may be confused about some part, so google it, think about it if still don't understand it, either ask in comment or get my discord link on my portfolio Portfolio.

Thank you, may blessing of her majesty be with you.