~boot/bootloader.asm
.asm
Assembly
(text/assembly)
bits 16
org 0x7c00 ; Load origin for bootloader

CR: equ 0x0d
LF: equ 0x0a
BOOTLOADER_STACK_ADDRESS: equ 0xb000

%include "kernel-load-macros-inl.asm"

start:
  jmp short main
  nop

biosParameterBlock: times 87 db 0

main:
  ; Set up segments
  .setup:
		xor ax, ax
		mov ds, ax
		mov es, ax
		mov fs, ax
		mov gs, ax
		mov ss, ax
		mov sp, BOOTLOADER_STACK_ADDRESS ; Stack

		; Boot drive number
		mov [bootDriveNumber], dl

		; Clear screen and print welcome message
		call clear_screen
		mov si, welcomeMessage
		call print_string
		mov si, blankLine
		call print_string

	; Bootloader expansion
	.expand_bootloader:
		mov si, expandingMessage
		call print_string

		; Destination
		mov ax, 0x07e0
		mov es, ax
		xor bx, bx

		; Start sector and length
		mov cl, 1
		mov al, [bootloaderNumberOfExtraSectors]

		; Read disk function
		call read_disk

	.after_expansion:
		jmp expanded_main

  ; Here we would normally load the kernel from disk, but for simplicity, we'll just jump to it.
  jmp 0x0000:0x8000 ; Jump to the kernel's entry point (assuming it's loaded at 0x8000)

%include "utility-inl.asm"

bootDriveNumber: db 0
welcomeMessage: db "[CrystalOS Bootloader]", CR, LF, 0
expandingMessage: db "Info: Expanding bootloader...", CR, LF, 0
diskErrorMessage: db "Error: Failed to read disk!", CR, LF, 0
rebootMessage: db "Press any key to reboot...", CR, LF, 0

end_of_first_sector:
  times 504 - ($ - $$) db 0

	bootloaderNumberOfExtraSectors: dw 0
	kernelStartSector: dw 0
	kernelNumberOfSectors: dw 0

  dw 0xaa55 ; bios bootsector validy magic number

expanded_main:
	mov si, expandedMessage
	call print_string

	call try_enable_a20 ; Try to enable A20 line for accessing memory above 1MB
	
	call describe_gdt ; Describe the GDT so we can switch modes safely
	call describe_idt ; Describe the IDT so protected mode has a valid IDT

	call enable_real_mode ; Ensure we're in real mode before loading the kernel
	call load_kernel ; Load the kernel from disk into memory
	call enter_long_mode ; Set up paging and enter long mode to jump to the 64-bit kernel entry point


  jmp $

%include "a20-utility-inl.asm"
%include "idt-utility-inl.asm"
%include "kernel-load-utility-inl.asm"
%include "long-mode-utility-inl.asm"

blankLine: db " ", CR, LF,0
enableProtectedModeMessage: db "Info: Enabling protected mode!", CR, LF, 0
enableRealModeMessage: db "Info: Enabled real mode!", CR, LF, 0
expandedMessage: db "Info: Bootloader expansion successful!", CR, LF, 0

bootloaderStackPointer: dw 0