Compare commits

...
52 Commits
Author SHA1 Message Date
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
32 changed files with 3407 additions and 143 deletions

No files matched your search

+4
View File
@@ -0,0 +1,4 @@
*.bin
.pc
target/
+3
View File
@@ -0,0 +1,3 @@
[submodule "seabios"]
path = seabios
url = https://github.com/coreboot/seabios.git
+87 -118
View File
@@ -3,35 +3,25 @@
; --------------------------------------------------------------------
; R | 0x000000 - 0x000400: real-mode interrupt vector table
; R | 0x000400 - 0x000500: bios data area
; U | 0x000500 - 0x007c00: stack
; U | 0x000500 - 0x004000: main stack
; U | 0x004000 - 0x006a00: globals
; U | 0x006a00 - 0x007c00: memory map
; 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 | 0x0c8000 - 0x0f0000: bios expansions
; 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
%include "defines.s"
; BIOS puts our boot sector at 0000:7c00
org 0x7c00
[org BOOT0_LOADPOINT]
; We're (probably) in real mode
bits 16
[bits 16]
main:
; Disable interrupts
cli
@@ -40,10 +30,10 @@ bits 16
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.
; 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, 0x7c00
mov bp, STACK_BASE
mov sp, bp
; Segment for VGA (0xb800 * 16 = 0xb8000)
@@ -63,7 +53,7 @@ bits 16
mov di, 0x00
mov ah, 0x08
int 0x13
jc .panic
jc panic
; Load sectors per track into cx & spill
and cl, 0x3f
xor ch, ch
@@ -76,14 +66,14 @@ bits 16
; Load LBA 1.
mov ax, 1
mov bx, 0x7e00
call .read_lba
call read_lba
; Check the GPT header magic "EFI PART"
mov cx, 8
mov si, .gpt_magic
mov cx, GPT_MAGIC_LEN
mov si, gpt_magic
mov di, 0x7e00
repe cmpsb
jne .panic
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
@@ -91,10 +81,9 @@ bits 16
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
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]
@@ -115,22 +104,22 @@ bits 16
; - 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
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
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!
@@ -157,53 +146,56 @@ bits 16
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
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 - 0x12]
cmp [bp - 0x0a], dx
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
jbe panic
; If we haven't loaded any sectors yet, load the first one.
cmp word [bp - 0x16], 0 ; Load number of sectors loaded
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 - 0x18] ; Load current entry index within the current sector
cmp [bp - 0x10], ax ; Compare to entries per 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 - 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
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:
mov ax, [bp - 0x18] ; Load current LBA
mov bx, 0x8000 ; Read sector just past end of the GPT header so we can keep it around
call .read_lba
inc word [bp - 0x16] ; Increment number of sectors loaded
; 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:
mov ax, [bp - 0x14] ; Load current entry index within current sector
; 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 - 0x0e] ; Get the byte offset in the current sector of the current entry
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)
mov cx, 16 ; GUID is 16 bytes
mov si, .guid_linux
; 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 - 0x12] ; Increment current entry index
inc word [bp - 0x14] ; Increment current entry index within the current sector
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
push ax ; Address of the GPT entry for stage 2
mov si, ax
; Load partition LBA start.
@@ -211,91 +203,68 @@ bits 16
mov ebx, [si + 0x24]
; Ensure it fits in 16 bits.
or ebx, ebx
jnz .panic
jnz panic
cmp ebx, 0xffff
ja .panic
ja panic
; Load partition LBA end.
mov ecx, [si + 0x28]
mov edx, [si + 0x2c]
; Assert that the end LBA is greater than the start LBA, so we have at least one sector to load.
; TODO: is the end LBA inclusive?
; 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
jae .panic
ja panic
.stage2_end_lba_ok:
mov bx, 0x8200
call .read_lba
; TODO: jump to the sector we just read
mov al, [0x7e00]
mov byte fs:[0x0000], al
mov al, [0x8000]
mov byte fs:[0x0002], al
hlt
mov bx, BOOT1_LOADPOINT
call read_lba
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. Possibly bx? TODO: double check
; ngl probably best to assume everything is clobbered because it's a bios interrupt
.read_lba:
; 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
; FIXME: we should probably get our globals from somewhere else, in case we want to change bp for
; a function call
div word [bp - 0x04] ; Divide by sectors per track. dx = mod (sector - 1), ax = div (temp)
; 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 ; Put sector into cx (bios will read sector from cl)
inc cx
xor dx, dx
div word [bp - 0x06] ; Divide by number of heads. dx = mod (head), ax = div (cylinder)
; 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 - 0x02] ; Load drive number
mov dl, byte [bp - BOOT_DRIVE]
mov ah, 0x02
mov al, 1
int 0x13 ; Read sector
jc .panic
; Read sector
int 0x13
jc panic
ret
.panic:
panic:
mov ax, 0x0003
int 0x10
mov word fs:[0x0000], 0x4f21
hlt
; TODO: enable A20
gpt_magic db "EFI PART"
GPT_MAGIC_LEN equ $ - gpt_magic
; TODO: load a second stage
; 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
; 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
; MBR bootstrap field is 440 bytes long
%if ($ - $$) > 440
%error "exceeded mbr bootstrap field size"
%endif
+1097 -19
View File
File diff suppressed because it is too large. Load diff
+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
}
}
+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,
}
+74
View File
@@ -0,0 +1,74 @@
%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
%macro fnstart 0
push bp
mov bp, sp
%endmacro
%macro fnret 0
pop bp
ret
%endmacro
+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
+29 -6
View File
@@ -1,17 +1,40 @@
run:
qemu-system-x86_64 -monitor stdio -drive format=raw,file=disk.bin
qemu-system-x86_64 \
-monitor stdio \
-no-reboot \
-bios seabios/out/bios.bin \
-m 512M \
-drive format=raw,file=disk.bin
build:
nasm -f bin -o boot0.bin boot0.s
nasm -f bin -Iinclude -o boot0.bin boot0.s
cd boot1; cargo build --release
# nasm -f bin -Iinclude -o boot1.bin boot1.s
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:
parted --script disk.bin mklabel gpt
parted --script disk.bin mkpart test 34s 50%
parted --script disk.bin type 1 0fc63daf-8483-4772-8e79-3d69d8477de4
parted --script disk.bin mkpart dummy1 34s 47s
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:
write_stage1:
dd if=/dev/zero of=disk.bin bs=440 count=1 conv=notrunc
dd if=boot0.bin of=disk.bin conv=notrunc
write_stage2:
# dd if=boot1.bin of=disk.bin bs=512 seek=70 conv=notrunc
dd if=boot1/target/target_protected/release/boot1 of=disk.bin bs=512 seek=70 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
+25
View File
@@ -2,18 +2,26 @@
- <https://www.felixcloutier.com/x86/>
- <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.02rc3/html/nasmdo10.html>
- <https://wiki.osdev.org/Real_Mode>
- <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://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
- <https://wiki.osdev.org/Boot_Sequence>
- <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
- <https://wiki.osdev.org/Memory_Map_(x86)>
- <https://wiki.osdev.org/Detecting_Memory_(x86)>
- <http://www.uruk.org/orig-grub/mem64mb.html>
## BIOS interrupts
- <https://en.wikipedia.org/wiki/BIOS_interrupt_call>
@@ -30,5 +38,22 @@
- <https://en.wikipedia.org/wiki/Code_page_437>
## ELF
- <http://www.skyfree.org/linux/references/ELF_Format.pdf>
- <https://wiki.osdev.org/ELF>
- <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://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>
Submodule
+1
Submodule seabios added at e5f2e4c696.