I know that in the end of Master Boot Record (MBR) there is a magic number that tells BIOS it is the bootloader, And that we need to fill in the amount of bytes left until it is 512 bytes (MBR size), but how can do we calculate the amount of bytes that remain?
[bits 16] ; 16 bits assembly
[org 0x7c00]
start:
;; Call VideoService interrupt 0x10
;; ah = 0x00 -> SetVideoMode
;; al = 0x13 -> 320x200 16 color
mov ah, 0x00
mov al, 0x13
int 0x10
times 510 - ($ - $$) db 0 ; instead of 510, what number do I need to use?
dw 0xaa55 ; magic number tells BIOS it is the bootloader
Instead of 510, what number do I need to use?
We always need 510. That's 512 - 2 (the signature) and the $-$$ takes care of the rest
Can we write whatever we want without needing to change
times
?As long as the expression 510 - ($ - $$) is non-negative, yes. This will happen when the code size (which is given by $ - $$) becomes bigger than 510 bytes. The assembler will complain, so you'll know if that happens. Also, technically speaking $-$$ works as long as you have a single section of code for the first stage of the bootloader, but that's almost always the case (if not always). (Margaret Bloom)
How does
times
work?$
is the current address,$$
is the start of the section. So$-$$
gives how many bytes you have used so far.510-($-$$)
thus gives you how many are left to 510 and that amount of zeroes are added. Thedw 0xaa55
then provides the signature in the final two bytes, bringing up the total to 512 to fill your sector. (Jester)