Gyan Prakash
Gyan Prakash

Reputation: 53

Linking first and second stage bootloader

I am writing a two stage bootloader Here is my boot.asm

[org 0x7c00]
[bits 16]
xor ax, ax
mov ds, ax
mov es, ax
xor bx, bx
mov ah, 0x0E
mov al, 'A'
int 0x10
jmp 0x8000
cli
hlt
times 510 - ($-$$) db 0
dw 0xAA55

And boot2.asm

[org 0x8000]
[bits 16]
xor ax, ax
mov ds, ax
mov es, ax
xor bx, bx
mov ah, 0x0E
mov al, 'B'
int 0x10

I compile it using

nasm -f bin -o boot.bin boot.asm
nasm -f bin -o boot2.bin boot2.asm

It compiles without any error or warning. But how will I put stage 2 at 0x8000 and link stage1 and stage2 to work together?

Upvotes: 1

Views: 891

Answers (2)

Martin Rosenau
Martin Rosenau

Reputation: 18493

But how will I put stage 2 at 0x8000 ...

Unfortunately, I don't use "nasm" but other assemblers. But I'd expect that you have to change [org 0x7e00] to [org 0x8000].

... and link stage1 and stage2 to work together?

That's not as easy as you think:

The BIOS will load one sector (510 bytes plus 2 bytes 0xAA55) into the memory at 0x7C00. Using a normal BIOS there is no possibility to load more data!

The code in these 510 bytes ("stage 1") has to load the "state 2" into the memory: It may use functions ah=2 or ah=0x42 of int 0x13 to do so.

If you have your own floppy format, this is quite simple:

You store "stage 2" in the second sector of the floppy disk and load the second sector.

If you want to load "stage 2" from a file system (e.g. from a file from a FAT-formatted disk), this is more tricky.

Upvotes: 1

Likely you are asking how to combine the first and second stage into one file. If so:
On Linux:

cat boot.bin boot2.bin > final_file.file_format

On Windows:

copy /b boot.bin+boot2.bin  final_file.file_format

To load the second stage from the bootloader you can use the following code:

mov ah, 0x02      ; Read disk BIOS call 
mov cl, 0x02      ; sector to start reading from
mov al, 1         ; number of sectors that will be read (modify if your second stage grows)
mov ch, 0x00      ; cylinder number
mov dh, 0x00      ; head number
xor bx, bx
mov es, bx        ; ES=0x0000
mov bx, 0x8000    ; ES:BX(0x0000:0x8000) forms complete address to read sectors to
; DL should contain the boot disk number passed to the bootloader by the BIOS
int 0x13          ; Make BIOS disk services call (Int 0x13/AH=2) to read sectors
; For simplicity assume the disk read was successful
jmp 0x0000:0x8000 ; FAR JMP to second stage and ensure CS=0x0000
                  ; since CS is not guaranteed to be 0x0000 when control is transferred
                  ; to our bootloader

Upvotes: 2

Related Questions