Skip to content

Instantly share code, notes, and snippets.

@sonald
Created March 13, 2015 06:15
Show Gist options
  • Save sonald/68d9848fae30001f6145 to your computer and use it in GitHub Desktop.
Save sonald/68d9848fae30001f6145 to your computer and use it in GitHub Desktop.
bootsect and small kernel
;; simple bootsector os
[org 0x7c00]
[bits 16]
mov bp, 0x9000
mov sp, bp
mov bx, msg
call print
call load_disk
jmp start
load_disk: ;; load sector 2 and 3
pusha
mov ah, 0x02 ; read disk
mov dl, 0 ; drive 0 (floppy)
mov ch, 0 ; cylinder
mov dh, 0 ; head
mov cl, 2 ; # of first sector
mov al, 2 ; count
; read to es:bx
mov bx, 0x7e00 ;; just load data at 0x7e00, right after bootsect
clc
int 0x13
jc .read_error
cmp al, 2
jne .read_error
popa
ret
.read_error:
mov bx, DISK_ERROR_MSG
call print
jmp $
ret
DISK_ERROR_MSG:
db 'disk read failed', 0
; bx = string
print:
pusha
.next:
mov al, [bx]
cmp al, 0
je .end
mov ah, 0x0e
mov al, [bx]
int 0x10
inc bx
jmp .next
.end:
popa
ret
msg:
db 'Booting...', 0
times 510 - ($-$$) db 0
dw 0xaa55
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; minimal Protect mode data structure
;; flat-mode
gdt:
; empty one
dd 0
dd 0
.code:
dw 0xffff ; limit
dw 0 ; base
db 0 ; base
dw 0xcf9a
db 0
.data:
dw 0xffff
dw 0
db 0
dw 0xcf92
db 0
gdt_end:
gdt_desc:
dw gdt_end - gdt - 1
dd gdt
;; global description table.
CODE_SEL equ gdt.code - gdt
DATA_SEL equ gdt.data - gdt
VIDEO_BASE equ 0xb8000
start:
cli
lgdt [gdt_desc]
; enable PM
mov eax, cr0
or eax, 0x1
mov cr0, eax
jmp CODE_SEL:pm_start
[bits 32]
pm_start:
mov ax, DATA_SEL
mov ds, ax
mov es, ax
mov gs, ax
mov fs, ax
mov ss, ax
;; Question: why not set cs and can we set cs ?
;; no difference between code and data segs
;; where is esp ?
call clear
push PM_WELCOME
push 26
push 11
call pm_print
push PM_WELCOME2
push 20
push 12
call pm_print
jmp $
hlt
;; void pm_print(int row, int col, char* msg)
pm_print:
push ebp
mov ebp, esp
pusha ;; if we follow x86 C calling convention, no need for this
mov edi, VIDEO_BASE ;; edi <- VIDEO_BASE
mov ecx, [ebp+0x8] ;; ecx <- row
imul ecx, 80 ;; row * 80
add ecx, [ebp+0xc] ;; row * 80 + col
imul ecx, 2 ;; (row * 80 + col) * 2
add edi, ecx ;; base + (row * 80 + col) * 2
mov esi, [ebp+0x10] ;; esi <- msg
mov ah, 0x9f ;; colored on black
cld
.repeat:
lodsb ;; al <- ds:esi
cmp al, 0
jz .finished
stosw ;; ax -> es:edi
jmp .repeat
.finished:
popa
pop ebp
ret
clear:
push ebp
mov ebp, esp
pusha
mov edi, VIDEO_BASE ;; edi <- VIDEO_BASE
xor ax, ax
mov ecx, 25 * 80
cld
rep stosw ;; ax -> es:edi
popa
pop ebp
ret
PM_WELCOME:
db 'Welcome to Small OS...', 0
PM_WELCOME2:
db 'Use Your imagination after now...', 0
times 256 dw 0xdead
times 256 dw 0xbeef
all: r
r: kernel.bin
qemu-system-x86_64 -fda $< -monitor stdio
kernel.bin: kernel.asm
nasm -f bin -o $@ $<
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment