Compare commits

..
82 Commits
Author SHA1 Message Date
pantonshire 20e857b453 explain big code segment 2025-11-03 09:40:30 +00:00
pantonshire 535749afc9 expand protected mode code segment more 2025-11-03 09:39:37 +00:00
pantonshire a90c727a9a expand protected mode code segment 2025-11-03 09:31:02 +00:00
pantonshire da6f981a6a move gdt, use fixed addr 2025-07-26 18:01:59 +01:00
pantonshire f0289cd753 use nographic for run_serial 2025-07-26 17:56:36 +01:00
pantonshire e2478d0f3a serial print macro 2025-07-26 17:53:41 +01:00
pantonshire 988d3d601d fixed addr gdt, serial 2025-07-26 17:40:48 +01:00
pantonshire b0dffe7bc8 use strict provenance api 2025-07-26 16:01:57 +01:00
pantonshire 868844f710 add calling convention notes 2025-07-26 15:43:02 +01:00
pantonshire 88d7fb32d4 fixes for latest nightly 2025-07-26 15:11:17 +01:00
pantonshire 1a8fadf226 wip reset docs 2025-04-27 15:43:55 +01:00
pantonshire bb60e1c8ed load and jump to stage 3 separately from stage 2 2025-04-21 10:53:34 +01:00
pantonshire da529e8426 fix off-by-one error in stage 2 prelude 2025-04-21 08:57:19 +01:00
pantonshire 9e5cbaf07b add build to gitignore 2025-04-07 18:29:32 +01:00
pantonshire 359d980a1c build single blob for stages 2 and 3 2025-04-07 18:28:05 +01:00
pantonshire b61aa778d0 xtask to build stages 1-3 2025-04-07 15:29:54 +01:00
pantonshire 1974163db6 use hlt for padding of stage 2 data section 2025-04-07 15:29:06 +01:00
pantonshire 96e98cd534 default to nightly compiler 2025-04-07 13:25:33 +01:00
pantonshire 4f79fbae5b cargo xtask alias 2025-04-07 12:53:35 +01:00
pantonshire 63977011cf update layout macros 2025-04-07 12:36:13 +01:00
pantonshire b41ba2de55 workspace for build tools 2025-04-06 14:34:42 +01:00
pantonshire 2219fac4e5 more refactoring 2025-04-06 14:27:55 +01:00
pantonshire 909875ec5b update resouces 2025-04-06 14:22:26 +01:00
pantonshire f5b28bd24d fix protected mode target specification 2025-04-05 19:20:14 +01:00
pantonshire b2bb36e9f4 rust stage 4 2025-03-09 09:13:30 +00:00
pantonshire dae57bb1a1 fix s3 a20 2025-03-05 09:00:39 +00:00
pantonshire 2b1a9f9412 wip refactor 2025-03-04 09:48:46 +00:00
pantonshire ae2720c826 library-ify nasm helper 2025-03-03 09:32:58 +00:00
pantonshire ed0f9119f4 memory region merge algorithm 2024-12-22 12:14:10 +00:00
pantonshire b0e757769a print to vga on panic 2024-10-18 14:09:43 +01:00
pantonshire 5d0539b987 global vga buf 2024-10-18 14:02:08 +01:00
pantonshire 8ed5f45a08 add implementation of write_char for VgaBuf 2024-10-17 13:14:05 +01:00
pantonshire 161df47dd5 vga helper 2024-10-17 13:11:46 +01:00
pantonshire eb197c3122 update resources 2024-10-16 21:15:44 +01:00
pantonshire 1880e89194 fix bios call, return register values to caller 2024-10-16 21:15:29 +01:00
pantonshire 766a9c981c refactor + wip bios call from protected mode 2024-10-16 17:45:52 +01:00
pantonshire 121e13165b enable a20 in stage 2 prelude 2024-10-15 10:51:31 +01:00
pantonshire a86d73e6ee enter protected mode and jump to rust binary 2024-08-26 20:05:24 +01:00
pantonshire e20030fbc3 link in the prelude object 2024-08-25 18:40:05 +01:00
pantonshire 559a4275ba move defines.s to include directory 2024-08-25 11:23:43 +01:00
pantonshire d55d71059f build asm with werror 2024-08-25 11:19:07 +01:00
pantonshire 465da6e7cd build asm in build.rs 2024-08-25 11:15:11 +01:00
pantonshire 246f5cfccf build flat x86 rust binary 2024-08-11 14:18:27 +01:00
pantonshire 88aa06627c fix hexdump alignment for non-multiple-of-16 size 2024-08-10 18:25:39 +01:00
pantonshire d1ee14003c parse section names table header 2024-08-10 18:20:59 +01:00
pantonshire 4d6521c5b4 debug hexdump for elf 2024-08-10 17:01:53 +01:00
pantonshire 0474360fef start elf parser 2024-07-30 09:42:07 +01:00
pantonshire 8f94f4b5e9 update resources 2024-07-28 18:42:12 +01:00
pantonshire 2015399687 enter unreal mode 2024-07-27 17:13:58 +01:00
pantonshire 4617416378 update resources 2024-07-26 07:50:30 +01:00
pantonshire 93f6223afc update resources 2024-07-25 09:27:53 +01:00
pantonshire f25d0391c1 todo comment for memory detection 2024-07-25 08:58:56 +01:00
pantonshire a7b35d7302 vga segment define 2024-07-24 20:59:29 +01:00
pantonshire 62638cf6f5 explicitly set memory in qemu args 2024-07-24 09:32:00 +01:00
pantonshire f4085f1069 calculate memmap entry len, dump entries 2024-07-24 09:25:25 +01:00
pantonshire fdf6d81b2e use e820 to get available memory 2024-07-23 07:40:29 +01:00
pantonshire 8e5761f610 improve 8042 status defines 2024-07-22 09:37:08 +01:00
pantonshire 575ab46109 enable a20 2024-07-22 09:33:02 +01:00
pantonshire bf3a9d2a00 typo 2024-07-22 08:53:49 +01:00
pantonshire 15d97a8d55 replace and with test in boot0 to remove a mov 2024-07-22 08:50:02 +01:00
pantonshire d362758b4d panic dumps more registers, panic type arg 2024-07-21 17:18:50 +01:00
pantonshire 035bba16f6 dump more registers on panic, print register names 2024-07-20 08:23:07 +01:00
pantonshire 5c9987e99b readme 2024-07-20 07:40:44 +01:00
pantonshire 89e2cef4fa start work on panic handler 2024-07-19 09:05:13 +01:00
pantonshire 030edfc301 function for dumping register value 2024-07-18 09:05:19 +01:00
pantonshire e913eb04ae use null-terminated strings for vga_println 2024-07-18 08:12:51 +01:00
pantonshire bd3063a80d vga print helpers 2024-07-14 19:01:15 +01:00
pantonshire 592826e8cd load remaining boot1 sectors 2024-07-14 10:06:18 +01:00
pantonshire 76c6d5c355 save a few boot0 bytes 2024-07-14 08:17:22 +01:00
pantonshire 8a75404437 minor boot0 cleanup 2024-07-13 15:46:48 +01:00
pantonshire cdb70a4105 add seabios as submodule 2024-07-12 20:23:35 +01:00
pantonshire 5dad1faa66 write second stage to its own partition 2024-07-07 18:30:11 +01:00
pantonshire 49d53571c4 remove proof, perhaps we can put it elsewhere later 2024-07-07 18:22:09 +01:00
pantonshire 067e4df824 clean up dummy stage 2 a bit 2024-07-07 18:13:01 +01:00
pantonshire fbdbbc5345 jump to stage 2 bootloader 2024-07-07 18:07:18 +01:00
pantonshire b45ee48c90 treat partition end lba as inclusive 2024-07-07 17:56:45 +01:00
pantonshire b32a763d17 tiny optimisation to gpt entry size check 2024-07-07 17:21:20 +01:00
pantonshire c599bf3ed6 use labels for stack variables 2024-07-07 16:34:54 +01:00
pantonshire f9e2135e3b fix bug in stage 2 search 2024-07-07 16:04:05 +01:00
pantonshire cda3a448a9 use qemu stdio monitor 2024-07-06 22:36:25 +01:00
pantonshire 2cca21750c load stage 2 partition start and end 2024-07-06 22:36:04 +01:00
pantonshire 4433200e23 function for reading lba, get correct offset into sector for gpt entry 2024-07-06 12:59:35 +01:00
68 changed files with 4240 additions and 303 deletions

No files matched your search

+3
View File
@@ -0,0 +1,3 @@
[alias]
xtask = "run --package xtask --"
+6
View File
@@ -0,0 +1,6 @@
build/
*.o
*.bin
.pc
target/
+3
View File
@@ -0,0 +1,3 @@
[submodule "seabios"]
path = seabios
url = https://github.com/coreboot/seabios.git
+5
View File
@@ -0,0 +1,5 @@
[workspace]
resolver = "2"
members = ["xtask"]
exclude = ["stage_3"]
-272
View File
@@ -1,272 +0,0 @@
; MEMORY LAYOUT
; R = reserved, U = usable
; --------------------------------------------------------------------
; R | 0x000000 - 0x000400: real-mode interrupt vector table
; R | 0x000400 - 0x000500: bios data area
; U | 0x000500 - 0x007c00: stack
; U | 0x007c00 - 0x007e00: boot sector
; U | 0x007e00 - 0x080000: conventional usable memory
; R | 0x080000 - 0x0a0000: extended bios data area (maximum possible size)
; R | 0x0a0000 - 0x0c0000: video memory
; R | 0x0c0000 - 0x0c8000: video bios
; R | 0x0c8000 - 0x0f0000: bios expansiosn
; R | 0x0f0000 - 0x100000: motherboard bios
; BASE STACK FRAME
; --------------------------------------------------------------------
; bp - 0x02: drive number
; bp - 0x04: sectors per track
; bp - 0x06: number of heads
; bp - 0x08: partition array starting LBA
; bp - 0x0a: number of GPT partitions (saturated to 16-bits)
; bp - 0x0c: sector stride when loading GPT entries
; bp - 0x0e: byte stride when loading GPT entries
; bp - 0x10: entries per sector when loding GPT entries
; bp - 0x12: current entry index
; bp - 0x14: current entry index within the current sector
; bp - 0x16: number of sectors loaded
; bp - 0x18: current LBA
; BIOS puts our boot sector at 0000:7c00
org 0x7c00
; We're (probably) in real mode
bits 16
; Disable interrupts
cli
xor ax, ax
mov ds, ax
mov es, ax
; Put the stack base at 0x7c00.
; Stack grows high->low, so we'll grow away from our program text at 0x7c00.
mov ss, ax
mov bp, 0x7c00
mov sp, bp
; Store boot drive number
xor dh, dh
push dx
; Get drive geometry
mov di, 0x00
mov ah, 0x08
int 0x13
jc .panic
; Load sectors per track into cx & spill
and cl, 0x3f
xor ch, ch
push cx
; Load number of heads into bx & spill
movzx bx, dh
inc bx
push bx
; Load LBA 1.
cmp cl, 1 ; Division of 1 by nonzero can be done with cmp
sete al ; temp = LBA / (sectors per track)
setne cl ; sector - 1 = LBA % (sectors per track)
inc cl
xor ah, ah ; Zero-extend temp
xor dx, dx ; div by 16-bit register divides dx:ax, so we zero dx
div bx ; dx = mod (head), ax = div (cylinder)
mov dh, dl ; Head
mov ch, al ; Cylinder
; We already have sector in cl
mov ah, 2 ; Read disk
mov al, 1 ; Load one sector
mov bx, 0x7e00
mov dl, [bp - 0x2] ; Drive number
int 0x13
jc .panic
; head = temp % number of heads
; cylinder = temp / number of heads
mov cx, 8
mov si, .gpt_magic
mov di, 0x7e00
repe cmpsb
jne .panic
; Ensure the 8-byte GPT starting LBA fits in 16 bits
mov di, 0x7e00 ; The rep increments di so we need to reset it
mov eax, [di + 0x4c]
mov bx, [di + 0x4a]
or ax, bx
or eax, eax
jnz .panic
; Load and spill the GPT starting LBA
mov ax, [di + 0x48]
push ax
; Load number of partitions
mov ax, [di + 0x50]
mov bx, [di + 0x52]
or bx, bx
jz .gpt_n_partitions_loaded
; Number of partitions overflows 16 bits, so we just concern ourselves with the first 65535.
; That's an awful lot of partitions anyway.
mov ax, 0xffff
.gpt_n_partitions_loaded:
push ax
; Load GPT entry size
mov eax, [di + 0x54] ; Operand size override otherwise this is going to be painful
mov ebx, eax
; Assert that the entry size is 128 * 2^n for some integer n>=0. This is required for a valid GPT
; and has the nice properties that:
; - If each entry is larger than a sector (512 bytes), they'll be sector-aligned.
; - If each entry is smaller than a sector, an integer number of them will fit into a sector.
or eax, eax ; Test size != 0 because 128 * 2^n != 0
jz .panic
and eax, 127 ; Test size is a multiple of 128
jnz .panic
mov eax, ebx
shr eax, 7 ; Divide by 128
mov ecx, eax
dec eax
and eax, ecx ; Test size/128 is a power of 2. popcnt gives an exception for some reason...
jnz .panic
mov eax, ebx
; Find the "sector stride", which is the number of sectors we increment by each time we want to
; load a new entry.
shr eax, 9 ; Divide by sector size to get sectors per entry
cmp eax, 0xffff ; Make sure sectors per entry fits in 16 bits
ja .panic
or ax, ax
jnz .gpt_sector_stride_loaded
; Sector stride must be at least one or we'll load the same sector each time!
inc ax
.gpt_sector_stride_loaded:
push ax
; Find the "byte stride", which is the number of bytes we increment by each time we want to load
; the next entry in the same sector.
cmp ebx, 512
jb .gpt_find_entries_per_sector
push word 0 ; Arbitrary byte stride since there's only one entry per sector
push word 1 ; 1 entry per sector, since an entry is larger than a sector
jmp .gpt_found_entries_per_sector
.gpt_find_entries_per_sector:
push bx ; Store byte stride = entry length in this case
xor dx, dx
mov ax, 512
div bx ; Find entries per sector
push ax
.gpt_found_entries_per_sector:
; Set up stack variables for our second stage search loop.
xor ax, ax
push ax ; Current entry
push ax ; Current entry within the current sector
push ax ; First LBA loaded?
mov ax, [bp - 0x08] ; Starting LBA
push ax ; Current LBA
; Search for the partition storing our second stage.
.loop_find_stage2:
mov dx, [bp - 0x12]
cmp [bp - 0x0a], dx
; Panic if we've run out of partitions and haven't found the second stage yet.
jbe .panic
; If we haven't loaded any sectors yet, load the first one.
cmp word [bp - 0x16], 0 ; Load number of sectors loaded
je .load_first_lba
; If there's still more entries in the current sector, skip loading a new sector
mov ax, [bp - 0x18] ; Load current entry index within the current sector
cmp [bp - 0x10], ax ; Compare to entries per sector
ja .process_current_entry
mov ax, [bp - 0x0c] ; Load sector stride
add word [bp - 0x18], ax ; Increment current LBA by sector stride
mov word [bp - 0x14], 0 ; Reset the current entry index within the current sector
.load_first_lba:
mov ax, [bp - 0x18] ; Load current LBA
xor dx, dx
div word [bp - 0x04] ; Divide by sectors per track. dx = mod (sector - 1), ax = div (temp)
mov cx, dx
inc cx ; Put sector into cx (bios will read sector from cl)
xor dx, dx
div word [bp - 0x06] ; Divide by number of heads. dx = mod (head), ax = div (cylinder)
mov dh, dl
mov ch, al
mov dl, byte [bp - 0x02] ; Load drive number
mov ah, 0x02
mov al, 1
mov bx, 0x8000
int 0x13 ; Read sector
jc .panic
inc word [bp - 0x16] ; Increment number of sectors loaded
.process_current_entry:
jmp .debug
; TODO
; TODO: remember to read offset by current entry index within the current sector
inc word [bp - 0x12] ; Increment current entry index
inc word [bp - 0x14] ; Increment current entry index within the current sector
jmp .loop_find_stage2
.debug:
; Segment for VGA (0xb800 * 16 = 0xb8000)
mov ax, 0xb800
mov fs, ax
; Set VGA mode
; https://mendelson.org/wpdos/videomodes.txt
mov ax, 0x0003
int 0x10
mov al, [0x7e00]
mov byte fs:[0x0000], al
mov al, [0x8000]
mov byte fs:[0x0002], al
; mov word fs:[0x0000], 0xc048
; mov word fs:[0x0002], 0xc069
hlt
.panic:
mov ax, 0x0003
int 0x10
mov ax, 0xb800
mov ds, ax
mov word [0x0000], 0x4f21
hlt
; TODO: enable A20
; TODO: load a second stage
; TODO: grab all the info we can from bios interrupts and deliver it to ths OS nicely
; e.g. in a fixed memory location
; TODO:
; - Generate GPT in justfile
; - Parse global parition table
; - Load second stage from GPT partition with a particular UUID / name like GRUB does
; (it's Hah!IdontNeedEFI in GRUB)
; - https://en.wikipedia.org/wiki/BIOS_boot_partition
; - Future work:
; - Boot from UEFI
; - Boot on non-GPT partitioned disk
.gpt_magic:
db "EFI PART"
.guid_linux:
db 0xaf, 0x3d, 0xc6, 0x0f, 0x83, 0x84, 0x72, 0x47, \
0x8e, 0x79, 0x3d, 0x69, 0xd8, 0x47, 0x7d, 0xe4
; MBR bootstrap field is 440 bytes long
%if ($ - $$) > 440
%error "exceeded mbr bootstrap field size"
%endif
-23
View File
@@ -1,23 +0,0 @@
org 0x7c00
bits 16
; Reveal the true nature of jen
xor bx, bx
mov ax, 17
loop:
cmp bx, ax
jae done
lea si, [womble + bx]
mov dh, [si]
mov di, bx
shl di, 1
mov byte fs:[di], dh
mov byte fs:[di + 0x01], 0x1f
inc bx
jmp loop
done:
hlt
womble:
db "jen is a womble!"
+7
View File
@@ -0,0 +1,7 @@
[build]
target = "target_protected.json"
[unstable]
build-std = [ "core", "compiler_builtins" ]
build-std-features = [ "compiler-builtins-mem" ]
+7
View File
@@ -0,0 +1,7 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 3
[[package]]
name = "boot1"
version = "0.1.0"
+14
View File
@@ -0,0 +1,14 @@
[package]
name = "boot1"
version = "0.1.0"
edition = "2021"
[profile.dev]
opt-level = "s"
debug = 0
[profile.release]
opt-level = "s"
debug = 0
[dependencies]
+186
View File
@@ -0,0 +1,186 @@
%include "defines.s"
extern gdt_flat_slice
extern gdt_flat
extern GDT_FLAT_IDX_CODE_32
extern GDT_FLAT_IDX_CODE_16
extern GDT_FLAT_IDX_DATA
section .text
[bits 32]
; FIXME: use a separate stack for real mode
_bios_call:
.PARAMS_START equ 36
.PARAM_BIOS_INTR_NUM equ .PARAMS_START
.PARAM_BIOS_INTR_ARGS_PTR equ .PARAMS_START + 4
pushad
mov ebp, esp
push ds
push es
push fs
push gs
push ss
; Push cr0, the GDT and the IDT to the stack so we can restore them once we're finished with real mode.
mov eax, cr0
push eax
sub esp, 8
sidt [esp]
sub esp, 8
sgdt [esp]
; Load the address of the `int` instruction we want to run, and store it on the stack for later.
mov eax, [ebp + .PARAM_BIOS_INTR_NUM]
lea eax, [int_fns + (3 * eax)]
push eax
; Copy the BIOS call arguments provided by the caller onto the stack, for us to pop later.
sub esp, 28
mov ecx, 28
mov esi, [ebp + .PARAM_BIOS_INTR_ARGS_PTR]
mov edi, esp
rep movsb
; Switch to a 16-bit code segment, but remain in protected mode.
jmp GDT_FLAT_IDX_CODE_16:.protected_mode_16
[bits 16]
.protected_mode_16:
; Disable paging and protected mode.
mov eax, cr0
and eax, 0x7ffffffe
mov cr0, eax
jmp 0:.real_mode
.real_mode:
xor ax, ax
mov ds, ax
mov es, ax
mov fs, ax
mov gs, ax
mov ss, ax
; Load the caller-provided register values off the stack.
pop eax
pop ebx
pop ecx
pop edx
pop esi
pop edi
pop ds
pop es
; Call the function which runs the correct `int` instruction.
push bp
mov bp, sp
call [bp + 2]
pop bp
; Copy the resulting register values back into the `BiosIntr` struct provided by the caller.
pushfd
push es
push ds
push edi
push esi
push edx
push ecx
push ebx
push eax
mov cx, 32
mov si, sp
mov di, [bp + .PARAM_BIOS_INTR_ARGS_PTR]
rep movsb
add sp, 32
; Reset the segment registers that were changed to the caller-provided values.
xor ax, ax
mov ds, ax
mov es, ax
; Pop the `int` function off the stack.
add sp, 4
; Reload the GDT in case the BIOS call changed it.
mov bx, sp
lgdt [bx]
add sp, 8
mov bx, sp
lidt [bx]
add sp, 8
; Restore cr0, re-enabling protected mode.
pop eax
mov cr0, eax
jmp GDT_FLAT_IDX_CODE_32:.protected_mode_32
[bits 32]
.protected_mode_32:
pop ss
pop gs
pop fs
pop es
pop ds
popad
ret
global _bios_call
%macro int_fn 1
int %1
ret
%endmacro
int_fns:
int_fn 0x00
int_fn 0x01
int_fn 0x02
int_fn 0x03
int_fn 0x04
int_fn 0x05
int_fn 0x06
int_fn 0x07
int_fn 0x08
int_fn 0x09
int_fn 0x0a
int_fn 0x0b
int_fn 0x0c
int_fn 0x0d
int_fn 0x0e
int_fn 0x0f
int_fn 0x10
int_fn 0x11
int_fn 0x12
int_fn 0x13
int_fn 0x14
int_fn 0x15
int_fn 0x16
int_fn 0x17
int_fn 0x18
int_fn 0x19
int_fn 0x1a
int_fn 0x1b
int_fn 0x1c
int_fn 0x1d
int_fn 0x1e
int_fn 0x1f
section .rodata
idt_real:
dw 0x3ff
dd 0
+95
View File
@@ -0,0 +1,95 @@
section .rodata
gdt_flat_slice:
dw GDT_FLAT_LEN
dd gdt_flat
global gdt_flat_slice
; Segment descriptor layout
; | Range (bits) | Field |
; |--------------|---------------|
; | 0-16 | limit |
; | 16-32 | base |
; | 32-40 | base cont. |
; | 40-48 | access |
; | 48-52 | limit cont. |
; | 52-56 | flags |
; | 56-64 | base cont. |
;
; Flags
; - 0: reserved
; - 1: long-mode code segment
; - 2: size
; - unset: 16-bit
; - set: 32-bit
; - 3: granularity
; - unset: limit is measured in bytes
; - set: limit is measured in 4KiB pages
;
; Access
; - 0: accessed
; - unset: CPU will set it when the segment is accessed
; - 1: readable / writable
; - data segments: is segment writable (data segments are always readable)
; - code segments: is segment readable (code segments are never writable)
; - 2: direction / conforming
; - data segments: whether segment grows down
; - code segments: whether this can be executed from a lower-privilege ring
; - 3: executable
; - unset: this is a data segment
; - set: this is a code segment
; - 4: descriptor type
; - unset: this is a task state segment
; - set: this is a data or code segment
; - 5-6: privilege level (ring number)
; - 7: present (must be set)
;
align 8
gdt_flat:
; First GDT entry must be 0.
dq 0
; 32-bit code segment.
; Bytes 0x0000 - 0xffff.
.segment_code_32:
db 0xff, 0xff, \
0x00, 0x00, \
0x00, \
10011011b, \
01000000b, \
0x00
; 16-bit code segment, to use if we want to switch back to real mode.
; Bytes 0x0000 - 0xffff.
.segment_code_16:
db 0xff, 0xff, \
0x00, 0x00, \
0x00, \
10011011b, \
00000000b, \
0x00
; Data segment.
; Pages 0x000000 - 0x0fffff, which covers the entire 32-bit address space (start of 0xfffff-th page
; is 0xfffff * 4096 = 0xfffff000, end of page exclusive is 0xfffff000 + 4096 = 0x100000000).
.segment_data:
db 0xff, 0xff, \
0x00, 0x00, \
0x00, \
10010011b, \
11001111b, \
0x00
global gdt_flat
GDT_FLAT_LEN equ ($ - gdt_flat)
GDT_FLAT_IDX_CODE_32 equ (gdt_flat.segment_code_32 - gdt_flat)
global GDT_FLAT_IDX_CODE_32
GDT_FLAT_IDX_CODE_16 equ (gdt_flat.segment_code_16 - gdt_flat)
global GDT_FLAT_IDX_CODE_16
GDT_FLAT_IDX_DATA equ (gdt_flat.segment_data - gdt_flat)
global GDT_FLAT_IDX_DATA
+377
View File
@@ -0,0 +1,377 @@
%include "defines.s"
%include "ps2.s"
[bits 16]
extern boot1_bin_len
extern boot1_bin_sectors
extern boot1_magic
extern _start
extern gdt_flat_slice
extern gdt_flat
extern GDT_FLAT_IDX_CODE_32
extern GDT_FLAT_IDX_CODE_16
extern GDT_FLAT_IDX_DATA
section .prelude
%macro copy_stack_var_to_globals 2
mov %1, [bp - %2]
mov [GLOBALS + %2], %1
%endmacro
; boot0 loads only our first sector into memory. We must load the rest.
self_load:
; Now that we're not doing instruction byte golf like we were in boot0, we can afford to move
; the various boot0 stack variables to the globals section.
copy_stack_var_to_globals ax, BOOT_DRIVE
copy_stack_var_to_globals ax, SECTORS_PER_TRACK
copy_stack_var_to_globals ax, N_HEADS
copy_stack_var_to_globals ax, GPT_ENTRIES_START_LBA
copy_stack_var_to_globals ax, GPT_N_ENTRIES_16
copy_stack_var_to_globals ax, GPT_SECTOR_STRIDE
copy_stack_var_to_globals ax, GPT_BYTE_STRIDE
copy_stack_var_to_globals ax, GPT_ENTRIES_PER_SECTOR
copy_stack_var_to_globals ax, GPT_CURRENT_ENTRY_IDX
copy_stack_var_to_globals ax, GPT_SECTOR_ENTRY_IDX
copy_stack_var_to_globals ax, GPT_SECTORS_LOADED
copy_stack_var_to_globals ax, GPT_CURRENT_LBA
copy_stack_var_to_globals ax, BOOT1_GPT_ENTRY_ADDR
; Reset the stack, now we've got everything we need from it.
mov sp, bp
mov si, [GLOBALS + BOOT1_GPT_ENTRY_ADDR]
mov eax, [si + 0x20] ; Partition / boot1 start LBA lower
mov ebx, [si + 0x24] ; Partition / boot1 start LBA upper
mov ecx, [si + 0x28] ; Partition end LBA lower
mov edx, [si + 0x32] ; Partition LBA upper
; Panic if the partition / boot1 starting LBA overflows 16 bits.
or ebx, ebx
jnz panic_simple
ror eax, 16
or ax, ax
jnz panic_simple
ror eax, 16
; Calculate the boot1 end LBA and panic if it overflows 16 bits.
; n.b. ebx is zero before this so both bx and ebx can be used as the boot1 end LBA.
mov bx, ax
add bx, boot1_bin_sectors
jc panic_simple
; Panic if the boot1 end LBA is after the partition end LBA.
; If the upper 32 bits of the partition end LBA are nonzero, then it must be greater than our
; 16-bit boot1 end LBA.
or edx, edx
jnz .end_lba_ok
; Compare the boot1 end LBA to the lower 32 bits of the partition end LBA.
cmp ebx, ecx
ja panic_simple
.end_lba_ok:
; The first sector has already been loaded (we're running it right now!) so increment the
; current LBA.
inc ax
push ax ; Current LBA
push bx ; boot1 end LBA
mov ebx, BOOT1_LOADPOINT + 512 ; Current sector load address
.self_load_loop:
mov ax, [bp - 0x02] ; Load current LBA
cmp word [bp - 0x04], ax ; Compare to boot1 end LBA
jb .self_load_done
mov ecx, ebx
call read_sector
jc panic_simple
add ebx, 512
inc word [bp - 0x02]
jmp .self_load_loop
.self_load_done:
; Check the magic bytes at the end of boot1.
push es
mov ebx, boot1_magic
call addr32_to_addr16
cmp dword es:[bx], BOOT1_MAGIC
pop es
jne panic_simple
jmp prelude_main
; Converts a 32-bit address to a 16-bit sector and offset.
; Arguments:
; - ebx: 32-bit address
; Return:
; - es: 16-bit address segment (unchanged on failure)
; - ebx: 16-bit address offset
; - cf: unset on success, set on failure
; Clobber: none
addr32_to_addr16:
fnstart
push es
push eax
mov eax, ebx
; Divide addr by 16 and saturate to 16 bits to get the segment.
shr eax, 4
ror eax, 16
or ax, ax
jz .segment_ok
mov eax, 0xffff0000
.segment_ok:
ror eax, 16
mov es, ax
; Calculate offset = addr - (16 * segment), failing if the offset doesn't fit in 16 bits.
shl eax, 4
sub ebx, eax
ror ebx, 16
or bx, bx
jnz .fail
ror ebx, 16
pop eax
add sp, 2 ; Discard the original es from the stack
pop bp
clc
ret
.fail:
pop eax
pop es
stc
fnret
; Reads a single sector at the given LBA into memory.
; Arguments:
; - ax: start LBA
; - ecx: address to read sector to
; Return:
; - cf: unset on success, set on failure
; Clobber: eax, ecx, edx
read_sector:
; sector - 1 = LBA % sectors_per_track
; temp = LBA / sectors_per_track
; head = temp % n_heads
; cylinder = temp / n_heads
fnstart
push es
push ebx
mov ebx, ecx
call addr32_to_addr16
jc .return
; Calculate sector and temp
xor dx, dx
; Divide by sectors per track. dx = mod (sector - 1), ax = div (temp)
div word [GLOBALS + SECTORS_PER_TRACK]
; Put the sector into cx (the bios call will use cl)
mov cx, dx
inc cx
; Calculate head and cylinder
xor dx, dx
; Divide by number of heads. dx = mod (head), ax = div (cylinder)
div word [GLOBALS + N_HEADS]
mov dh, dl
mov ch, al
mov dl, byte [GLOBALS + BOOT_DRIVE]
mov ah, 0x02
mov al, 1
; Read sector
int 0x13
.return:
pop ebx
pop es
fnret
panic_simple:
mov ax, 0x0003
int 0x10
mov word fs:[0x0000], 0x4f21
.halt:
hlt
jmp .halt
%if ($ - $$) > 512
%error "boot1 self-loader exceeded sector size"
%endif
; Check whether the A20 line is enabled. Writes to the boot sector identifier.
; Arguments: none
; Return:
; - ax: 0 if A20 disabled, nonzero if A20 enabled
; Clobber: none
test_a20:
push bp
mov bp, sp
push gs
; Restore the boot sector identifier in case it was overwritten by anything.
mov word [0x7dfe], 0xaa55
mov ax, 0xffff
mov gs, ax
xor ax, ax
; If the word at 0x107dfe (1 MiB after the boot sector identifier) is different to the boot
; sector identifier, than A20 must be enabled.
cmp word gs:[0x7e0e], 0xaa55
setne al
jne .return
; Even if A20 was enabled, the two words may have been equal by chance, so we temporarily swap
; the boot sector identifier bytes and test again.
ror word [0x7dfe], 8
cmp word gs:[0x7e0e], 0x55aa
setne al
ror word [0x7dfe], 8
jmp .return
.return:
pop gs
pop bp
ret
; Wait for the Intel 8042 input buffer to become empty, so we can write.
; Arguments: none
; Return: none
; Clobber: al
intel_8042_wait_write:
.loop:
; Read the 8042 status register.
in al, INTEL_8042_IN_STATUS
; Input buffer status flag set means the input buffer is full, so loop in this case.
test al, INTEL_8042_STATUS_MASK_IBUF
jnz .loop
ret
; Wait for the Intel 8042 output buffer to become filled, so we can read.
; Arguments: none
; Return: none
; Clobber: al
intel_8042_wait_read:
.loop:
; Read the 8042 status register.
in al, INTEL_8042_IN_STATUS
; Output buffer status flag unset means output buffer is empty, so loop in this case.
test al, INTEL_8042_STATUS_MASK_OBUF
jz .loop
ret
; Try to enable A20 using the Intel 8042 PS/2 keyboard controller.
; Arguments: none
; Return: none
; Clobber: ax, cx, dx
enable_a20_intel_8042:
; Temporarily disable the keyboard.
call intel_8042_wait_write
mov al, INTEL_8042_CMD_PS2_1_DISABLE
out INTEL_8042_OUT_CMD, al
; Read the controller output port.
call intel_8042_wait_write
mov al, INTEL_8042_CMD_CONTROLLER_OUT_PORT_READ
out INTEL_8042_OUT_CMD, al
call intel_8042_wait_read
in al, INTEL_8042_IO_DATA
; The second bit is "A20 enabled", so set it.
mov cl, al
or cl, 2
; Write the modified byte back to the controller output port.
call intel_8042_wait_write
mov al, INTEL_8042_CMD_CONTROLLER_OUT_PORT_WRITE
out INTEL_8042_OUT_CMD, al
call intel_8042_wait_write
mov al, cl
out INTEL_8042_IO_DATA, al
; Re-enable the keyboard.
call intel_8042_wait_write
mov al, INTEL_8042_CMD_PS2_1_ENABLE
out INTEL_8042_OUT_CMD, al
; Wait for writes to finish.
call intel_8042_wait_write
ret
prelude_main:
call test_a20
test al, al
jnz .a20_enabled
; Try to enable A20 using the Intel 8042 PS/2 keyboard controller.
call enable_a20_intel_8042
call test_a20
test al, al
jnz .a20_enabled
; TODO: try other methods first before we panic:
; - [ ] BIOS interrupt
; - [ ] Fast A20 enable
jmp panic_simple
.a20_enabled:
mov ax, 0x0003
int 0x10
; Disable cursor
mov ax, 0x0100
mov cx, 0x3f00
int 0x10
; Ensure interrupts are definitely disabled.
cli
; Load our flat-address-space GDT.
lgdt [gdt_flat_slice]
; Set the protected-mode bit in cr0.
mov eax, cr0
or al, 0x01
mov cr0, eax
; Long jump to set the code segment to gdt_flat.segment_code, and to clear the instruction
; pipeline.
jmp GDT_FLAT_IDX_CODE_32:.protected_mode_32
[bits 32]
.protected_mode_32:
; Set the data segments to gdt_flat.segment_data.
mov eax, GDT_FLAT_IDX_DATA
mov ds, eax
mov es, eax
mov fs, eax
mov gs, eax
mov ss, eax
; Reset the stack.
mov ebp, STACK_BASE
mov esp, ebp
jmp _start
jmp panic_simple
+213
View File
@@ -0,0 +1,213 @@
use std::{env, ffi::{OsStr, OsString}, fmt, fs, io, path::{Path, PathBuf}, process::{self, Command}};
fn main() {
let out_dir = env::var_os("OUT_DIR")
.expect("OUT_DIR not set");
let out_dir = PathBuf::from(out_dir);
let search_path = SearchPath::load();
let nasm_path = search_path.search("nasm")
.next()
.expect("failed to find nasm in PATH");
let nasm = Nasm::new(nasm_path);
build_asm(&nasm, &out_dir);
emit_link_args();
rerun_if_changed("build.rs".as_ref());
}
fn emit_link_args() {
let linker_script_path = "link.ld";
println!("cargo::rustc-link-arg=-T{}", linker_script_path);
rerun_if_changed(linker_script_path.as_ref());
}
fn rerun_if_changed(path: &Path) {
let path_str = path.to_str()
.expect("expected path to be valid utf8");
println!("cargo::rerun-if-changed={}", path_str);
}
fn link_obj(path: &Path) {
let path_str = path.to_str()
.expect("expected path to be valid utf8");
println!("cargo::rustc-link-arg={}", path_str);
}
fn build_asm(nasm: &Nasm, out_dir: &Path) {
let asm_srcs = fs::read_dir("asm")
.expect("failed to get asm sources");
for asm_src in asm_srcs {
let asm_src = asm_src.expect("failed to get asm source");
let ty = asm_src.file_type().expect("failed to get file type");
if !ty.is_file() {
continue;
}
let src_path = asm_src.path();
let is_asm = src_path
.extension()
.map(|ext| ext == "s")
.unwrap_or(false);
if !is_asm {
continue;
}
let out_filename = src_path
.file_name()
.unwrap()
.apply(PathBuf::from)
.with_extension("o");
let out_path = out_dir.join(out_filename);
nasm.assemble(
&out_path,
&[&src_path],
&["../include".as_ref()]
).expect("failed to assemble");
link_obj(&out_path);
}
}
struct Nasm {
bin_path: PathBuf,
}
impl Nasm {
fn new(bin_path: PathBuf) -> Self {
Self { bin_path }
}
fn assemble(&self, output: &Path, sources: &[&Path], includes: &[&Path]) -> Result<(), CmdError>
{
for source in sources {
rerun_if_changed(source);
}
let mut cmd = Command::new(&self.bin_path);
cmd
.arg("-Werror")
.arg("-f")
.arg("elf");
for include in includes {
let mut buf = OsString::new();
buf.push("-I");
buf.push(include);
cmd.arg(buf);
}
cmd
.arg("-o")
.arg(output)
.args(sources);
run_cmd(&mut cmd)?;
Ok(())
}
}
struct SearchPath {
paths: Vec<PathBuf>
}
impl SearchPath {
fn load() -> Self {
let path_var = env::var_os("PATH").unwrap_or_default();
let paths = env::split_paths(&path_var).collect();
Self { paths }
}
fn search<'a, 'b, 'c, T>(&'a self, bin: &'b T) -> impl Iterator<Item = PathBuf> + 'c
where
'a: 'c,
'b: 'c,
T: AsRef<OsStr> + ?Sized,
{
let bin = bin.as_ref();
self.paths
.iter()
.filter_map(move |path| {
let path = path.join(bin);
fs::metadata(&path)
.ok()
.and_then(|meta| if meta.is_file() || meta.is_symlink() {
Some(path)
} else {
None
})
})
}
}
fn run_cmd(cmd: &mut Command) -> Result<process::Output, CmdError> {
use fmt::Write;
cmd
.output()
.map_err(CmdErrorKind::Io)
.and_then(|out| if out.status.success() {
Ok(out)
} else {
Err(CmdErrorKind::Status(out))
})
.map_err(|err| {
let mut cmd_buf = String::new();
write!(&mut cmd_buf, "{:?}", cmd).ok();
CmdError::new(cmd_buf, err)
})
}
#[derive(Debug)]
struct CmdError {
cmd: String,
kind: CmdErrorKind,
}
impl CmdError {
fn new(cmd: String, kind: CmdErrorKind) -> Self {
Self { cmd, kind }
}
}
impl fmt::Display for CmdError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "`{}` failed: ", self.cmd)?;
match &self.kind {
CmdErrorKind::Io(err) => err.fmt(f),
CmdErrorKind::Status(out) => write!(f, "exited with status {}", out.status),
}
}
}
#[derive(Debug)]
enum CmdErrorKind {
Io(io::Error),
Status(process::Output),
}
trait Apply: Sized {
fn apply<T, F>(self, f: F) -> T
where
F: FnOnce(Self) -> T;
}
impl<U> Apply for U
where
U: Sized,
{
fn apply<T, F>(self, f: F) -> T
where
F: FnOnce(Self) -> T
{
f(self)
}
}
+43
View File
@@ -0,0 +1,43 @@
OUTPUT_FORMAT("binary")
. = 0x8200;
SECTIONS {
.prelude : {
KEEP(*(.prelude))
*(.prelude)
}
.text : {
*(.text)
*(.text.*)
}
.data : {
*(.data)
*(.data.*)
}
.bss : {
*(.bss)
*(.bss.*)
}
.rodata : {
*(.rodata)
*(.rodata.*)
}
.magic : {
/* Magic bytes the prelude uses to make sure it's loaded the subsequent sectors correctly. */
LONG(0x544e4150)
}
boot1_magic = ADDR(.magic);
/* Define a symbol for the total length of the binary, so the prelude knows how many blocks to
* load from disk.
*/
boot1_bin_len = . - 0x8200;
boot1_bin_sectors = (boot1_bin_len + 511) / 512;
}
+72
View File
@@ -0,0 +1,72 @@
#![no_std]
#![no_main]
mod spin;
mod vga;
use core::{arch::asm, panic::PanicInfo, fmt::Write};
#[repr(C)]
#[derive(Clone, Debug)]
struct BiosIntr {
eax: u32,
ebx: u32,
ecx: u32,
edx: u32,
esi: u32,
edi: u32,
ds: u16,
es: u16,
eflags: u32,
}
unsafe extern "C" {
unsafe fn _bios_call(intr: u32, args: *mut BiosIntr);
}
#[panic_handler]
fn panic(info: &PanicInfo) -> ! {
vga_println!("panic!");
if let Some(location) = info.location() {
vga_println!("{}", location);
}
vga_println!("{}", info.message());
hlt()
}
#[no_mangle]
pub extern "C" fn _start() -> ! {
vga::vga_init();
vga_println!("hello from rust");
let mut args = BiosIntr {
eax: 0xe820,
ebx: 0,
ecx: 24,
edx: 0x534d4150,
esi: 0,
edi: 0x6a00,
ds: 0,
es: 0,
eflags: 0,
};
unsafe {
_bios_call(0x15, &raw mut args);
}
vga_println!("eax = {:x}", args.eax);
hlt()
}
#[inline]
fn hlt() -> ! {
loop {
unsafe {
asm!("hlt");
}
}
}
+101
View File
@@ -0,0 +1,101 @@
use core::{cell::UnsafeCell, hint, ops::{Deref, DerefMut}, sync::atomic::{AtomicBool, Ordering}};
pub struct Spinlock<T> {
data: UnsafeCell<T>,
locked: AtomicBool,
}
impl<T> Spinlock<T> {
pub const fn new(data: T) -> Self {
Self {
data: UnsafeCell::new(data),
locked: AtomicBool::new(false),
}
}
pub fn lock(&self) -> SpinlockGuard<T> {
// If we observe `locked` was `false`, then:
// - Use acquire ordering, so nothing inside the critical section gets reordered before we
// observed the `false` value.
// - Store `true`, so nothing else can enter the critical section until we exit it.
// Otherwise, spin until we observe a `false` value.
while self.locked
.compare_exchange_weak(false, true, Ordering::Acquire, Ordering::Relaxed)
.is_err()
{
hint::spin_loop();
}
SpinlockGuard { lock: self }
}
/// # Safety
/// There must be no "active" `SpinlockGuards` for this lock, i.e. a `SpinlockGuard` which can be
/// used to obtain a reference to the spinlock-protected data.
unsafe fn unlock(&self) {
// Unset `locked` with release ordering so that nothing inside the critical section gets
// reordered to after we stored `false`.
self.locked.store(false, Ordering::Release);
}
/// # Safety
/// No mutable references to the spinlock-protected data may exist.
unsafe fn get<'s, 'a>(&'s self) -> &'a T
where
's: 'a,
{
unsafe { &*self.data.get() }
}
/// # Safety
/// No references to the spinlock-protected data may exist.
unsafe fn get_mut<'s, 'a>(&'s self) -> &'a mut T
where
's: 'a,
{
unsafe { &mut *self.data.get() }
}
}
unsafe impl<T> Sync for Spinlock<T>
where
T: Send,
{}
pub struct SpinlockGuard<'a, T> {
lock: &'a Spinlock<T>,
}
impl<'a, T> Deref for SpinlockGuard<'a, T> {
type Target = T;
#[inline]
fn deref(&self) -> &Self::Target {
// SAFETY:
// For the entire lifetime of the `SpinlockGuard`, `locked` remains `true`, so we have
// exclusive access to `data`, so no mutable references to `data` can exist.
unsafe { self.lock.get() }
}
}
impl<'a, T> DerefMut for SpinlockGuard<'a, T> {
#[inline]
fn deref_mut(&mut self) -> &mut Self::Target {
// SAFETY:
// For the entire lifetime of the `SpinlockGuard`, `locked` remains `true`, so we have
// exclusive access to `data`, so no other references to `data` can exist.
unsafe { self.lock.get_mut() }
}
}
impl<'a, T> Drop for SpinlockGuard<'a, T> {
fn drop(&mut self) {
// SAFETY:
// Only one `SpinlockGuard` can exist at a time for a particular lock, since we set `locked`
// to true before creating a guard and refuse to create any new ones until it is `false` again.
// Therefore, we are the only `SpinlockGuard` for the lock. Since this is the destructor, and
// we don't access the spinlock-protected data here, there are therefore no "active"
// `SpinlockGuard`s remaining for the lock.
unsafe { self.lock.unlock() }
}
}
+128
View File
@@ -0,0 +1,128 @@
use core::{fmt, ptr};
use crate::spin::Spinlock;
const VGA_WIDTH: usize = 80;
const VGA_HEIGHT: usize = 25;
const COLOUR_MASK: u16 = 0x0a00;
pub static VGA: Spinlock<Option<VgaBuf>> = Spinlock::new(None);
#[macro_export]
macro_rules! vga_print {
($($args:tt)*) => ({
crate::vga::with_vga_buf(|vga_buf| {
::core::write!(vga_buf, $($args)*).ok();
});
})
}
#[macro_export]
macro_rules! vga_println {
($($args:tt)*) => ({
crate::vga::with_vga_buf(|vga_buf| {
::core::writeln!(vga_buf, $($args)*).ok();
});
})
}
pub fn vga_init() {
let vga_buf = unsafe { VgaBuf::new(0xb8000 as *mut u16) };
let mut guard = VGA.lock();
*guard = Some(vga_buf);
}
pub fn with_vga_buf<F>(f: F)
where
F: FnOnce(&mut VgaBuf),
{
let mut guard = crate::vga::VGA.lock();
let vga = guard.as_mut().expect("vga not initialised");
f(vga);
}
pub struct VgaBuf {
buf: *mut u16,
col: usize,
row: usize,
}
impl VgaBuf {
pub unsafe fn new(buf: *mut u16) -> Self {
Self { buf, col: 0, row: 0 }
}
pub fn vga_write_str(&mut self, s: &str) {
for c in s.chars() {
self.vga_write_char(c);
}
}
pub fn vga_write_char(&mut self, c: char) {
let newline = c == '\n';
if newline || self.col >= VGA_WIDTH {
self.col = 0;
self.row += 1;
}
if self.row >= VGA_HEIGHT {
self.scroll();
self.row -= 1;
}
if !newline {
self.vga_write_char_at(c, self.col, self.row);
self.col += 1;
}
}
pub fn vga_write_ascii_char_at(&mut self, c: u8, col: usize, row: usize) {
let vga_val = COLOUR_MASK | u16::from(c);
if col < VGA_WIDTH && row < VGA_HEIGHT {
unsafe {
self.coord_ptr(col, row)
.write_volatile(vga_val);
}
}
}
pub fn vga_write_char_at(&mut self, c: char, col: usize, row: usize) {
let c = u8::try_from(c).unwrap_or(0xfe);
self.vga_write_ascii_char_at(c, col, row);
}
fn scroll(&mut self) {
unsafe {
ptr::copy(
self.coord_ptr(0, 1),
self.coord_ptr(0, 0),
VGA_WIDTH * (VGA_HEIGHT - 1)
);
for col in 0..VGA_WIDTH {
self.vga_write_ascii_char_at(0, col, VGA_HEIGHT - 1);
}
}
}
unsafe fn coord_ptr(&self, col: usize, row: usize) -> *mut u16 {
unsafe { self.buf.add((row * VGA_WIDTH) + col) }
}
}
impl fmt::Write for VgaBuf {
fn write_str(&mut self, s: &str) -> fmt::Result {
self.vga_write_str(s);
Ok(())
}
fn write_char(&mut self, c: char) -> fmt::Result {
self.vga_write_char(c);
Ok(())
}
}
unsafe impl Send for VgaBuf {}
+16
View File
@@ -0,0 +1,16 @@
{
"arch": "x86",
"os": "none",
"llvm-target": "i686-unknown-none",
"data-layout": "e-m:e-p:32:32-p270:32:32-p271:32:32-p272:64:64-i128:128-f64:32:64-f80:32-n8:16:32-S128",
"target-endian": "little",
"target-pointer-width": "32",
"target-c-int-width": "32",
"executables": true,
"linker-flavor": "ld.lld",
"linker": "rust-lld",
"panic-strategy": "abort",
"disable-redzone": true,
"features": "-mmx,-sse,+soft-float"
}
+7
View File
@@ -0,0 +1,7 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 3
[[package]]
name = "buildtools"
version = "0.1.0"
+6
View File
@@ -0,0 +1,6 @@
[package]
name = "buildtools"
version = "0.1.0"
edition = "2021"
[dependencies]
+109
View File
@@ -0,0 +1,109 @@
use std::{ffi::OsString, path::{Path, PathBuf}, process::Command};
#[derive(Clone)]
pub struct Nasm {
bin_path: PathBuf,
includes: Vec<PathBuf>,
warnings: Vec<String>,
werror: bool,
out_format: Option<String>,
}
impl Nasm {
pub fn new(bin_path: PathBuf) -> Self {
Self {
bin_path,
includes: Vec::new(),
warnings: Vec::new(),
werror: true,
out_format: None,
}
}
pub fn include<T, I>(self, paths: I) -> Self
where
PathBuf: From<T>,
I: IntoIterator<Item = T>,
{
Self {
includes: {
let mut updated_includes = self.includes;
updated_includes.extend(paths.into_iter().map(From::from));
updated_includes
},
..self
}
}
pub fn warnings<T, I>(self, warnings: I) -> Self
where
String: From<T>,
I: IntoIterator<Item = T>,
{
Self {
warnings: {
let mut updated_warnings = self.warnings;
updated_warnings.extend(warnings.into_iter().map(From::from));
updated_warnings
},
..self
}
}
pub fn werror(self, enabled: bool) -> Self {
Self {
werror: enabled,
..self
}
}
pub fn out_format<T>(self, format: T) -> Self
where
String: From<T>,
{
Self {
out_format: Some(From::from(format)),
..self
}
}
// TODO: make this generic over sources & path types
pub fn to_cmd(&self, output: &Path, sources: &[&Path]) -> Command {
let mut cmd = self.to_common_cmd();
cmd
.arg("-o")
.arg(output)
.args(sources);
cmd
}
fn to_common_cmd(&self) -> Command {
let mut cmd = Command::new(&self.bin_path);
if let Some(format) = self.out_format.as_ref() {
cmd.arg("-f").arg(format);
}
for include in self.includes.iter() {
let mut buf = OsString::new();
buf.push("-I");
buf.push(include);
cmd.arg(buf);
}
for warning in self.warnings.iter() {
let mut buf = OsString::new();
buf.push("-w+");
buf.push(warning);
cmd.arg(buf);
}
if self.werror {
cmd.arg("-werror");
}
cmd
}
}
+10
View File
@@ -0,0 +1,10 @@
# Calling convention
## boot0
I'm not sticking to any particular calling convention for boot0, since we have to golf to fit in
440 bytes. Whatever's most convenient.
## boot1
- Arguments: ax, cx, dx, stack
- Return value: ax, cf for booleans
- ax may be clobbered. All other registers are preserved
- Callee cleanup (i.e. the function pops stack arguments when returning)
+37
View File
@@ -0,0 +1,37 @@
# Physical memory layout
## Low memory
| Type | Range | |
|----------|---------------------|-------------------------------------------------|
| Reserved | 0x000000 - 0x000400 | real-mode interrupt vector table |
| Reserved | 0x000400 - 0x000500 | bios data area |
| Usable | 0x000500 - 0x004000 | main stack |
| Usable | 0x004000 - 0x006a00 | globals |
| Usable | 0x006a00 - 0x007c00 | memory map |
| Usable | 0x007c00 - 0x007e00 | boot sector |
| Usable | 0x007e00 - 0x080000 | conventional usable memory |
| Reserved | 0x080000 - 0x0a0000 | extended bios data area (maximum possible size) |
| Reserved | 0x0a0000 - 0x0c0000 | video memory |
| Reserved | 0x0c0000 - 0x0c8000 | video bios |
| Reserved | 0x0c8000 - 0x0f0000 | bios expansions |
| Reserved | 0x0f0000 - 0x100000 | motherboard bios |
### Allocations
- 0x00500 - 0x04000: stage 1/2 stack
- 0x04000 - 0x06a00: globals
- 0x07c00 - 0x07e00: stage 1 text
- 0x07e00 - 0x08000: gpt partition header
- 0x08000 - 0x08200: stage 2 partition table entry
- 0x08200 - 0x0c000: stage 2 text, stage 3 stack
- 0x0e000 : gdt
- 0x10000 : stage 3 text
0x10000: stage 3
TODO: once we're in real mode, repurpose s2 for a stack
TODO: load s3 into a separate memory region
TODO: use some fixed known memory address for the GDT, rather than putting it in stage 2.
That way, we can safely overwrite stage 2 once we're done with it.
+41
View File
@@ -0,0 +1,41 @@
QEMU emulated hardware:
- i440fx northbridge
- National Semiconductor 16550a UART
```asm
[bits 16]
[org 0xff000]
times (0xff0 - ($ - $$)) db 0x00
mov eax, 0xcafeface
hlt
times (0x2000 - ($ - $$)) db 0xf4
```
```sh
qemu-system-x86_64 \
-monitor stdio \
-no-reboot \
-m 512M \
-drive if=pflash,file=reset.bin,format=raw
```
- The BIOS flash is mapped in its entirety to a board-specific address. Here it looks like the
right edge is always 00000000ffffffff, and it expands to the left as the size of the flash
increases.
- The last 4096 bytes of flash are mapped to ff000 as well.
```
x/4096xb 0x00000000fffff000
```
Left edge moves left as we add more to the ROM image.
Last 4096 bytes of the ROM image are also mapped to 0xff000.
```
info mtree
00000000ffffe000-00000000ffffffff (prio 0, romd): system.flash0
```
+8
View File
@@ -0,0 +1,8 @@
[package]
name = "elf"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
+349
View File
@@ -0,0 +1,349 @@
use core::fmt;
use std::{char, env, fs};
fn main() {
let mut args = env::args().skip(1);
let path = args.next().unwrap();
let bytes = fs::read(path).unwrap();
let elf = Elf::parse(&bytes).unwrap();
}
#[derive(Clone)]
struct InputBytes<'a> {
bytes: &'a [u8],
}
impl<'a> InputBytes<'a> {
fn new(bytes: &'a [u8]) -> Self {
Self { bytes }
}
fn new_offset(bytes: &'a [u8], offset: usize) -> Self {
Self::new(bytes).advanced(offset)
}
fn prefix_len(&self, n: usize) -> usize {
self.bytes.len().min(n)
}
fn advanced(&self, n: usize) -> Self {
Self {
bytes: &self.bytes[self.prefix_len(n)..],
}
}
fn advance(&mut self, n: usize) -> &mut Self {
self.bytes = &self.bytes[self.prefix_len(n)..];
self
}
fn peek(&self, n: usize) -> Result<&'a [u8], ParseError> {
self.bytes.get(..n).ok_or(ParseError::UnexpectedEof)
}
fn pop(&mut self, n: usize) -> Result<&'a [u8], ParseError> {
let res = self.peek(n);
if res.is_ok() {
self.advance(n);
}
res
}
fn pop_arr<const N: usize>(&mut self) -> Result<[u8; N], ParseError> {
self.pop(N).map(|bs| <[u8; N]>::try_from(bs).unwrap())
}
fn pop_u8(&mut self) -> Result<u8, ParseError> {
self.pop_arr::<1>().map(|[x]| x)
}
fn pop_u16(&mut self, endianness: Endianness) -> Result<u16, ParseError> {
let bytes = self.pop_arr::<2>()?;
Ok(endianness.read_u16(bytes))
}
fn pop_u32(&mut self, endianness: Endianness) -> Result<u32, ParseError> {
let bytes = self.pop_arr::<4>()?;
Ok(endianness.read_u32(bytes))
}
fn pop_u64(&mut self, endianness: Endianness) -> Result<u64, ParseError> {
let bytes = self.pop_arr::<8>()?;
Ok(endianness.read_u64(bytes))
}
fn pop_word(&mut self, endianness: Endianness, width: Width) -> Result<u64, ParseError> {
match width {
Width::Bits32 => self.pop_u32(endianness).map(u64::from),
Width::Bits64 => self.pop_u64(endianness),
}
}
fn pop_word_usize(&mut self, endianness: Endianness, width: Width) -> Result<usize, ParseError> {
self.pop_word(endianness, width)
.and_then(|x| usize::try_from(x).map_err(|_| ParseError::OffsetOutOfBounds))
}
fn hexdump(&self, n: usize) {
print!("{: <8}", "");
for i in 0..16 {
print!(" {:x}", i);
}
println!();
for (i, chunk) in self.bytes[.. n.min(self.bytes.len())].chunks(16).enumerate() {
print!("{:08x}", i * 16);
for b in chunk {
print!(" {:02x}", b);
}
print!("{: <1$}", "", 4 + 3 * (16 - chunk.len()));
for b in chunk {
let c = match char::from(*b) {
c if c.is_ascii_graphic() => c,
_ => '.',
};
print!("{}", c);
}
println!();
}
}
}
struct Elf<'a> {
elf_bytes: &'a [u8],
bl: ByteLayout,
header_version: u8,
abi: u8,
ty: ElfType,
instruction_set: Option<InstructionSet>,
elf_version: u32,
}
impl<'a> Elf<'a> {
fn parse(bytes: &'a [u8]) -> Result<Self, ElfError> {
let mut hdr = InputBytes::new(bytes);
hdr.hexdump(64);
let magic = hdr.pop(4)?;
if magic != &[0x7f, b'E', b'L', b'F'] {
return Err(ElfError::BadMagic);
}
let width = match hdr.pop_u8()? {
1 => Width::Bits32,
2 => Width::Bits64,
_ => return Err(ElfError::UnsupportedValue),
};
let endianness = match hdr.pop_u8()? {
1 => Endianness::Little,
2 => Endianness::Big,
_ => return Err(ElfError::UnsupportedValue),
};
let bl = ByteLayout {
endianness,
width,
};
let header_version = hdr.pop_u8()?;
let abi = hdr.pop_u8()?;
hdr.pop(8)?;
let ty = match hdr.pop_u16(endianness)? {
1 => ElfType::Relocatable,
2 => ElfType::Executable,
3 => ElfType::Shared,
4 => ElfType::Core,
_ => return Err(ElfError::UnsupportedValue),
};
let instruction_set = match hdr.pop_u16(endianness)? {
0 => None,
0x02 => Some(InstructionSet::Sparc),
0x03 => Some(InstructionSet::I386),
0x08 => Some(InstructionSet::Mips),
0x14 => Some(InstructionSet::PowerPc),
0x28 => Some(InstructionSet::Arm),
0x2a => Some(InstructionSet::SuperH),
0x32 => Some(InstructionSet::Ia64),
0x3e => Some(InstructionSet::Amd64),
0xb7 => Some(InstructionSet::Aarch64),
0xf3 => Some(InstructionSet::RiscV),
_ => return Err(ElfError::UnsupportedValue),
};
let elf_version = hdr.pop_u32(endianness)?;
let entry_offset = hdr.pop_word(endianness, width)?;
let pht_offset = hdr.pop_word_usize(endianness, width)?;
let sht_offset = hdr.pop_word_usize(endianness, width)?;
let flags = hdr.pop_u32(endianness)?;
let header_size = hdr.pop_u16(endianness)?;
let pht_entry_size = hdr.pop_u16(endianness)?;
let pht_len = hdr.pop_u16(endianness)?;
let sht_entry_size = hdr.pop_u16(endianness)?;
let sht_len = hdr.pop_u16(endianness)?;
let shstr_idx = hdr.pop_u16(endianness)?;
dbg!(entry_offset);
dbg!(pht_offset);
dbg!(sht_offset);
dbg!(flags);
dbg!(header_size);
dbg!(pht_entry_size);
dbg!(pht_len);
dbg!(sht_entry_size);
dbg!(sht_len);
dbg!(shstr_idx);
// TODO
let shstr = SectionHeader::parse(bl,
InputBytes::new_offset(bytes, sht_offset + usize::from(sht_entry_size * shstr_idx)))?;
let str_table = InputBytes::new_offset(bytes, shstr.offset);
str_table.hexdump(shstr.size);
Ok(Self {
elf_bytes: bytes,
bl,
header_version,
abi,
ty,
instruction_set,
elf_version,
})
}
}
struct SectionHeader {
name: u32,
// FIXME: parse type
ty: u32,
flags: u64,
addr: u64,
offset: usize,
size: usize,
link: u32,
info: u32,
align: u64,
ent_size: usize,
}
impl SectionHeader {
fn parse(bl: ByteLayout, mut bytes: InputBytes) -> Result<Self, ElfError> {
let name = bytes.pop_u32(bl.endianness)?;
let ty = bytes.pop_u32(bl.endianness)?;
let flags = bytes.pop_word(bl.endianness, bl.width)?;
let addr = bytes.pop_word(bl.endianness, bl.width)?;
let offset = bytes.pop_word_usize(bl.endianness, bl.width)?;
let size = bytes.pop_word_usize(bl.endianness, bl.width)?;
let link = bytes.pop_u32(bl.endianness)?;
let info = bytes.pop_u32(bl.endianness)?;
let align = bytes.pop_word(bl.endianness, bl.width)?;
let ent_size = bytes.pop_word_usize(bl.endianness, bl.width)?;
Ok(Self {
name,
ty,
flags,
addr,
offset,
size,
link,
info,
align,
ent_size,
})
}
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
struct ByteLayout {
endianness: Endianness,
width: Width,
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum Width {
Bits32,
Bits64,
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum Endianness {
Little,
Big,
}
impl Endianness {
fn read_u16(self, bytes: [u8; 2]) -> u16 {
match self {
Self::Little => u16::from_le_bytes(bytes),
Self::Big => u16::from_be_bytes(bytes),
}
}
fn read_u32(self, bytes: [u8; 4]) -> u32 {
match self {
Self::Little => u32::from_le_bytes(bytes),
Self::Big => u32::from_be_bytes(bytes),
}
}
fn read_u64(self, bytes: [u8; 8]) -> u64 {
match self {
Self::Little => u64::from_le_bytes(bytes),
Self::Big => u64::from_be_bytes(bytes),
}
}
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum ElfType {
Relocatable,
Executable,
Shared,
Core,
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum InstructionSet {
Sparc,
I386,
Mips,
PowerPc,
Arm,
SuperH,
Ia64,
Amd64,
Aarch64,
RiscV,
}
#[derive(Debug)]
enum ElfError {
BadMagic,
UnexpectedEof,
OffsetOutOfBounds,
UnsupportedValue,
}
impl From<ParseError> for ElfError {
fn from(value: ParseError) -> Self {
match value {
ParseError::UnexpectedEof => Self::UnexpectedEof,
ParseError::OffsetOutOfBounds => Self::OffsetOutOfBounds,
}
}
}
#[derive(Debug)]
enum ParseError {
UnexpectedEof,
OffsetOutOfBounds,
}
+64
View File
@@ -0,0 +1,64 @@
%define BOOT0_LOADPOINT 0x7c00
%define BOOT1_LOADPOINT 0x8200
%define MEMMAP 0x6a00
%define MEMMAP_END BOOT0_LOADPOINT
%define MEMMAP_ENT_SIZE 32
%define MEMMAP_CAP ((MEMMAP_END - MEMMAP) / MEMMAP_ENT_SIZE)
%define GLOBALS 0x4000
%define GLOBALS_END MEMMAP
%define STACK_BASE GLOBALS
%define EBDA_START 0x080000
%define VGA_SEG 0xb800
%define BOOT1_MAGIC 0x544e4150
%define VGA_WIDTH 80
%define VGA_HEIGHT 25
; ASCII string "SMAP", which is used by e820 as a magic number argument and return value.
%define E820_MAGIC 0x534d4150
; Size of entry returned by e820. This is less than MEMMAP_ENT_SIZE because we add some fields of
; our own.
%define E820_ENTRY_SIZE 24
%define MEMMAP_ENT_FIELD_BASE 0x00
%define MEMMAP_ENT_FIELD_LEN 0x08
%define MEMMAP_ENT_FIELD_TYPE 0x10
%define MEMMAP_ENT_FIELD_EXT 0x14
%define MEMMAP_ENT_FIELD_END 0x18
%define GDT_DESCRIPTOR_SIZE 0x08
; boot0 base stack frame variable offsets / globals
; (we use the same offsets once we copy the variables to the globals section)
; -------------------------------------------------------------------------------------------------
; The boot drive number given to us by the BIOS.
%define BOOT_DRIVE 0x02
; Boot drive geometry
%define SECTORS_PER_TRACK 0x04
%define N_HEADS 0x06
; Starting LBA of the GPT partition entries array.
%define GPT_ENTRIES_START_LBA 0x08
; Number of GPT entries, saturated to 16 bits.
%define GPT_N_ENTRIES_16 0x0a
; Number of sectors to advance by once we've read every GPT entry in the current sector.
%define GPT_SECTOR_STRIDE 0x0c
; Number of bytes to advance by in the current sector once we've read a GPT entry.
%define GPT_BYTE_STRIDE 0x0e
; Number of GPT entries which can fit in a single sector.
%define GPT_ENTRIES_PER_SECTOR 0x10
%define GPT_CURRENT_ENTRY_IDX 0x12
%define GPT_SECTOR_ENTRY_IDX 0x14
%define GPT_SECTORS_LOADED 0x16
%define GPT_CURRENT_LBA 0x18
%define BOOT1_GPT_ENTRY_ADDR 0x1a
; Globals
; ------------------------------------------------------------------------------------------------
%define VGA_COL 0x1c
%define TEXTBUF_LINE 0x1e
%define MEMMAP_ENTRIES 0x20
+14
View File
@@ -0,0 +1,14 @@
%ifndef BOOT_FN_H
%define BOOT_FN_H
%macro fnstart 0
push bp
mov bp, sp
%endmacro
%macro fnret 0
pop bp
ret
%endmacro
%endif
+38
View File
@@ -0,0 +1,38 @@
%ifndef BOOT_GLOBALS_H
%define BOOT_GLOBALS_H
; Stage 1 base stack frame variable offsets / globals
; (we use the same offsets once we copy the variables to the globals section)
; -------------------------------------------------------------------------------------------------
; The boot drive number given to us by the BIOS.
%define BOOT_DRIVE 0x02
; Boot drive geometry
%define SECTORS_PER_TRACK 0x04
%define N_HEADS 0x06
; Starting LBA of the GPT partition entries array.
%define GPT_ENTRIES_START_LBA 0x08
; Number of GPT entries, saturated to 16 bits.
%define GPT_N_ENTRIES_16 0x0a
; Number of sectors to advance by once we've read every GPT entry in the current sector.
%define GPT_SECTOR_STRIDE 0x0c
; Number of bytes to advance by in the current sector once we've read a GPT entry.
%define GPT_BYTE_STRIDE 0x0e
; Number of GPT entries which can fit in a single sector.
%define GPT_ENTRIES_PER_SECTOR 0x10
%define GPT_CURRENT_ENTRY_IDX 0x12
%define GPT_SECTOR_ENTRY_IDX 0x14
%define GPT_SECTORS_LOADED 0x16
%define GPT_CURRENT_LBA 0x18
; 2-byte address of the partition GPT entry loaded into memory.
%define STAGE_2_GPT_ENTRY_ADDR 0x1a
; Stage 2 globals
; -------------------------------------------------------------------------------------------------
; 4-byte partition end LBA.
%define LOADER_PART_END_LBA 0x1c
; 2-byte stage 2 start LBA.
%define STAGE_2_START_LBA 0x20
; 2-byte stage 2 start LBA (inclusive).
%define STAGE_2_END_LBA 0x22
%endif
+26
View File
@@ -0,0 +1,26 @@
%ifndef BOOT_LAYOUT_H
%define BOOT_LAYOUT_H
%define S1_ADDR 0x7c00
%define S2_DATA_LEN 32
%define S2_TEXT_OFFSET S2_DATA_LEN
%define S2_LOAD_ADDR 0x8200
%define S2_DATA S2_LOAD_ADDR
%define S2_ENTRYPOINT (S2_DATA_ADDR + S2_DATA_LEN)
%define GDT_FLAT_ADDR 0xe000
%define S3_LOAD_ADDR 0x10000
; %define MEMMAP 0x6a00
; %define MEMMAP_END S2_ADDR
; %define MEMMAP_ENT_SIZE 32
; %define MEMMAP_CAP ((MEMMAP_END - MEMMAP) / MEMMAP_ENT_SIZE)
%define REAL_GLOBALS 0x4000
%define REAL_GLOBALS_END 0x6a00
%define REAL_STACK_BASE REAL_GLOBALS
%define S2_MAGIC 0x544e4150
%endif
+18
View File
@@ -0,0 +1,18 @@
%ifndef BOOT_PS2_H
%define BOOT_PS2_H
%define INTEL_8042_IO_DATA 0x60
%define INTEL_8042_IN_STATUS 0x64
%define INTEL_8042_OUT_CMD 0x64
%define INTEL_8042_STATUS_BIT_OBUF 0
%define INTEL_8042_STATUS_BIT_IBUF 1
%define INTEL_8042_STATUS_MASK_OBUF (1 << INTEL_8042_STATUS_BIT_OBUF)
%define INTEL_8042_STATUS_MASK_IBUF (1 << INTEL_8042_STATUS_BIT_IBUF)
%define INTEL_8042_CMD_PS2_1_DISABLE 0xad
%define INTEL_8042_CMD_PS2_1_ENABLE 0xae
%define INTEL_8042_CMD_CONTROLLER_OUT_PORT_READ 0xd0
%define INTEL_8042_CMD_CONTROLLER_OUT_PORT_WRITE 0xd1
%endif
+8
View File
@@ -0,0 +1,8 @@
%ifndef BOOT_S2_FNS_H
%define BOOT_S2_FNS_H
extern addr32_to_addr16
extern read_sector
extern panic_simple
%endif
+48 -8
View File
@@ -1,17 +1,57 @@
include_flags := "-Iinclude"
common_flags := "-werror " + include_flags
ld32 := "ld -m elf_i386"
run: run:
qemu-system-x86_64 -drive format=raw,file=disk.bin qemu-system-x86_64 \
-monitor stdio \
-no-reboot \
-m 512M \
-drive format=raw,file=disk.bin
run_serial:
qemu-system-x86_64 \
-nographic \
-no-reboot \
-m 512M \
-drive format=raw,file=disk.bin
run_reset:
qemu-system-x86_64 \
-monitor stdio \
-no-reboot \
-m 512M \
-drive if=pflash,file=reset.bin,format=raw
build_reset:
nasm -f bin -werror -o reset.bin reset.s
#-bios seabios/out/bios.bin
build: build:
nasm -f bin -o boot0.bin boot0.s cargo xtask build
mkimg:
dd if=/dev/zero of=disk.bin bs=440 count=1 conv=notrunc
dd if=build/stage_1/s1.bin of=disk.bin conv=notrunc
dd if=build/s23.bin of=disk.bin bs=512 seek=70 conv=notrunc
zero_disk: zero_disk:
dd if=/dev/zero of=disk.bin bs=64K count=16 dd if=/dev/zero of=disk.bin bs=512 count=1000
partition_disk: partition_disk:
parted --script disk.bin mklabel gpt parted --script disk.bin mklabel gpt
parted --script disk.bin mkpart test 34s 50% parted --script disk.bin mkpart dummy1 34s 47s
parted --script disk.bin type 1 0fc63daf-8483-4772-8e79-3d69d8477de4 parted --script disk.bin type 1 e3c9e316-0b5c-4db8-817d-f92df00215ae
parted --script disk.bin mkpart dummy2 64s 65s
parted --script disk.bin type 2 e3c9e316-0b5c-4db8-817d-f92df00215ae
parted --script disk.bin mkpart dummy3 66s 67s
parted --script disk.bin type 3 e3c9e316-0b5c-4db8-817d-f92df00215ae
parted --script disk.bin mkpart dummy4 68s 69s
parted --script disk.bin type 4 e3c9e316-0b5c-4db8-817d-f92df00215ae
parted --script disk.bin mkpart dummy5 48s 63s
parted --script disk.bin type 5 0fc63daf-8483-4772-8e79-3d69d8477de4
# parted --script disk.bin mkpart stage2 70s 200s
parted --script disk.bin mkpart stage2 70s 900s
parted --script disk.bin type 6 fdffea69-3651-442f-a11d-88a09bf372dd
write_stage0:
dd if=/dev/zero of=disk.bin bs=440 count=1 conv=notrunc
dd if=boot0.bin of=disk.bin conv=notrunc
+7
View File
@@ -0,0 +1,7 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "memregion_merge"
version = "0.1.0"
+6
View File
@@ -0,0 +1,6 @@
[package]
name = "memregion_merge"
version = "0.1.0"
edition = "2021"
[dependencies]
+282
View File
@@ -0,0 +1,282 @@
// Notes:
// - Once we've got a list of usable memory, we can use some of it to store the original e820 list
// for future use. We therefore don't have to worry about storing the unavailable regions for
// now, we can do that later.
use std::array;
struct MemRegions<const N: usize> {
buf: [MemRegion; N],
len: usize,
}
impl<const N: usize> MemRegions<N> {
fn new() -> Self {
Self { buf: array::from_fn(|_| Default::default()), len: 0 }
}
fn regions(&self) -> &[MemRegion] {
&self.buf[..self.len]
}
fn push_usable(&mut self, new: MemRegion) -> bool {
let mut merged = false;
for old in &mut self.buf[..self.len] {
if old.overlaps(&new) {
old.merge(&new);
merged = true;
break;
}
}
// If we merged the new region with an existing one, we may have filled in a gap that allows
// other regions to be merged, so check if any adjacent regions can be merged.
if merged {
let mut i = 1;
while i < self.len {
if self.buf[i - 1].overlaps(&self.buf[i]) {
let (left, right) = self.buf.split_at_mut(i);
left[i - 1].merge(&right[0]);
right.rotate_left(1);
self.len -= 1;
}
else {
i += 1;
}
}
return true;
}
// If we couldn't merge the new region with any others, then place it into its sorted position
// in the regions buffer.
else {
self.push_without_merge_at(new, 0)
}
}
fn push_without_merge_at(&mut self, new: MemRegion, start_idx: usize) -> bool {
// Fail if we don't have space for the new region.
if self.len >= N {
return false;
}
let mut i = start_idx;
while i < self.len {
if new.start < self.buf[i].start {
break;
}
i += 1;
}
self.buf[self.len] = new;
self.len += 1;
self.buf[i..self.len].rotate_right(1);
true
}
// n.b. expects to be run only after all `push_usable`s are done
fn push_unusable(&mut self, unusable: MemRegion) {
let mut i = 0;
while i < self.len {
if !unusable.overlaps(&self.buf[i]) {
i += 1;
}
else {
let left_region = MemRegion::new(self.buf[i].start, unusable.start);
let right_region = MemRegion::new(unusable.end, self.buf[i].end);
// If the unusable region completely contains the usable region, remove the usable region
// entirely.
if left_region.empty() && right_region.empty() {
self.buf[i..self.len].rotate_left(1);
self.len -= 1;
}
// If the unusable region is completely contained within the usable region, then split the
// usable region in two.
else if !left_region.empty() && !right_region.empty() {
self.buf[i] = left_region;
self.push_without_merge_at(right_region, i + 1);
i += 1;
}
// Otherwise, trim the usable region.
else {
self.buf[i] = if !left_region.empty() { left_region } else { right_region };
i += 1;
}
}
}
}
}
#[derive(Clone, Default, PartialEq, Eq, Debug)]
struct MemRegion {
start: u64,
end: u64,
}
impl MemRegion {
fn new(start: u64, end: u64) -> Self {
Self { start, end }
}
fn len(&self) -> u64 {
if self.end < self.start {
0
}
else {
self.end - self.start
}
}
fn empty(&self) -> bool {
self.len() == 0
}
fn overlaps(&self, other: &MemRegion) -> bool {
self.start <= other.end && other.start <= self.end
}
fn merge(&mut self, other: &MemRegion) {
debug_assert!(self.overlaps(other));
self.start = self.start.min(other.start);
self.end = self.end.max(other.end);
}
}
fn main() {
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_push_usable() {
{
let mut rs = MemRegions::<4>::new();
rs.push_usable(MemRegion::new(800, 900));
rs.push_usable(MemRegion::new(500, 600));
rs.push_usable(MemRegion::new(250, 400));
rs.push_usable(MemRegion::new(100, 200));
assert_eq!(rs.regions(), &[
MemRegion::new(100, 200),
MemRegion::new(250, 400),
MemRegion::new(500, 600),
MemRegion::new(800, 900),
]);
}
{
let mut rs = MemRegions::<4>::new();
rs.push_usable(MemRegion::new(250, 400));
rs.push_usable(MemRegion::new(100, 200));
rs.push_usable(MemRegion::new(150, 300));
assert_eq!(rs.regions(), &[
MemRegion::new(100, 400),
]);
}
{
let mut rs = MemRegions::<4>::new();
rs.push_usable(MemRegion::new(100, 200));
rs.push_usable(MemRegion::new(150, 300));
rs.push_usable(MemRegion::new(250, 400));
assert_eq!(rs.regions(), &[
MemRegion::new(100, 400),
]);
}
{
let mut rs = MemRegions::<4>::new();
rs.push_usable(MemRegion::new(250, 400));
rs.push_usable(MemRegion::new(100, 200));
rs.push_usable(MemRegion::new(500, 600));
rs.push_usable(MemRegion::new(150, 300));
assert_eq!(rs.regions(), &[
MemRegion::new(100, 400),
MemRegion::new(500, 600),
]);
}
}
#[test]
fn test_push_unusable() {
{
let mut rs = MemRegions::<4>::new();
rs.push_usable(MemRegion::new(800, 900));
rs.push_usable(MemRegion::new(500, 600));
rs.push_usable(MemRegion::new(250, 400));
rs.push_usable(MemRegion::new(100, 200));
rs.push_unusable(MemRegion::new(250, 400));
assert_eq!(rs.regions(), &[
MemRegion::new(100, 200),
MemRegion::new(500, 600),
MemRegion::new(800, 900),
]);
}
{
let mut rs = MemRegions::<4>::new();
rs.push_usable(MemRegion::new(800, 900));
rs.push_usable(MemRegion::new(500, 600));
rs.push_usable(MemRegion::new(250, 400));
rs.push_usable(MemRegion::new(100, 200));
rs.push_unusable(MemRegion::new(300, 400));
assert_eq!(rs.regions(), &[
MemRegion::new(100, 200),
MemRegion::new(250, 300),
MemRegion::new(500, 600),
MemRegion::new(800, 900),
]);
}
{
let mut rs = MemRegions::<4>::new();
rs.push_usable(MemRegion::new(800, 900));
rs.push_usable(MemRegion::new(500, 600));
rs.push_usable(MemRegion::new(250, 400));
rs.push_usable(MemRegion::new(100, 200));
rs.push_unusable(MemRegion::new(250, 300));
assert_eq!(rs.regions(), &[
MemRegion::new(100, 200),
MemRegion::new(300, 400),
MemRegion::new(500, 600),
MemRegion::new(800, 900),
]);
}
{
let mut rs = MemRegions::<5>::new();
rs.push_usable(MemRegion::new(800, 900));
rs.push_usable(MemRegion::new(500, 600));
rs.push_usable(MemRegion::new(250, 400));
rs.push_usable(MemRegion::new(100, 200));
rs.push_unusable(MemRegion::new(300, 350));
assert_eq!(rs.regions(), &[
MemRegion::new(100, 200),
MemRegion::new(250, 300),
MemRegion::new(350, 400),
MemRegion::new(500, 600),
MemRegion::new(800, 900),
]);
}
{
let mut rs = MemRegions::<4>::new();
rs.push_usable(MemRegion::new(800, 900));
rs.push_usable(MemRegion::new(500, 600));
rs.push_usable(MemRegion::new(250, 400));
rs.push_usable(MemRegion::new(100, 200));
rs.push_unusable(MemRegion::new(150, 550));
assert_eq!(rs.regions(), &[
MemRegion::new(100, 150),
MemRegion::new(550, 600),
MemRegion::new(800, 900),
]);
}
}
}
+13
View File
@@ -0,0 +1,13 @@
Index: boot/seabios/scripts/kconfig/lxdialog/check-lxdialog.sh
===================================================================
--- boot.orig/seabios/scripts/kconfig/lxdialog/check-lxdialog.sh
+++ boot/seabios/scripts/kconfig/lxdialog/check-lxdialog.sh
@@ -43,7 +43,7 @@ trap "rm -f $tmp" 0 1 2 3 15
check() {
$cc -x c - -o $tmp 2>/dev/null <<'EOF'
#include CURSES_LOC
-main() {}
+int main() { return 0; }
EOF
if [ $? != 0 ]; then
echo " *** Unable to find the ncurses libraries or the" 1>&2
+1
View File
@@ -0,0 +1 @@
001_seabios_menuconfig.patch
+22
View File
@@ -0,0 +1,22 @@
## Overview
Currently we boot from BIOS on a GPT-partitioned disk.
`boot0.s` is the first-stage bootloader. It lives in the MBR bootstrap field, and must therefore
fit into 440 bytes. Its tasks are:
- [x] Set up a stack etc.
- [x] Get the boot drive geometry
- [x] Load and parse the GPT
- [x] Find the partition of the second stage
- [x] Load and jump to the first sector of the second stage
`boot1.s` is the second-stage bootloader. Its tasks are:
- [x] Load its own sectors not loaded by the first stage
- [x] Enable A20
- [ ] Detect available memory
- [ ] Enter unreal mode
- [ ] Read the kernel ELF from disk (don't have to parse the ELF just yet)
- [ ] Get all the useful information we can from the BIOS before we leave unreal mode
- [ ] Enter long mode (possibly via protected mode?)
- [ ] Load the kernel ELF
- [ ] Initialise stack etc. for the kernel
- [ ] Jump to kernel
+14
View File
@@ -0,0 +1,14 @@
; flash seems to get mapped to ff000
; reset vector is f000:fff0 = ffff0
; so there's ff0 = 4080 bytes of something before the reset vector. what is it?
[bits 16]
[org 0xff000]
times (0xff0 - ($ - $$)) db 0x00
mov eax, 0xcafeface
hlt
times (0x1000 - ($ - $$)) db 0xf4
+26
View File
@@ -2,18 +2,26 @@
- <https://www.felixcloutier.com/x86/> - <https://www.felixcloutier.com/x86/>
- <http://www.unixwiz.net/techtips/x86-jumps.html> - <http://www.unixwiz.net/techtips/x86-jumps.html>
- <https://www.nasm.us/xdoc/2.13.01/nasmdoc.pdf> - <https://www.nasm.us/xdoc/2.13.01/nasmdoc.pdf>
- <https://www.nasm.us/xdoc/2.13.02rc3/html/nasmdo10.html>
- <https://wiki.osdev.org/Real_Mode> - <https://wiki.osdev.org/Real_Mode>
- <https://www.eecg.utoronto.ca/~amza/www.mindsec.com/files/x86regs.html> - <https://www.eecg.utoronto.ca/~amza/www.mindsec.com/files/x86regs.html>
- <https://en.wikibooks.org/wiki/X86_Assembly/16,_32,_and_64_Bits> - <https://en.wikibooks.org/wiki/X86_Assembly/16,_32,_and_64_Bits>
- <https://www.plantation-productions.com/Webster/www.artofasm.com/DOS/ch04/CH04-2.html> - <https://www.plantation-productions.com/Webster/www.artofasm.com/DOS/ch04/CH04-2.html>
- <https://www.tortall.net/projects/yasm/manual/html/nasm-local-label.html>
## Boot sequence ## Boot sequence
- <https://wiki.osdev.org/Boot_Sequence> - <https://wiki.osdev.org/Boot_Sequence>
- <https://wiki.osdev.org/Protected_Mode#Entering_Protected_Mode> - <https://wiki.osdev.org/Protected_Mode#Entering_Protected_Mode>
- <https://wiki.osdev.org/A20_Line>
## Unreal mode
- <https://wiki.osdev.org/Unreal_Mode>
- <http://www.rcollins.org/ddj/Aug98/Aug98.html>
## Memory ## Memory
- <https://wiki.osdev.org/Memory_Map_(x86)> - <https://wiki.osdev.org/Memory_Map_(x86)>
- <https://wiki.osdev.org/Detecting_Memory_(x86)> - <https://wiki.osdev.org/Detecting_Memory_(x86)>
- <http://www.uruk.org/orig-grub/mem64mb.html>
## BIOS interrupts ## BIOS interrupts
- <https://en.wikipedia.org/wiki/BIOS_interrupt_call> - <https://en.wikipedia.org/wiki/BIOS_interrupt_call>
@@ -30,5 +38,23 @@
- <https://en.wikipedia.org/wiki/Code_page_437> - <https://en.wikipedia.org/wiki/Code_page_437>
## ELF ## ELF
- <http://www.skyfree.org/linux/references/ELF_Format.pdf>
- <https://wiki.osdev.org/ELF> - <https://wiki.osdev.org/ELF>
- <https://wiki.osdev.org/ELF_Tutorial> - <https://wiki.osdev.org/ELF_Tutorial>
## Intel 8042 PS/2 controller
- <https://wiki.osdev.org/%228042%22_PS/2_Controller>
- <https://wiki.osdev.org/I/O_Ports>
## Partitioning
- <https://uefi.org/specs/UEFI/2.10/05_GUID_Partition_Table_Format.html>
- <https://wiki.osdev.org/GPT>
## Memory protection
- <https://wiki.osdev.org/Global_Descriptor_Table>
- <https://wiki.osdev.org/GDT_Tutorial>
- <https://wiki.osdev.org/Segment_Limits>
- <https://www.felixcloutier.com/x86/lgdt:lidt>
## Qemu
- <https://qemu-project.gitlab.io/qemu/system/monitor.html>
+3
View File
@@ -0,0 +1,3 @@
[toolchain]
channel = "nightly"
Submodule
+1
Submodule seabios added at e5f2e4c696.
+253
View File
@@ -0,0 +1,253 @@
%include "layout.s"
%include "globals.s"
[org S1_ADDR]
[bits 16]
main:
cli
xor ax, ax
mov ds, ax
mov es, ax
; Put the stack base at 0x4000.
; Stack grows high->low, so we'll grow away from our globals and program text.
mov ss, ax
mov bp, REAL_STACK_BASE
mov sp, bp
; Segment for VGA (0xb800 * 16 = 0xb8000)
mov ax, 0xb800
mov fs, ax
; Set VGA mode
; https://mendelson.org/wpdos/videomodes.txt
mov ax, 0x0003
int 0x10
; Store boot drive number
xor dh, dh
push dx
; Get drive geometry
mov di, 0x00
mov ah, 0x08
int 0x13
jc panic
; Load sectors per track into cx & spill
and cl, 0x3f
xor ch, ch
push cx
; Load number of heads into bx & spill
movzx bx, dh
inc bx
push bx
; Load LBA 1.
mov ax, 1
mov bx, 0x7e00
call read_lba
; Check the GPT header magic "EFI PART"
mov cx, GPT_MAGIC_LEN
mov si, gpt_magic
mov di, 0x7e00
repe cmpsb
jne panic
; Ensure the 8-byte GPT starting LBA fits in 16 bits
mov di, 0x7e00 ; The rep increments di so we need to reset it
mov eax, [di + 0x4c]
mov bx, [di + 0x4a]
or ax, bx
or eax, eax
jnz panic
; Store the first 16 bits of the GPT starting LBA (we have made sure the remaining bits are 0)
push word [di + 0x48]
; Load number of partitions
mov ax, [di + 0x50]
mov bx, [di + 0x52]
or bx, bx
jz .gpt_n_partitions_loaded
; Number of partitions overflows 16 bits, so we just concern ourselves with the first 65535.
; That's an awful lot of partitions anyway.
mov ax, 0xffff
.gpt_n_partitions_loaded:
push ax
; Load GPT entry size
mov eax, [di + 0x54] ; Operand size override otherwise this is going to be painful
mov ebx, eax
; Assert that the entry size is 128 * 2^n for some integer n>=0. This is required for a valid GPT
; and has the nice properties that:
; - If each entry is larger than a sector (512 bytes), they'll be sector-aligned.
; - If each entry is smaller than a sector, an integer number of them will fit into a sector.
or eax, eax ; Test size != 0 because 128 * 2^n != 0
jz panic
test eax, 127 ; Test size is a multiple of 128
jnz panic
; Use the (n & (n - 1)) == 0 trick to test if the entry size is a power of 2. Since we already
; know it's a nonzero multiple of 128, if size is a power of 2 then size = 128 * 2^n holds.
; Therefore we don't need to bother dividing by 128 first (shr 7), which saves a couple of bytes.
mov ecx, ebx
dec ecx
and ecx, eax
jnz panic
; Find the "sector stride", which is the number of sectors we increment by each time we want to
; load a new entry.
shr eax, 9 ; Divide by sector size to get sectors per entry
cmp eax, 0xffff ; Make sure sectors per entry fits in 16 bits
ja panic
or ax, ax
jnz .gpt_sector_stride_loaded
; Sector stride must be at least one or we'll load the same sector each time!
inc ax
.gpt_sector_stride_loaded:
push ax
; Find the "byte stride", which is the number of bytes we increment by each time we want to load
; the next entry in the same sector.
cmp ebx, 512
jb .gpt_find_entries_per_sector
push word 0 ; Arbitrary byte stride since there's only one entry per sector
push word 1 ; 1 entry per sector, since an entry is larger than a sector
jmp .gpt_found_entries_per_sector
.gpt_find_entries_per_sector:
push bx ; Store byte stride = entry length in this case
xor dx, dx
mov ax, 512
div bx ; Find entries per sector
push ax
.gpt_found_entries_per_sector:
; Set up stack variables for our second stage search loop.
xor ax, ax
push ax ; Current entry
push ax ; Current entry within the current sector
push ax ; Number of sectors loaded
push word [bp - GPT_ENTRIES_START_LBA] ; Current LBA
; Search for the partition storing our second stage.
.loop_find_stage2:
mov dx, [bp - GPT_CURRENT_ENTRY_IDX]
cmp [bp - GPT_N_ENTRIES_16], dx
; Panic if we've run out of partitions and haven't found the second stage yet.
jbe panic
; If we haven't loaded any sectors yet, load the first one.
cmp word [bp - GPT_SECTORS_LOADED], 0
je .load_first_lba
; If there's still more entries in the current sector, skip loading a new sector
mov ax, [bp - GPT_SECTOR_ENTRY_IDX] ; Load current entry index within the current sector
cmp [bp - GPT_ENTRIES_PER_SECTOR], ax ; Compare to entries per sector
ja .process_current_entry
mov ax, [bp - GPT_SECTOR_STRIDE] ; Load sector stride
add word [bp - GPT_CURRENT_LBA], ax ; Increment current LBA by sector stride
mov word [bp - GPT_SECTOR_ENTRY_IDX], 0 ; Reset the current entry index within the current sector
.load_first_lba:
; Read the current LBA to 0x8000 (just past the end of the GPT header)
mov ax, [bp - GPT_CURRENT_LBA]
mov bx, 0x8000
call read_lba
; Increment number of sectors loaded
inc word [bp - GPT_SECTORS_LOADED]
.process_current_entry:
; Calculate the address of the current GPT entry.
mov ax, [bp - GPT_SECTOR_ENTRY_IDX] ; Load current entry index within current sector
xor dx, dx
mul word [bp - GPT_BYTE_STRIDE] ; Get the byte offset in the current sector of the current entry
add ax, 0x8000 ; Convert offset to address (we loaded the sector at 0x8000)
; Compare entry GUID to our stage 2 partition GUID.
mov cx, GUID_LEN
mov si, guid_stage2
mov di, ax
repe cmpsb
je .found_stage2
; Next iteration
inc word [bp - GPT_CURRENT_ENTRY_IDX] ; Increment current entry index
inc word [bp - GPT_SECTOR_ENTRY_IDX] ; Increment current entry index within the current sector
jmp .loop_find_stage2
.found_stage2:
push ax ; Address of the GPT entry for stage 2
mov si, ax
; Load partition LBA start.
mov eax, [si + 0x20]
mov ebx, [si + 0x24]
; Ensure it fits in 16 bits.
or ebx, ebx
jnz panic
cmp ebx, 0xffff
ja panic
; Load partition LBA end.
mov ecx, [si + 0x28]
mov edx, [si + 0x2c]
; Assert that the end LBA is greater than or equal to the start LBA, so we have at least one
; sector to load (end LBA is inclusive).
or edx, edx
jnz .stage2_end_lba_ok
cmp eax, ecx
ja panic
.stage2_end_lba_ok:
mov bx, S2_LOAD_ADDR
call read_lba
add bx, S2_TEXT_OFFSET
jmp bx
; Load a single boot disk sector. Panic on failure.
; Inputs:
; - ax: LBA to load
; - bx: address to read sector to
; Clobber: ax, cx, dx
read_lba:
; sector - 1 = LBA % sectors_per_track
; temp = LBA / sectors_per_track
; head = temp % n_heads
; cylinder = temp / n_heads
xor dx, dx
; Divide by sectors per track. dx = mod (sector - 1), ax = div (temp)
div word [bp - SECTORS_PER_TRACK]
; Put the sector into cx (the bios call will use cl)
mov cx, dx
inc cx
xor dx, dx
; Divide by number of heads. dx = mod (head), ax = div (cylinder)
div word [bp - N_HEADS]
mov dh, dl
mov ch, al
mov dl, byte [bp - BOOT_DRIVE]
mov ah, 0x02
mov al, 1
; Read sector
int 0x13
jc panic
ret
panic:
mov ax, 0x0003
int 0x10
mov word fs:[0x0000], 0x4f21
hlt
gpt_magic db "EFI PART"
GPT_MAGIC_LEN equ $ - gpt_magic
; Our stage2 guid: fdffea69-3651-442f-a11d-88a09bf372dd
guid_stage2 db 0x69, 0xea, 0xff, 0xfd, 0x51, 0x36, 0x2f, 0x44, \
0xa1, 0x1d, 0x88, 0xa0, 0x9b, 0xf3, 0x72, 0xdd
GUID_LEN equ $ - guid_stage2
; MBR bootstrap field is 440 bytes long
%if ($ - $$) > 440
%error "exceeded mbr bootstrap field size"
%endif
+112
View File
@@ -0,0 +1,112 @@
[bits 16]
%include "fn.s"
%include "ps2.s"
%macro mov_out 3
mov %1, %3
out %2, %1
%endmacro
; Check whether the A20 line is enabled. Writes to the boot sector identifier.
; Arguments: none
; Return:
; - ax: 0 if A20 disabled, nonzero if A20 enabled
; Clobber: none
test_a20:
push bp
mov bp, sp
push gs
; Restore the boot sector identifier in case it was overwritten by anything.
mov word [0x7dfe], 0xaa55
mov ax, 0xffff
mov gs, ax
xor ax, ax
; If the word at 0x107dfe (1 MiB after the boot sector identifier) is different to the boot
; sector identifier, than A20 must be enabled.
cmp word gs:[0x7e0e], 0xaa55
setne al
jne .return
; Even if A20 was enabled, the two words may have been equal by chance, so we temporarily swap
; the boot sector identifier bytes and test again.
ror word [0x7dfe], 8
cmp word gs:[0x7e0e], 0x55aa
setne al
ror word [0x7dfe], 8
jmp .return
.return:
pop gs
pop bp
ret
global test_a20
; Try to enable A20 using the Intel 8042 PS/2 keyboard controller.
; Arguments: none
; Return: none
; Clobber: ax, cx, dx
enable_a20_intel_8042:
; Temporarily disable the keyboard.
call intel_8042_wait_write
mov_out al, INTEL_8042_OUT_CMD, INTEL_8042_CMD_PS2_1_DISABLE
; Read the controller output port.
call intel_8042_wait_write
mov_out al, INTEL_8042_OUT_CMD, INTEL_8042_CMD_CONTROLLER_OUT_PORT_READ
call intel_8042_wait_read
in al, INTEL_8042_IO_DATA
; The second bit is "A20 enabled", so set it.
mov cl, al
or cl, 2
; Write the modified byte back to the controller output port.
call intel_8042_wait_write
mov_out al, INTEL_8042_OUT_CMD, INTEL_8042_CMD_CONTROLLER_OUT_PORT_WRITE
call intel_8042_wait_write
mov_out al, INTEL_8042_IO_DATA, cl
; Re-enable the keyboard.
call intel_8042_wait_write
mov_out al, INTEL_8042_OUT_CMD, INTEL_8042_CMD_PS2_1_ENABLE
; Wait for writes to finish.
call intel_8042_wait_write
ret
global enable_a20_intel_8042
; Wait for the Intel 8042 input buffer to become empty, so we can write.
; Arguments: none
; Return: none
; Clobber: al
intel_8042_wait_write:
.loop:
; Read the 8042 status register.
in al, INTEL_8042_IN_STATUS
; Input buffer status flag set means the input buffer is full, so loop in this case.
test al, INTEL_8042_STATUS_MASK_IBUF
jnz .loop
ret
; Wait for the Intel 8042 output buffer to become filled, so we can read.
; Arguments: none
; Return: none
; Clobber: al
intel_8042_wait_read:
.loop:
; Read the 8042 status register.
in al, INTEL_8042_IN_STATUS
; Output buffer status flag unset means output buffer is empty, so loop in this case.
test al, INTEL_8042_STATUS_MASK_OBUF
jz .loop
ret
+43
View File
@@ -0,0 +1,43 @@
OUTPUT_FORMAT("binary")
. = 0x8200;
SECTIONS {
/* Prelude must come first so it's in the single sector loaded by stage 1. */
.prelude : {
*(.prelude)
}
.text : {
*(.text)
*(.text.*)
}
.data : {
*(.data)
*(.data.*)
}
.bss : {
*(.bss)
*(.bss.*)
}
.rodata : {
*(.rodata)
*(.rodata.*)
}
.magic : {
/* Magic bytes stage 2 uses to make sure it's loaded the subsequent sectors correctly. */
LONG(0x544e4150)
}
s2_magic = ADDR(.magic);
/* Define a symbol for the total length of the binary, so the prelude knows how many blocks to
* load from disk.
*/
s2_bin_len = . - 0x8200;
s2_bin_sectors = (s2_bin_len + 511) / 512;
}
+69
View File
@@ -0,0 +1,69 @@
[bits 16]
%include "fn.s"
%include "layout.s"
%include "globals.s"
%include "s2_fns.s"
extern s2_data.s3_bin_offset_sectors
extern s2_data.s3_bin_len_sectors
load_s3:
fnstart
push ebx
; Calculate the stage 3 start LBA.
mov ax, [REAL_GLOBALS + STAGE_2_START_LBA]
add ax, [s2_data.s3_bin_offset_sectors]
jc .fail
; Stage 3 should not overlap with stage 2.
cmp word [REAL_GLOBALS + STAGE_2_END_LBA], ax
jae .fail
xor ebx, ebx
; There must be at least one sector to load.
mov bx, [s2_data.s3_bin_len_sectors]
or bx, bx
jz .fail
; Calculate the end LBA (inclusive).
dec bx
add bx, ax
jc .fail
; Check stage 3 is entirely inside the partition.
cmp dword [REAL_GLOBALS + LOADER_PART_END_LBA], ebx
jb .fail
push ax ; Current LBA
push bx ; s3 end LBA
mov ebx, S3_LOAD_ADDR ; Current load address
.load_loop:
mov ax, [bp - 0x06] ; Load current LBA
cmp word [bp - 0x08], ax ; Compare to s3 end LBA
jb .load_done
mov ecx, ebx
call read_sector
jc .fail
add ebx, 512
inc word [bp - 0x06]
jmp .load_loop
.load_done:
add sp, 4
pop ebx
clc
fnret
.fail:
pop ebx
stc
fnret
global load_s3
+176
View File
@@ -0,0 +1,176 @@
[bits 16]
%include "fn.s"
%include "layout.s"
%include "s2_fns.s"
extern test_a20
extern enable_a20_intel_8042
extern load_s3
s2_main:
call test_a20
test al, al
jnz .a20_enabled
; Try to enable A20 using the Intel 8042 PS/2 keyboard controller.
call enable_a20_intel_8042
call test_a20
test al, al
jnz .a20_enabled
; TODO: try other methods first before we panic:
; - [ ] BIOS interrupt
; - [ ] Fast A20 enable
jmp panic_simple
.a20_enabled:
call load_s3
jc panic_simple
mov ax, 0x0003
int 0x10
; Disable cursor
mov ax, 0x0100
mov cx, 0x3f00
int 0x10
; Copy the GDT
mov cx, GDT_FLAT_LEN
mov si, gdt_flat
mov di, GDT_FLAT_ADDR
rep movsb
; Ensure interrupts are definitely disabled.
cli
; Load our flat-address-space GDT.
lgdt [gdt_flat_slice]
; Set the protected-mode bit in cr0.
mov eax, cr0
or al, 0x01
mov cr0, eax
; Long jump to set the code segment to gdt_flat.segment_code, and to clear the instruction
; pipeline.
jmp GDT_FLAT_IDX_CODE_32:.protected_mode_32
[bits 32]
.protected_mode_32:
; Set the data segments to gdt_flat.segment_data.
mov eax, GDT_FLAT_IDX_DATA
mov ds, eax
mov es, eax
mov fs, eax
mov gs, eax
mov ss, eax
; Reset the stack.
; TODO: put the 32-bit stack somewhere else.
mov ebp, REAL_STACK_BASE
mov esp, ebp
jmp S3_LOAD_ADDR
.halt:
hlt
jmp .halt
global s2_main
section .s3_data
gdt_flat_slice:
dw GDT_FLAT_LEN
dd GDT_FLAT_ADDR
; Segment descriptor layout
; | Range (bits) | Field |
; |--------------|---------------|
; | 0-16 | limit |
; | 16-32 | base |
; | 32-40 | base cont. |
; | 40-48 | access |
; | 48-52 | limit cont. |
; | 52-56 | flags |
; | 56-64 | base cont. |
;
; Flags
; - 0: reserved
; - 1: long-mode code segment
; - 2: size
; - unset: 16-bit
; - set: 32-bit
; - 3: granularity
; - unset: limit is measured in bytes
; - set: limit is measured in 4KiB pages
;
; Access
; - 0: accessed
; - unset: CPU will set it when the segment is accessed
; - 1: readable / writable
; - data segments: is segment writable (data segments are always readable)
; - code segments: is segment readable (code segments are never writable)
; - 2: direction / conforming
; - data segments: whether segment grows down
; - code segments: whether this can be executed from a lower-privilege ring
; - 3: executable
; - unset: this is a data segment
; - set: this is a code segment
; - 4: descriptor type
; - unset: this is a task state segment
; - set: this is a data or code segment
; - 5-6: privilege level (ring number)
; - 7: present (must be set)
;
align 8
gdt_flat:
; First GDT entry must be 0.
dq 0
; 32-bit code segment.
; Pages 0x0000 - 0xffff. Needs to contain 0x10000, where the stage 3 text is loaded.
.segment_code_32:
db 0xff, 0xff, \
0x00, 0x00, \
0x00, \
10011011b, \
11001111b, \
0x00
; 16-bit code segment, to use if we want to switch back to real mode.
; Bytes 0x0000 - 0xffff.
.segment_code_16:
db 0xff, 0xff, \
0x00, 0x00, \
0x00, \
10011011b, \
00000000b, \
0x00
; Data segment.
; Pages 0x000000 - 0x0fffff, which covers the entire 32-bit address space (start of 0xfffff-th page
; is 0xfffff * 4096 = 0xfffff000, end of page exclusive is 0xfffff000 + 4096 = 0x100000000).
.segment_data:
db 0xff, 0xff, \
0x00, 0x00, \
0x00, \
10010011b, \
11001111b, \
0x00
GDT_FLAT_LEN equ ($ - gdt_flat)
GDT_FLAT_IDX_CODE_32 equ (gdt_flat.segment_code_32 - gdt_flat)
global GDT_FLAT_IDX_CODE_32
GDT_FLAT_IDX_CODE_16 equ (gdt_flat.segment_code_16 - gdt_flat)
global GDT_FLAT_IDX_CODE_16
GDT_FLAT_IDX_DATA equ (gdt_flat.segment_data - gdt_flat)
global GDT_FLAT_IDX_DATA
+241
View File
@@ -0,0 +1,241 @@
[bits 16]
%include "fn.s"
%include "layout.s"
%include "globals.s"
extern s2_bin_len
extern s2_bin_sectors
extern s2_magic
extern s2_main
%macro copy_stack_var_to_globals 2
mov %1, [bp - %2]
mov [REAL_GLOBALS + %2], %1
%endmacro
section .prelude
s2_data:
.s3_bin_offset_sectors:
dw 0
.s3_bin_len_sectors:
dw 0
.padding:
times (S2_DATA_LEN - 4) db 0xf4
global s2_data
global s2_data.s3_bin_offset_sectors
global s2_data.s3_bin_len_sectors
%if ($ - $$) != S2_DATA_LEN
%error "incorrect prelude data size"
%endif
; Load the rest of stage 2 into memory.
prelude:
; Now that we're not doing instruction byte golf like we were in stage 1, we can afford to move
; the various stage 1 stack variables to the globals section.
copy_stack_var_to_globals ax, BOOT_DRIVE
copy_stack_var_to_globals ax, SECTORS_PER_TRACK
copy_stack_var_to_globals ax, N_HEADS
copy_stack_var_to_globals ax, GPT_ENTRIES_START_LBA
copy_stack_var_to_globals ax, GPT_N_ENTRIES_16
copy_stack_var_to_globals ax, GPT_SECTOR_STRIDE
copy_stack_var_to_globals ax, GPT_BYTE_STRIDE
copy_stack_var_to_globals ax, GPT_ENTRIES_PER_SECTOR
copy_stack_var_to_globals ax, GPT_CURRENT_ENTRY_IDX
copy_stack_var_to_globals ax, GPT_SECTOR_ENTRY_IDX
copy_stack_var_to_globals ax, GPT_SECTORS_LOADED
copy_stack_var_to_globals ax, GPT_CURRENT_LBA
copy_stack_var_to_globals ax, STAGE_2_GPT_ENTRY_ADDR
; Reset the stack, now we've got everything we need from it.
mov sp, bp
mov si, [REAL_GLOBALS + STAGE_2_GPT_ENTRY_ADDR]
mov eax, [si + 0x20] ; Partition / s2 start LBA lower
mov ebx, [si + 0x24] ; Partition / s2 start LBA upper
mov ecx, [si + 0x28] ; Partition end LBA lower
mov edx, [si + 0x32] ; Partition end LBA upper
; Panic if the partition / boot1 starting LBA overflows 16 bits.
or ebx, ebx
jnz panic_simple
ror eax, 16
or ax, ax
jnz panic_simple
ror eax, 16
; There must be at least one sector to load.
mov bx, s2_bin_sectors
or bx, bx
jz panic_simple
; Calculate the s2 end LBA (inclusive) and panic if it overflows 16 bits.
; n.b. ebx is zero before this so both bx and ebx can be used as the s2 end LBA.
dec bx
add bx, ax
jc panic_simple
; Panic if the s2 end LBA is after the partition end LBA.
; If the upper 32 bits of the partition end LBA are nonzero, then it must be greater than our
; 16-bit s2 end LBA.
or edx, edx
jnz .end_lba_ok
; Compare the s2 end LBA to the lower 32 bits of the partition end LBA.
cmp ebx, ecx
ja panic_simple
; Save partition / s2 extents for later.
mov [REAL_GLOBALS + LOADER_PART_END_LBA], ecx
mov [REAL_GLOBALS + STAGE_2_START_LBA], ax
mov [REAL_GLOBALS + STAGE_2_END_LBA], bx
.end_lba_ok:
; The first sector has already been loaded (we're running it right now!) so increment the
; current LBA.
inc ax
push ax ; Current LBA
push bx ; s2 end LBA
mov ebx, S2_LOAD_ADDR + 512 ; Current sector load address
.load_loop:
mov ax, [bp - 0x02] ; Load current LBA
cmp word [bp - 0x04], ax ; Compare to s2 end LBA
jb .load_done
mov ecx, ebx
call read_sector
jc panic_simple
add ebx, 512
inc word [bp - 0x02]
jmp .load_loop
.load_done:
; Check the magic bytes at the end of s2.
push es
mov ebx, s2_magic
call addr32_to_addr16
cmp dword es:[bx], S2_MAGIC
pop es
jne panic_simple
jmp s2_main
; Converts a 32-bit address to a 16-bit sector and offset.
; Arguments:
; - ebx: 32-bit address
; Return:
; - es: 16-bit address segment (unchanged on failure)
; - ebx: 16-bit address offset
; - cf: unset on success, set on failure
; Clobber: none
addr32_to_addr16:
fnstart
push es
push eax
mov eax, ebx
; Divide addr by 16 and saturate to 16 bits to get the segment.
shr eax, 4
ror eax, 16
or ax, ax
jz .segment_ok
mov eax, 0xffff0000
.segment_ok:
ror eax, 16
mov es, ax
; Calculate offset = addr - (16 * segment), failing if the offset doesn't fit in 16 bits.
shl eax, 4
sub ebx, eax
ror ebx, 16
or bx, bx
jnz .fail
ror ebx, 16
pop eax
add sp, 2 ; Discard the original es from the stack
pop bp
clc
ret
.fail:
pop eax
pop es
stc
fnret
global addr32_to_addr16
; Reads a single sector at the given LBA into memory.
; Arguments:
; - ax: start LBA
; - ecx: address to read sector to
; Return:
; - cf: unset on success, set on failure
; Clobber: eax, ecx, edx
read_sector:
; sector - 1 = LBA % sectors_per_track
; temp = LBA / sectors_per_track
; head = temp % n_heads
; cylinder = temp / n_heads
fnstart
push es
push ebx
mov ebx, ecx
call addr32_to_addr16
jc .return
; Calculate sector and temp
xor dx, dx
; Divide by sectors per track. dx = mod (sector - 1), ax = div (temp)
div word [REAL_GLOBALS + SECTORS_PER_TRACK]
; Put the sector into cx (the bios call will use cl)
mov cx, dx
inc cx
; Calculate head and cylinder
xor dx, dx
; Divide by number of heads. dx = mod (head), ax = div (cylinder)
div word [REAL_GLOBALS + N_HEADS]
mov dh, dl
mov ch, al
mov dl, byte [REAL_GLOBALS + BOOT_DRIVE]
mov ah, 0x02
mov al, 1
; Read sector
int 0x13
.return:
pop ebx
pop es
fnret
global read_sector
panic_simple:
mov ax, 0x0003
int 0x10
mov word fs:[0x0000], 0x4f21
.halt:
hlt
jmp .halt
global panic_simple
%if ($ - $$) > 512
%error "stage 2 exceeded sector size"
%endif
+7
View File
@@ -0,0 +1,7 @@
[build]
target = "protected32.json"
[unstable]
build-std = [ "core", "compiler_builtins" ]
build-std-features = [ "compiler-builtins-mem" ]
+1
View File
@@ -0,0 +1 @@
/target
+7
View File
@@ -0,0 +1,7 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "stage_3"
version = "0.1.0"
+6
View File
@@ -0,0 +1,6 @@
[package]
name = "stage_3"
version = "0.1.0"
edition = "2024"
[dependencies]
+6
View File
@@ -0,0 +1,6 @@
fn main() {
const LINKER_SCRIPT_PATH: &str = "link.ld";
println!("cargo::rerun-if-changed={}", LINKER_SCRIPT_PATH);
println!("cargo::rustc-link-arg=-T{}", LINKER_SCRIPT_PATH);
}
+30
View File
@@ -0,0 +1,30 @@
OUTPUT_FORMAT("binary")
. = 0x10000;
SECTIONS {
.trampoline : {
KEEP(*(.trampoline))
KEEP(*(.trampoline.*))
}
.text : {
*(.text)
*(.text.*)
}
.data : {
*(.data)
*(.data.*)
}
.bss : {
*(.bss)
*(.bss.*)
}
.rodata : {
*(.rodata)
*(.rodata.*)
}
}
+17
View File
@@ -0,0 +1,17 @@
{
"arch": "x86",
"os": "none",
"llvm-target": "i686-unknown-none",
"data-layout": "e-m:e-p:32:32-p270:32:32-p271:32:32-p272:64:64-i128:128-f64:32:64-f80:32-n8:16:32-S128",
"target-endian": "little",
"target-pointer-width": "32",
"target-c-int-width": 32,
"executables": true,
"linker-flavor": "ld.lld",
"linker": "rust-lld",
"panic-strategy": "abort",
"disable-redzone": true,
"features": "-mmx,-sse,+soft-float",
"rustc-abi": "x86-softfloat"
}
+8
View File
@@ -0,0 +1,8 @@
section .text
[bits 32]
; TODO: reference sysv abi spec to see what we can mangle and what we must preserve
load_sector:
ret
+7
View File
@@ -0,0 +1,7 @@
.code32
.section ".trampoline", "ax", @progbits
trampoline:
jmp _start
.globl trampoline
+124
View File
@@ -0,0 +1,124 @@
use core::{fmt, hint};
use crate::{ioport, spin::Spinlock};
const COM1_PORT: u16 = 0x3f8;
pub static COM1: Spinlock<Option<Com>> = Spinlock::new(None);
#[macro_export]
macro_rules! com1_print {
($($args:tt)*) => ({
crate::com::with_com1_if_available(|com1| {
::core::write!(com1, $($args)*).ok();
});
})
}
#[macro_export]
macro_rules! com1_println {
($($args:tt)*) => ({
crate::com::with_com1_if_available(|com1| {
::core::writeln!(com1, $($args)*).ok();
});
})
}
pub struct Com {
port: u16,
}
pub struct ComError;
pub fn with_com1_if_available<F>(f: F)
where
F: FnOnce(&mut Com),
{
let mut guard = COM1.lock();
if let Some(com1) = guard.as_mut() {
f(com1);
}
}
pub unsafe fn try_com1_init() -> bool {
match unsafe { Com::init(COM1_PORT) } {
Ok(com1) => {
let mut guard = COM1.lock();
*guard = Some(com1);
true
}
_ => false,
}
}
impl Com {
pub unsafe fn init(port: u16) -> Result<Self, ComError> {
const ECHO_BYTE: u8 = 0x5a;
let echo = unsafe {
// Unset DLAB
ioport::outb(port + 3, 0x00);
// Disable interrupts
ioport::outb(port + 1, 0x00);
// Set DLAB
ioport::outb(port + 3, 0x80);
// Set baud rate divisor to 00 01 (115200)
ioport::outb(port + 0, 0x01);
ioport::outb(port + 1, 0x00);
// 8 bits, no parity, one stop bit
ioport::outb(port + 3, 0x03);
// Enable FIFO, clear them, with 14-byte threshold
ioport::outb(port + 2, 0xc7);
// IRQs enabled, RTS/DSR set
ioport::outb(port + 4, 0x0b);
// Set loopback mode
ioport::outb(port + 4, 0x1e);
ioport::outb(port + 0, ECHO_BYTE);
ioport::inb(port + 0)
};
if echo != ECHO_BYTE {
return Err(ComError);
}
unsafe {
ioport::outb(port + 4, 0x0f);
}
Ok(Self { port })
}
pub fn poll_has_data(&self) -> bool {
unsafe { ioport::inb(self.port + 5) & 0x01 != 0 }
}
pub fn read_poll(&mut self) -> u8 {
while !self.poll_has_data() {
hint::spin_loop();
}
unsafe { ioport::inb(self.port) }
}
pub fn poll_has_space(&self) -> bool {
unsafe { ioport::inb(self.port + 5) & 0x20 != 0 }
}
pub fn write_poll(&mut self, x: u8) {
while !self.poll_has_space() {
hint::spin_loop();
}
unsafe {
ioport::outb(self.port, x);
}
}
}
impl fmt::Write for Com {
fn write_str(&mut self, s: &str) -> fmt::Result {
for b in s.bytes() {
self.write_poll(b);
}
Ok(())
}
}
+23
View File
@@ -0,0 +1,23 @@
use core::arch::asm;
pub unsafe fn inb(port: u16) -> u8 {
let x: u8;
unsafe {
asm!(
"in al, dx",
in("dx") port,
lateout("al") x
);
}
x
}
pub unsafe fn outb(port: u16, x: u8) {
unsafe {
asm!(
"out dx, al",
in("al") x,
in("dx") port,
);
}
}
+59
View File
@@ -0,0 +1,59 @@
#![no_std]
#![no_main]
#![feature(custom_test_frameworks)]
#![test_runner(crate::test_runner)]
mod com;
mod ioport;
mod spin;
mod vga;
use core::{
arch::{asm, global_asm},
fmt::{self, Write},
panic::PanicInfo,
ptr, slice,
};
global_asm!(include_str!("asm/trampoline.s"));
#[panic_handler]
fn panic(info: &PanicInfo) -> ! {
vga_println!("panic!");
if let Some(location) = info.location() {
vga_println!("{}", location);
}
vga_println!("{}", info.message());
hlt()
}
#[unsafe(no_mangle)]
pub extern "C" fn _start() -> ! {
vga::vga_init();
unsafe {
com::try_com1_init();
}
let gdt_ptr = ptr::with_exposed_provenance::<u64>(0xe000);
let gdt_slice = unsafe { slice::from_raw_parts(gdt_ptr, 4) };
vga_println!("hello from rust :)");
vga_println!("{:016x}", gdt_slice[0]);
vga_println!("{:016x}", gdt_slice[1]);
vga_println!("{:016x}", gdt_slice[2]);
vga_println!("{:016x}", gdt_slice[3]);
com1_println!("hello serial!");
hlt()
}
#[inline]
fn hlt() -> ! {
loop {
unsafe {
asm!("hlt");
}
}
}
+104
View File
@@ -0,0 +1,104 @@
use core::{
cell::UnsafeCell,
hint,
ops::{Deref, DerefMut},
sync::atomic::{AtomicBool, Ordering},
};
pub struct Spinlock<T> {
data: UnsafeCell<T>,
locked: AtomicBool,
}
impl<T> Spinlock<T> {
pub const fn new(data: T) -> Self {
Self {
data: UnsafeCell::new(data),
locked: AtomicBool::new(false),
}
}
pub fn lock(&self) -> SpinlockGuard<'_, T> {
// If we observe `locked` was `false`, then:
// - Use acquire ordering, so nothing inside the critical section gets reordered before we
// observed the `false` value.
// - Store `true`, so nothing else can enter the critical section until we exit it.
// Otherwise, spin until we observe a `false` value.
while self
.locked
.compare_exchange_weak(false, true, Ordering::Acquire, Ordering::Relaxed)
.is_err()
{
hint::spin_loop();
}
SpinlockGuard { lock: self }
}
/// # Safety
/// There must be no "active" `SpinlockGuards` for this lock, i.e. a `SpinlockGuard` which can be
/// used to obtain a reference to the spinlock-protected data.
unsafe fn unlock(&self) {
// Unset `locked` with release ordering so that nothing inside the critical section gets
// reordered to after we stored `false`.
self.locked.store(false, Ordering::Release);
}
/// # Safety
/// No mutable references to the spinlock-protected data may exist.
unsafe fn get<'s, 'a>(&'s self) -> &'a T
where
's: 'a,
{
unsafe { &*self.data.get() }
}
/// # Safety
/// No references to the spinlock-protected data may exist.
unsafe fn get_mut<'s, 'a>(&'s self) -> &'a mut T
where
's: 'a,
{
unsafe { &mut *self.data.get() }
}
}
unsafe impl<T> Sync for Spinlock<T> where T: Send {}
pub struct SpinlockGuard<'a, T> {
lock: &'a Spinlock<T>,
}
impl<'a, T> Deref for SpinlockGuard<'a, T> {
type Target = T;
#[inline]
fn deref(&self) -> &Self::Target {
// SAFETY:
// For the entire lifetime of the `SpinlockGuard`, `locked` remains `true`, so we have
// exclusive access to `data`, so no mutable references to `data` can exist.
unsafe { self.lock.get() }
}
}
impl<'a, T> DerefMut for SpinlockGuard<'a, T> {
#[inline]
fn deref_mut(&mut self) -> &mut Self::Target {
// SAFETY:
// For the entire lifetime of the `SpinlockGuard`, `locked` remains `true`, so we have
// exclusive access to `data`, so no other references to `data` can exist.
unsafe { self.lock.get_mut() }
}
}
impl<'a, T> Drop for SpinlockGuard<'a, T> {
fn drop(&mut self) {
// SAFETY:
// Only one `SpinlockGuard` can exist at a time for a particular lock, since we set `locked`
// to true before creating a guard and refuse to create any new ones until it is `false` again.
// Therefore, we are the only `SpinlockGuard` for the lock. Since this is the destructor, and
// we don't access the spinlock-protected data here, there are therefore no "active"
// `SpinlockGuard`s remaining for the lock.
unsafe { self.lock.unlock() }
}
}
+132
View File
@@ -0,0 +1,132 @@
use core::{fmt, ptr};
use crate::spin::Spinlock;
const VGA_ADDR: usize = 0xb8000;
const VGA_WIDTH: usize = 80;
const VGA_HEIGHT: usize = 25;
const COLOUR_MASK: u16 = 0x0a00;
pub static VGA: Spinlock<Option<VgaBuf>> = Spinlock::new(None);
#[macro_export]
macro_rules! vga_print {
($($args:tt)*) => ({
crate::vga::with_vga_buf(|vga_buf| {
::core::write!(vga_buf, $($args)*).ok();
});
})
}
#[macro_export]
macro_rules! vga_println {
($($args:tt)*) => ({
crate::vga::with_vga_buf(|vga_buf| {
::core::writeln!(vga_buf, $($args)*).ok();
});
})
}
pub fn vga_init() {
let vga_buf = unsafe { VgaBuf::new(ptr::with_exposed_provenance_mut::<u16>(VGA_ADDR)) };
let mut guard = VGA.lock();
*guard = Some(vga_buf);
}
pub fn with_vga_buf<F>(f: F)
where
F: FnOnce(&mut VgaBuf),
{
let mut guard = VGA.lock();
let vga = guard.as_mut().expect("vga not initialised");
f(vga);
}
pub struct VgaBuf {
buf: *mut u16,
col: usize,
row: usize,
}
impl VgaBuf {
pub unsafe fn new(buf: *mut u16) -> Self {
Self {
buf,
col: 0,
row: 0,
}
}
pub fn vga_write_str(&mut self, s: &str) {
for c in s.chars() {
self.vga_write_char(c);
}
}
pub fn vga_write_char(&mut self, c: char) {
let newline = c == '\n';
if newline || self.col >= VGA_WIDTH {
self.col = 0;
self.row += 1;
}
if self.row >= VGA_HEIGHT {
self.scroll();
self.row -= 1;
}
if !newline {
self.vga_write_char_at(c, self.col, self.row);
self.col += 1;
}
}
pub fn vga_write_ascii_char_at(&mut self, c: u8, col: usize, row: usize) {
let vga_val = COLOUR_MASK | u16::from(c);
if col < VGA_WIDTH && row < VGA_HEIGHT {
unsafe {
self.coord_ptr(col, row).write_volatile(vga_val);
}
}
}
pub fn vga_write_char_at(&mut self, c: char, col: usize, row: usize) {
let c = u8::try_from(c).unwrap_or(0xfe);
self.vga_write_ascii_char_at(c, col, row);
}
fn scroll(&mut self) {
unsafe {
ptr::copy(
self.coord_ptr(0, 1),
self.coord_ptr(0, 0),
VGA_WIDTH * (VGA_HEIGHT - 1),
);
for col in 0..VGA_WIDTH {
self.vga_write_ascii_char_at(0, col, VGA_HEIGHT - 1);
}
}
}
unsafe fn coord_ptr(&self, col: usize, row: usize) -> *mut u16 {
unsafe { self.buf.add((row * VGA_WIDTH) + col) }
}
}
impl fmt::Write for VgaBuf {
fn write_str(&mut self, s: &str) -> fmt::Result {
self.vga_write_str(s);
Ok(())
}
fn write_char(&mut self, c: char) -> fmt::Result {
self.vga_write_char(c);
Ok(())
}
}
unsafe impl Send for VgaBuf {}
+1
View File
@@ -0,0 +1 @@
/target
+8
View File
@@ -0,0 +1,8 @@
[package]
name = "xtask"
version = "0.1.0"
edition = "2024"
[dependencies]
eyre = "0.6.12"
kdl = "6.3.4"
+305
View File
@@ -0,0 +1,305 @@
use std::{
ffi::OsStr,
fs::{self, File, OpenOptions},
io::{self, Seek, Write},
path::{Path, PathBuf},
process::{Command, Output, Stdio},
};
use eyre::{WrapErr, eyre};
use crate::Context;
const SECTOR_SIZE: usize = 512;
const NASM_COMMON_FLAGS: &[&str] = &["-werror"];
pub fn build(ctx: &Context) -> Result<(), eyre::Error> {
let s1_src_dir = ctx.workspace.join("stage_1");
let s2_src_dir = ctx.workspace.join("stage_2");
let s3_src_dir = ctx.workspace.join("stage_3");
let build_dir = ctx.workspace.join("build");
let s1_build_dir = build_dir.join("stage_1");
let s2_build_dir = build_dir.join("stage_2");
mkdir_if_missing(&build_dir)?;
mkdir_if_missing(&s1_build_dir)?;
mkdir_if_missing(&s2_build_dir)?;
println!("building stage 1");
let s1_bin_path = build_stage_1(ctx, &s1_build_dir, &s1_src_dir)?;
println!("building stage 2");
let s2_bin_path = build_stage_2(ctx, &s2_build_dir, &s2_src_dir)?;
println!("building stage 3");
let s3_bin_path = build_stage_3(ctx, &s3_src_dir)?;
println!("creating stage 2/3 blob");
make_s23_blob(&build_dir, &s2_bin_path, &s3_bin_path)?;
Ok(())
}
fn build_stage_1(ctx: &Context, build_dir: &Path, src_dir: &Path) -> Result<PathBuf, eyre::Error> {
let src_paths = ls_with_extension(src_dir, "s")?;
let [src_path] = &*src_paths else {
return Err(eyre!(
"expected exactly one stage 1 source file, found {}",
src_paths.len()
));
};
let bin_path = build_dir.join("s1.bin");
let include_dir = ctx.workspace.join("include");
Command::new("nasm")
.args(["-f", "bin"])
.args(NASM_COMMON_FLAGS)
.arg("-I")
.arg(&include_dir)
.arg("-o")
.arg(&bin_path)
.arg(src_path)
.stdout(Stdio::inherit())
.stderr(Stdio::inherit())
.run_ok()?;
Ok(bin_path)
}
fn build_stage_2(ctx: &Context, build_dir: &Path, src_dir: &Path) -> Result<PathBuf, eyre::Error> {
let include_dir = ctx.workspace.join("include");
let src_paths = ls_with_extension(src_dir, "s")?;
let mut obj_paths = Vec::new();
for src_path in src_paths {
let Some(file_stem) = src_path.file_stem() else {
continue;
};
let obj_path = build_dir.join(file_stem).with_extension("o");
Command::new("nasm")
.args(["-f", "elf"])
.args(NASM_COMMON_FLAGS)
.arg("-I")
.arg(&include_dir)
.arg("-o")
.arg(&obj_path)
.arg(src_path)
.stdout(Stdio::inherit())
.stderr(Stdio::inherit())
.run_ok()?;
obj_paths.push(obj_path);
}
let linker_file_path = src_dir.join("link.ld");
let bin_path = build_dir.join("s2.bin");
Command::new("ld")
.args(["-m", "elf_i386"])
.arg("-T")
.arg(&linker_file_path)
.arg("-o")
.arg(&bin_path)
.args(&obj_paths)
.stdout(Stdio::inherit())
.stderr(Stdio::inherit())
.run_ok()?;
Ok(bin_path)
}
fn build_stage_3(ctx: &Context, stage_3_src_dir: &Path) -> Result<PathBuf, eyre::Error> {
Command::new(ctx.cargo)
.arg("build")
.arg("--release")
.current_dir(stage_3_src_dir)
.stdout(Stdio::inherit())
.stderr(Stdio::inherit())
.run_ok()?;
let bin_path = {
let mut bin_path = stage_3_src_dir.to_owned();
bin_path.extend(["target", "protected32", "release", "stage_3"]);
bin_path
};
Ok(bin_path)
}
fn make_s23_blob(
build_dir: &Path, s2_bin_path: &Path, s3_bin_path: &Path,
) -> Result<(), eyre::Error> {
let out_path = build_dir.join("s23.bin");
let mut out_file = OpenOptions::new()
.write(true)
.truncate(true)
.create(true)
.open(&out_path)
.wrap_io_err(IoOp::Open, &out_path)?;
let mut buf = [0u8; SECTOR_SIZE];
let s2_len_sectors = read_sectors_from_to(s2_bin_path, &mut out_file, &out_path, &mut buf)?;
if s2_len_sectors == 0 {
return Err(eyre!("empty stage 2"));
}
let s3_offset_sectors_16 = u16::try_from(s2_len_sectors).wrap_err("stage 3 offset overflow")?;
let s3_len_sectors = read_sectors_from_to(s3_bin_path, &mut out_file, &out_path, &mut buf)?;
if s3_len_sectors == 0 {
return Err(eyre!("empty stage 3"));
}
let s3_len_sectors_16 = u16::try_from(s3_len_sectors).wrap_err("stage 3 length overflow")?;
out_file
.seek(io::SeekFrom::Start(0))
.wrap_io_err(IoOp::Seek, &out_path)?;
// Write the stage 2 data section fields
out_file
.write_all(&s3_offset_sectors_16.to_le_bytes())
.wrap_io_err(IoOp::Write, &out_path)?;
out_file
.write_all(&s3_len_sectors_16.to_le_bytes())
.wrap_io_err(IoOp::Write, &out_path)?;
out_file.flush().wrap_io_err(IoOp::Flush, &out_path)?;
Ok(())
}
fn mkdir_if_missing(path: &Path) -> Result<(), eyre::Error> {
if !fs::exists(path).wrap_io_err(IoOp::Stat, path)? {
fs::create_dir(path).wrap_io_err(IoOp::Open, path)?;
}
Ok(())
}
fn ls_with_extension(path: &Path, ext: &str) -> Result<Vec<PathBuf>, eyre::Error> {
let read_dir = fs::read_dir(path).wrap_io_err(IoOp::Read, path)?;
let mut paths = Vec::new();
for dir in read_dir {
let dir = dir.wrap_io_err(IoOp::Read, path)?;
if dir.path().extension() == Some(OsStr::new(ext)) {
paths.push(dir.path());
}
}
Ok(paths)
}
fn read_retry_eintr<T>(r: &mut T, buf: &mut [u8]) -> Result<usize, io::Error>
where
T: io::Read,
{
loop {
match r.read(buf) {
Ok(n) => return Ok(n),
Err(err) => match err.kind() {
io::ErrorKind::Interrupted => (),
_ => return Err(err),
},
}
}
}
fn read_sectors_from_to(
src_path: &Path, dst_file: &mut File, dst_path: &Path, buf: &mut [u8],
) -> Result<u64, eyre::Error> {
let mut total_read = 0u64;
let mut src_file = File::open(src_path).wrap_io_err(IoOp::Open, src_path)?;
loop {
match read_retry_eintr(&mut src_file, buf).wrap_io_err(IoOp::Read, src_path)? {
0 => break,
n => {
total_read += n as u64;
dst_file
.write_all(&buf[..n])
.wrap_io_err(IoOp::Write, dst_path)?;
}
}
}
let remainder = (total_read % (SECTOR_SIZE as u64)) as usize;
let padding = (SECTOR_SIZE - remainder) % SECTOR_SIZE;
if padding != 0 {
// Pad with 0xf4 since it encodes HLT, in case we accidentally jump to it.
buf[..padding].fill(0xf4);
dst_file
.write_all(&buf[..padding])
.wrap_io_err(IoOp::Write, dst_path)?;
}
let total_bytes = total_read + padding as u64;
assert!(total_bytes % SECTOR_SIZE as u64 == 0);
Ok(total_bytes / SECTOR_SIZE as u64)
}
trait CommandExt {
fn run_ok(&mut self) -> Result<Output, eyre::Error>;
}
impl CommandExt for Command {
fn run_ok(&mut self) -> Result<Output, eyre::Error> {
let output = self
.output()
.wrap_err_with(|| format!("failed to run {:?}", self))?;
if !output.status.success() {
return Err(eyre!("command failed: {:?}", self));
}
Ok(output)
}
}
trait WrapIoError<T> {
fn wrap_io_err(self, op: IoOp, path: &Path) -> Result<T, eyre::Report>;
}
impl<T, E> WrapIoError<T> for Result<T, E>
where
Self: WrapErr<T, E>,
{
fn wrap_io_err(self, op: IoOp, path: &Path) -> Result<T, eyre::Report> {
self.wrap_err_with(|| format!("failed to {} {}", op.name(), path.to_string_lossy()))
}
}
#[derive(Clone, Copy)]
enum IoOp {
Read,
Write,
Stat,
Open,
Seek,
Flush,
}
impl IoOp {
fn name(self) -> &'static str {
match self {
IoOp::Read => "read",
IoOp::Write => "write",
IoOp::Stat => "stat",
IoOp::Open => "open",
IoOp::Seek => "seek",
IoOp::Flush => "flush",
}
}
}
+44
View File
@@ -0,0 +1,44 @@
use std::{
env,
path::{Path, PathBuf},
};
use eyre::{ContextCompat, eyre};
mod build;
mod mkimg;
fn main() -> Result<(), eyre::Error> {
let mut args = env::args_os().skip(1);
let task = args.next().context("no task provided")?;
let task = task
.to_str()
.with_context(|| format!("invalid utf-8 \"{}\"", task.to_string_lossy()))?;
let manifest_dir =
PathBuf::from(env::var_os("CARGO_MANIFEST_DIR").context("CARGO_MANIFEST_DIR not set")?);
let workspace_dir = manifest_dir
.parent()
.context("invalid CARGO_MANIFEST_DIR")?;
let cargo_path = PathBuf::from(env::var_os("CARGO").context("CARGO not set")?);
let ctx = Context {
workspace: workspace_dir,
cargo: &cargo_path,
};
match task {
"build" => build::build(&ctx),
"mkimg" => mkimg::mkimg_bios_gpt(&ctx),
_ => Err(eyre!("unknown task \"{}\"", task)),
}
}
struct Context<'a> {
workspace: &'a Path,
cargo: &'a Path,
}
+23
View File
@@ -0,0 +1,23 @@
use crate::Context;
// LBA 0: MBR
// LBA 1: partition header
// LBA 2..33: partition table entries
// LBA 34..n: usable blocks
// LBA -33..-2: partition table entries (dup)
// LBA -1: partition header (dup)
struct Partition {
type_guid: [u8; 16],
part_guid: [u8; 16],
lba_start: u64,
lba_end: u64,
attr: u64,
name: String,
}
pub fn mkimg_bios_gpt(ctx: &Context) -> Result<(), eyre::Error> {
println!("dir={}", ctx.workspace.to_string_lossy());
Ok(())
}