Skip to content

Instantly share code, notes, and snippets.

@i3abghany
Created January 7, 2024 01:11
Show Gist options
  • Save i3abghany/e01e007e4103b1ec03cb9f3e2c1164ad to your computer and use it in GitHub Desktop.
Save i3abghany/e01e007e4103b1ec03cb9f3e2c1164ad to your computer and use it in GitHub Desktop.
bootloader.asm
use16
org 0x7c00
; Set stack
mov bp, 0x8000
mov sp, bp
; Load 2nd stage
mov bx, 0x07E0
mov es, bx
mov ds, bx
xor bx, bx
mov al, 0x01 ; number of sectors to read
mov ch, 0x00 ; cylinder number
mov cl, 0x02 ; sector number
mov dh, 0x00 ; head number
mov dl, 0x80 ; drive number (using a disk drive in qemu)
clc
mov ah, 0x02
int 0x13
jc error ; error handling is omitted, not important & doesn't cause problems
jmp 0x07E0:0x00
times 510 - ($-$$) db 0
dw 0xaa55
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; second stage code
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
use16
org 0x7E00
bootsect_second_stage:
; WITHOUT THIS BIT IT DOESN'T WORK...
; WHY DO I NEED TO SET THE SEGMENT REGISTERS to 0... (and not 0x07E0 for example)?
mov bx, 0
mov ds, bx
mov es, bx
mov fs, bx
mov gs, bx
mov ss, bx
call switch_to_protected_mode
cli
hlt
gdt_start:
gdd_null:
dq 0
gdt_code:
dw 0xFFFF
dw 0
db 0
db 10011010b
db 11001111b
db 0
gdt_data:
dw 0xFFFF
dw 0
db 0
db 10010010b
db 11001111b
db 0
gdt_end:
gdt_descriptor:
dw gdt_end - gdt_start - 1
dd gdt_start
CODE_SEG equ gdt_code - gdt_start
DATA_SEG equ gdt_data - gdt_start
switch_to_protected_mode:
mov bx, switching_to_protected_mode
call print_str
cli
lgdt [gdt_descriptor]
mov eax, cr0
or eax, 1
mov cr0, eax
jmp CODE_SEG:protected_mode_start
ret ; Should never be reached
use32
protected_mode_start:
mov ax, DATA_SEG
mov ds, ax
mov es, ax
mov fs, ax
mov gs, ax
mov ss, ax
mov esp, 090000h
; Write 'A' to the middle of the screen (beginning of the video memory is at 0xB8000)
mov edi, 0xB85EC
mov byte [edi], 'A'
mov edi, 0xB85ED
mov byte [edi], 4
hlt
times 512 - ($ - $$) db 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment