Purpose of stack register(s) in holding 0x7c00

40 Views Asked by At

I have a problem in understanding the curtain part of the code, how it works and what's behind the operating stack register(s).

; that part i'm referring to
mov ss, ax
mov sp, 0x7c00 

I need an explanation of that code part and its purpose, maybe the info will be from the source such as documentation or forum you're about to send the link to, you can always correct me if i'm wrong about something.

1

There are 1 best solutions below

0
Sep Roland On
mov ss, ax
mov sp, 0x7c00

That code comes from my answer at No BIOS output from sector 1

org 0x7C00
bits 16

XOR  AX, AX
MOV  DS, AX
MOV  ES, AX
MOV  SS, AX
MOV  SP, 0x7C00

You're asking about the purpose of the lines that setup the SS and SP registers.
Well, every program at some point will be using the stack.

  • It could be because you want to execute a subroutine for which you would use a call instruction that places a return address on the stack and use a ret instruction that removes that very same return address from the stack.
  • Or you could choose to preserve one or more registers and then the stack would be a convenient place to do so.
  • Or you could desire to make use of the BIOS or DOS api for which you would use the int instruction that places a copy of the FLAGS register, the CS segment register, and the IP register on the stack. Upon returning the iret instruction will then restore those items.

And then there are the interrupt handlers like timer, keyboard, and others that operate autonomously and also need the stack properly setup.

So you see that the stack is very important.
But why did I initialize SS:SP to 0x0000:0x7C00?

When BIOS gave your bootloader program control of the machine a functional stack already existed. Sadly, you can't count on the fact that it would reside at a place that does not interfere with whatever it is that you plan to do on the machine. The obvious solution is to place the stack yourself at a safe location, and the safest spot for a bootloader that itself sits at the linear address 0x7C00 is just beneath it in memory. So the stackpointer SP (that represents the top of the stack memory) is set to 0x7C00 which provides a stack memory of some 30000 bytes. That's more than enough for even the most demanding bootloader.

MOV  SS, AX
MOV  SP, 0x7C00

You should always change these registers in tandem and in this particular order! The x86 cpu has a special safety mechanism that makes it impossible for an interrupt to execute after a write to the SS segment register. pop ss enjoys the same protection as a mov ss, r/m16. If the programmer then uses this window to assign a value to the companion SP register, there's no more risk of a malformed stackpointer SS:SP which would be a disastrous event.