Skip to content

Instantly share code, notes, and snippets.

@qookei
Last active November 15, 2019 17:00
Show Gist options
  • Save qookei/3a21f5cac3f10e55828f7cb590861899 to your computer and use it in GitHub Desktop.
Save qookei/3a21f5cac3f10e55828f7cb590861899 to your computer and use it in GitHub Desktop.
Bootsector ELF loader
; to use, compile your elf binary to run, and update BINARY_SIZE accordingly,
; then compile this file with `nasm -fbin elf_ldr.asm -o elf_ldr.bin`
; and concatenate the elf_ldr.bin and your elf file with `cat elf_ldr.bin <your.elf> >image`
bits 16
org 0x7C00
BINARY_SIZE equ 20 ; in sectors
entry:
cli
cld
mov sp, 0x7C00
in al, 0x92
or al, 2
out 0x92, al
xor ax, ax
mov ds, ax
mov ss, ax
mov si, disk_load_struct
mov ah, 0x42
int 0x13
lgdt [gdt]
mov eax, cr0
or eax, 1
mov cr0, eax
jmp 0x08:.prot
.prot:
bits 32
mov ax, 0x10
mov ds, ax
mov es, ax
mov ss, ax
mov gs, ax
mov fs, ax
mov edx, 0x7E00 ; elf base
mov dword ebx, [edx + 28] ; e_phoff
movzx ecx, word [edx + 44] ; e_phnum
push dword [edx + 24] ; e_entry
.ph_loop:
push ecx
cmp dword [edx + ebx], 1
jne .skip
mov ecx, [edx + ebx + 20] ; p_memsz
mov edi, [edx + ebx + 12] ; p_paddr
xor al, al
rep stosb
mov esi, [edx + ebx + 4] ; p_offset
add esi, edx ; + elf base
mov edi, [edx + ebx + 12] ; p_paddr
mov ecx, [edx + ebx + 16] ; p_filesz
rep movsb
.skip:
add ebx, 32
pop ecx
dec ecx
test ecx, ecx
jz .done
jmp .ph_loop
.done:
ret
jmp $
; ------ data -------
disk_load_struct:
db 16
db 0
dw BINARY_SIZE
dw 0x0000
dw 0x07E0
dq 1
gdt:
dw 23
dd gdt
dw 0
dq 0x00cf9a000000ffff
dq 0x00cf92000000ffff
times 510 - ($-$$) db 0
dw 0xAA55
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment