Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assembly popping an empty stack

Tags:

x86

assembly

a86

I'm learning assembly and wondering what happend when you pop an empty stack or increasing SP (Stack Pointer) when it's already FFFE for example:

seg1 segment 
       org 100h 
       pop ax
       mov ah,4ch 
       int 21h
seg1 ends

When I run the program through the debugger I saw that SP wil point to SP = 0000 after pop command is executed. Why the SP point to 0000? Is it because the max SP in the memory is FFFF and it just loop to the first point? (I know that SP will only increase or decrease by 2 because push and pop is always 2 byte) And will the program pop anythign at SP = 0000 when the command is executed?

I'm using a86 macro assembler, Oracle VM VirtualBox. Thank you.

like image 330
Andre Avatar asked Jul 20 '26 05:07

Andre


2 Answers

This effect is called "wraparound". FFFE plus 2 would be 10000, but the first bit is just cut away, so the result is 0000.

This is useful, among others, for signed operations: FFFE is equivalent to -2. -2 + 2 = 0.

And yes, the next pop will load the value at SS:0000 and increment SP, whereas a push will also cause a wraparound and store a value at SS:FFFE.

like image 200
rkhb Avatar answered Jul 21 '26 23:07

rkhb


SP is 16 bit register.

When you POP, SP has "2" added to it. FFFE+2 produces the value 0.

This happens without error on older architectures (e.g., X8086) and probably in x86-32 running in 16 bit real mode (I'd have to check the manuals). While it does happen, you should consider this to be programming error on your part, as it violates the intent of the stack pointer, to linearly scan the stack area.

On x86-32 or -64 in protected mode, falling of the edge of the stack area will generally produce an illegal memory access, caused by the OS very carefully marking the area beyond your valid stack is "not valid".

like image 45
Ira Baxter Avatar answered Jul 21 '26 23:07

Ira Baxter