Skip to content

Qwen3-0.6B inference (12 KB), bare-metal bootable OS (22 KB), and from-scratch Mini-GPT trainer with live Braille TUI (32 KB) in 100% pure x86-64 NASM assembly. Zero C, zero libc, zero dependencies.

12.9 KB
Raw Blame
; ============================================================================
; src/boot.asm — Multiboot 1 -> 64-bit Long Mode + Ring 3 GDT/TSS + 256-IDT
; Zero-App Ephemeral OS (Stage 1) — Pure x86-64 NASM
; ============================================================================

%include "constants.inc"

extern _bss_start
extern _bss_end
extern kernel_main
extern enable_avx2_cpu
extern isr_exception_handler
extern isr_apic_timer
extern isr_user_exit
extern isr_spurious

global _start
global pml4_table
global pdpt_table
global pd_tables
global gdt64
global gdt64_ptr
global tss64
global idt64
global idt64_ptr
global g_mb_magic
global g_mb_info
global g_boot_tsc
global ring0_trap_stack_top
global df_stack_top
global idt_set_gate

; ============================================================================
; Multiboot 1 Header (within first 8 KiB of ELF)
; ============================================================================
section .multiboot align=4
    dd MB_HEADER_MAGIC
    dd MB_HEADER_FLAGS
    dd MB_HEADER_CHECKSUM

; ============================================================================
; 32-bit Protected Mode Bootstrap
; ============================================================================
section .text.boot
bits 32
default abs

_start:
    cli
    cld

    ; Save Multiboot magic (eax) and info pointer (ebx)
    mov     esi, eax
    mov     ebp, ebx

    ; Zero .bss completely
    mov     edi, _bss_start
    mov     ecx, _bss_end
    sub     ecx, edi
    shr     ecx, 2
    xor     eax, eax
    rep     stosd

    mov     esp, bsp_stack_top
    mov     [g_mb_magic], esi
    mov     [g_mb_info], ebp

    rdtsc
    mov     [g_boot_tsc], eax
    mov     [g_boot_tsc + 4], edx

    ; Zero 14 initial page-table pages (PML4 + PDPT + 12 PDs = 56 KiB -> 0..12 GiB)
    mov     edi, pml4_table
    xor     eax, eax
    mov     ecx, (14 * 4096) / 4
    rep     stosd

    ; PML4[0] -> pdpt_table | P | RW | U (0x07, fine-grained U/S enforced in PD/PT)
    mov     eax, pdpt_table
    or      eax, 0x07
    mov     [pml4_table], eax

    ; PDPT[0] -> pd_tables[0] | P | RW | U (0x07) — holds kernel (U=0) + user sandbox (U=1)
    mov     eax, pd_tables
    or      eax, 0x07
    mov     [pdpt_table + 0], eax

    ; PDPT[1..11] -> pd_tables[1..11] | P | RW (0x03, U=0! Supervisor-only 1..12 GiB!)
    mov     ecx, 1
.fill_pdpt:
    mov     eax, ecx
    shl     eax, 12
    add     eax, pd_tables
    or      eax, 0x03
    mov     [pdpt_table + ecx*8], eax
    mov     dword [pdpt_table + ecx*8 + 4], 0
    inc     ecx
    cmp     ecx, 12
    jb      .fill_pdpt

    ; Fill all 12 * 512 = 6144 PD entries (0..12 GiB) as Supervisor-only (U=0) 2 MiB huge pages:
    ;   0x00000000..0xDFFFFFFF: 0x83 (WB, U=0)
    ;   0xE0000000..0xFDFFFFFF: 0x8B (WT for PCI LFB, U=0)
    ;   0xFE000000..0xFFFFFFFF: 0x9B (UC for APIC/IOAPIC, U=0)
    ;   0x100000000..0x2FFFFFFFF: 0x83 (WB high RAM / NVDIMM weights, U=0)
    mov     edi, pd_tables
    xor     ebx, ebx                    ; low 32 of phys addr
    xor     edx, edx                    ; high 32 of phys addr
    xor     ecx, ecx
.fill_pd:
    mov     eax, ebx
    test    edx, edx
    jnz     .wb_flags
    cmp     ecx, 2032                   ; >= 0xFE000000
    jae     .uc_flags
    cmp     ecx, 1792                   ; >= 0xE0000000
    jae     .wt_flags
.wb_flags:
    or      eax, 0x83
    jmp     .store_pde
.wt_flags:
    or      eax, 0x83                   ; WB for QEMU/Proxmox Bochs VGA LFB (1000x faster scroll/HUD!)
    jmp     .store_pde
.uc_flags:
    or      eax, 0x9B
.store_pde:
    mov     [edi], eax
    mov     [edi + 4], edx
    add     edi, 8
    add     ebx, 0x00200000
    adc     edx, 0
    inc     ecx
    cmp     ecx, 6144
    jb      .fill_pd

    ; Build clean Supervisor-only direct physical map at PML4[1] (0x8000000000 .. +12 GiB)
    ; Never modified by Ring 3 sandbox 4 KiB PTs (immune to 0x10000000..0x205FFFFF VA holes!)
    mov     edi, pdpt_phys
    xor     eax, eax
    mov     ecx, (2 * 4096) / 4
    rep     stosd

    mov     eax, pdpt_phys
    or      eax, 0x03                   ; P | RW (U=0 Supervisor-only!)
    mov     [pml4_table + 8], eax
    mov     dword [pml4_table + 12], 0

    ; Copy clean 0..1 GiB 2 MiB PDEs from pd_tables[0] -> pd_phys0
    mov     esi, pd_tables
    mov     edi, pd_phys0
    mov     ecx, 4096 / 4
    rep     movsd

    mov     eax, pd_phys0
    or      eax, 0x03
    mov     [pdpt_phys + 0], eax
    mov     dword [pdpt_phys + 4], 0

    mov     ecx, 1
.fill_pdpt_phys:
    mov     eax, ecx
    shl     eax, 12
    add     eax, pd_tables
    or      eax, 0x03
    mov     [pdpt_phys + ecx*8], eax
    mov     dword [pdpt_phys + ecx*8 + 4], 0
    inc     ecx
    cmp     ecx, 12
    jb      .fill_pdpt_phys

    ; Load CR3 = pml4_table
    mov     eax, pml4_table
    mov     cr3, eax

    ; Enable PAE (CR4.PAE = bit 5)
    mov     eax, cr4
    or      eax, (1 << 5)
    mov     cr4, eax

    ; Enable Long Mode (LME = bit 8) + No-Execute (NXE = bit 11) in IA32_EFER
    mov     ecx, 0xC0000080
    rdmsr
    or      eax, (1 << 8) | (1 << 11)
    wrmsr

    ; Enable Paging (CR0.PG=31), Write Protect (CR0.WP=16), Protected Mode (CR0.PE=0)
    mov     eax, cr0
    or      eax, 0x80010001
    mov     cr0, eax

    ; Load 64-bit GDT and far jump to 64-bit Long Mode
    lgdt    [gdt64_ptr]
    jmp     SEL_KCODE:long_mode_start

; ============================================================================
; 64-bit Long Mode Entry
; ============================================================================
section .text
bits 64
default rel

long_mode_start:
    mov     ax, SEL_KDATA
    mov     ds, ax
    mov     es, ax
    mov     ss, ax
    mov     fs, ax
    mov     gs, ax

    lea     rsp, [rel bsp_stack_top]
    and     rsp, -16

    ; Clean RFLAGS (IF=0, DF=0)
    push    0
    popfq

    ; Enable basic SSE/FPU cleanly (CR0.EM=0, CR0.MP=1, CR4.OSFXSR|OSXMMEXCPT)
    mov     rax, cr0
    and     ax, 0xFFFB
    or      ax, 0x0002
    mov     cr0, rax
    mov     rax, cr4
    or      eax, (1 << 9) | (1 << 10)
    mov     cr4, rax
    fninit
    ldmxcsr [rel default_mxcsr]
    call    enable_avx2_cpu

    ; Setup 64-bit TSS and load TR (0x28)
    call    tss_setup_and_load

    ; Setup 256-entry IDT (exceptions 0..31, APIC timer 0x20, int 0x80 DPL=3, spurious 0xFF)
    call    idt_setup_and_load

    ; Enter kernel
    call    kernel_main

.halt_forever:
    cli
    hlt
    jmp     .halt_forever

; ----------------------------------------------------------------------------
; Setup 64-bit TSS with RSP0 (Ring 3 trap stack), IST1 (#DF stack), IOPB=104
; ----------------------------------------------------------------------------
tss_setup_and_load:
    lea     rdi, [rel tss64]
    xor     eax, eax
    mov     ecx, 104 / 4
    rep     stosd

    lea     rax, [rel ring0_trap_stack_top]
    mov     [rel tss64 + 4], rax        ; RSP0
    lea     rax, [rel df_stack_top]
    mov     [rel tss64 + 36], rax       ; IST1 (for #DF)
    mov     word [rel tss64 + 102], 104 ; IOPB offset >= limit -> deny all I/O in Ring 3

    ; Write 16-byte 64-bit TSS descriptor at gdt64 + 0x28
    lea     rax, [rel tss64]            ; base
    lea     rdi, [rel gdt64 + 0x28]
    mov     word [rdi + 0], 103         ; limit[15:0]
    mov     [rdi + 2], ax               ; base[15:0]
    shr     rax, 16
    mov     [rdi + 4], al               ; base[23:16]
    mov     byte [rdi + 5], 0x89        ; P=1, DPL=0, S=0, Type=9 (64-bit TSS avail)
    mov     byte [rdi + 6], 0x00        ; flags + limit[19:16]
    mov     [rdi + 7], ah               ; base[31:24]
    shr     rax, 16
    mov     [rdi + 8], eax              ; base[63:32]
    mov     dword [rdi + 12], 0         ; reserved

    lgdt    [rel gdt64_ptr]
    mov     ax, SEL_TSS
    ltr     ax
    ret

; ----------------------------------------------------------------------------
; void idt_set_gate(uint32 vec in edi, void *handler in rsi, uint8 attr in dl, uint8 ist in cl)
; ----------------------------------------------------------------------------
idt_set_gate:
    mov     eax, edi
    shl     rax, 4                      ; vec * 16
    lea     r8, [rel idt64]
    add     r8, rax
    mov     rax, rsi
    mov     [r8 + 0], ax                ; offset 15..0
    mov     word [r8 + 2], SEL_KCODE    ; 64-bit kernel CS
    mov     [r8 + 4], cl                ; IST (0..7)
    mov     [r8 + 5], dl                ; type/attr (0x8E or 0xEE)
    shr     rax, 16
    mov     [r8 + 6], ax                ; offset 31..16
    shr     rax, 16
    mov     [r8 + 8], eax               ; offset 63..32
    mov     dword [r8 + 12], 0
    ret

; ----------------------------------------------------------------------------
; Build & load 256-entry 64-bit IDT
; ----------------------------------------------------------------------------
idt_setup_and_load:
    push    rbx
    ; Fill all 256 vectors with spurious handler first
    xor     ebx, ebx
.fill_spurious:
    cmp     ebx, 256
    jae     .fill_exc
    mov     edi, ebx
    lea     rsi, [rel isr_spurious]
    mov     dl, 0x8E
    xor     cl, cl
    call    idt_set_gate
    inc     ebx
    jmp     .fill_spurious

.fill_exc:
    ; Vectors 0..31: CPU exceptions (vector 8 #DF uses IST=1)
    lea     r9, [rel isr_stub_table]
    xor     ebx, ebx
.exc_lp:
    cmp     ebx, 32
    jae     .install_special
    mov     edi, ebx
    mov     rsi, [r9 + rbx*8]
    mov     dl, 0x8E                    ; P=1, DPL=0, Interrupt Gate
    xor     cl, cl
    cmp     ebx, 8                      ; Double Fault -> IST1
    jne     .no_ist
    mov     cl, 1
.no_ist:
    call    idt_set_gate
    inc     ebx
    jmp     .exc_lp

.install_special:
    ; Vector 0x20: Local APIC Timer (DPL=0, Interrupt Gate)
    mov     edi, VEC_APIC_TIMER
    lea     rsi, [rel isr_apic_timer]
    mov     dl, 0x8E
    xor     cl, cl
    call    idt_set_gate

    ; Vector 0x80: Ring 3 Exit Gate (DPL=3! 0xEE = P=1, DPL=3, Interrupt Gate)
    mov     edi, VEC_EXIT
    lea     rsi, [rel isr_user_exit]
    mov     dl, 0xEE
    xor     cl, cl
    call    idt_set_gate

    ; Vector 0xFF: APIC Spurious Interrupt
    mov     edi, VEC_APIC_SPURIOUS
    lea     rsi, [rel isr_spurious]
    mov     dl, 0x8E
    xor     cl, cl
    call    idt_set_gate

    lidt    [rel idt64_ptr]
    pop     rbx
    ret

; ============================================================================
; Exception ISR Stubs (vectors 0..31) -> isr_exception_handler (in sandbox.asm)
; ============================================================================
%macro ISR_NOERR 1
isr_stub_%1:
    push    qword 0
    push    qword %1
    jmp     isr_exception_handler
%endmacro

%macro ISR_ERR 1
isr_stub_%1:
    push    qword %1
    jmp     isr_exception_handler
%endmacro

ISR_NOERR 0
ISR_NOERR 1
ISR_NOERR 2
ISR_NOERR 3
ISR_NOERR 4
ISR_NOERR 5
ISR_NOERR 6
ISR_NOERR 7
ISR_ERR   8
ISR_NOERR 9
ISR_ERR   10
ISR_ERR   11
ISR_ERR   12
ISR_ERR   13
ISR_ERR   14
ISR_NOERR 15
ISR_NOERR 16
ISR_ERR   17
ISR_NOERR 18
ISR_NOERR 19
ISR_NOERR 20
ISR_ERR   21
ISR_NOERR 22
ISR_NOERR 23
ISR_NOERR 24
ISR_NOERR 25
ISR_NOERR 26
ISR_NOERR 27
ISR_NOERR 28
ISR_ERR   29
ISR_ERR   30
ISR_NOERR 31

; ============================================================================
; Writable GDT (needed so tss_setup_and_load can fill 64-bit TSS base)
; ============================================================================
section .data
align 16
gdt64:
    dq 0x0000000000000000               ; 0x00: Null
    dq 0x00AF9A000000FFFF               ; 0x08: Kernel 64-bit Code (DPL=0, RX)
    dq 0x00CF92000000FFFF               ; 0x10: Kernel 64-bit Data (DPL=0, RW)
    dq 0x00CFF2000000FFFF               ; 0x18: User 64-bit Data   (DPL=3, RW) -> 0x1B
    dq 0x00AFFA000000FFFF               ; 0x20: User 64-bit Code   (DPL=3, RX) -> 0x23
    dq 0x0000000000000000               ; 0x28: TSS low  (filled at runtime)
    dq 0x0000000000000000               ; 0x30: TSS high (filled at runtime)
gdt64_end:

align 8
gdt64_ptr:
    dw gdt64_end - gdt64 - 1
    dq gdt64

; ============================================================================
; Read-only Tables
; ============================================================================
section .rodata
align 8
idt64_ptr:
    dw 256 * 16 - 1
    dq idt64

align 8
isr_stub_table:
%assign i 0
%rep 32
    dq isr_stub_%+i
%assign i i+1
%endrep

align 4
default_mxcsr:  dd 0x00001F80

; ============================================================================
; Uninitialized Data (.bss)
; ============================================================================
section .bss
alignb 4096
pml4_table:         resb 4096
pdpt_table:         resb 4096
pd_tables:          resb 12 * 4096
pdpt_phys:          resb 4096
pd_phys0:           resb 4096

alignb 16
idt64:              resb 256 * 16
tss64:              resb 104

alignb 16
bsp_stack:          resb BSP_STACK_SIZE
bsp_stack_top:

alignb 16
ring0_trap_stack:   resb TRAP_STACK_SIZE
ring0_trap_stack_top:

alignb 16
df_stack:           resb DF_STACK_SIZE
df_stack_top:

alignb 8
g_boot_tsc:         resq 1
g_mb_magic:         resd 1
g_mb_info:          resd 1