loader.asm
Code: Select all
section .multiboot_header
header_start:
dd 0xe85250d6
dd 0
dd header_end - header_start
dd 0x100000000 - (0xe85250d6 + 0 + (header_end - header_start))
dw 0
dw 0
dd 0
header_end:
global start
extern long_mode_start
section .text
bits 32
start:
mov esp, stack_top
call check_multiboot
call check_cpuid
call check_long_mode
call set_up_page_tables
call enable_paging
lgdt [gdt64.pointer]
jmp gdt64.code:long_mode_start
hlt
check_multiboot:
cmp eax, 0x36d76289
jne .no_multiboot
ret
.no_multiboot:
mov al,"0"
jmp error
check_cpuid:
pushfd
pop eax
mov ecx, eax
xor eax, 1 << 21
push eax
popfd
pushfd
pop eax
push ecx
popfd
xor eax, ecx
jz .no_cpuid
ret
.no_cpuid:
mov al, "1"
jmp error
check_long_mode:
mov eax, 0x80000000
cpuid
cmp eax, 0x80000001
jb .no_longmode
mov eax, 0x80000001
cpuid
test edx, 1 << 29
jz .no_longmode
ret
.no_longmode:
mov al, "2"
jmp error
set_up_page_tables:
mov eax, p3_table
or eax, 0b11
mov [p4_table], eax
mov eax, p2_table
or eax, 0b11
mov [p3_table], eax
mov ecx, 0
.map_p2_table:
mov eax, 0x200000
mul ecx
mov eax, 0b10000011
mov [p2_table + ecx * 8],eax
inc ecx
cmp ecx, 512
jne .map_p2_table
ret
enable_paging:
mov eax, p4_table
mov cr3, eax
mov eax, cr4
or eax, 1 << 5
mov cr4, eax
mov ecx, 0xC0000080
rdmsr
or eax, 1 << 8
wrmsr
mov eax, cr0
or eax, 1 << 31
mov cr0, eax
ret
error:
mov dword [0xb8000], 0x4f524f45
mov dword [0xb8004], 0x4f3a4f52
mov dword [0xb8008], 0x4f204f20
mov byte [0xb800a], al
hlt
section .bss
align 4096
p4_table:
resb 4096
p3_table:
resb 4096
p2_table:
resb 4096
stack_bottom:
resb 64
stack_top:
section .rodata
gdt64:
dq 0
.code: equ $ - gdt64
dq (1 << 43) | (1 << 44) | (1 << 47) | (1 << 53)
.pointer:
dw $ - gdt64 - 1
dq gdt64
Code: Select all
global long_mode_start
section .text
bits 64
long_mode_start:
mov ax, 0
mov ss, ax
mov ds, ax
mov es, ax
mov fs, ax
mov gs, ax
extern kmain
call kmain
mov rax, 0x2f592f412f4b2f4f
mov qword[0xb8000], rax
hlt
Code: Select all
ENTRY(start)
SECTIONS
{
. = 0x0100000;
.text :
{
*(.multiboot_header)
*(.text*)
*(.rodata)
}
.data :
{
start_ctors = .;
KEEP(*( .init_array ));
KEEP(*(SORT_BY_INIT_PRIORITY( .init_array.* )));
end_ctors = .;
*(.data)
}
.bss :
{
*(.bss)
}
/DISCARD/ :
{
*(.fini_array*)
*(.comment)
}
}