Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NASM - Get number of items in stack

Tags:

assembly

nasm

I am trying to figure out how to get the number of items in the stack by subtracting the sp register with bp. What am I doing wrong? I get totally wrong result

MOV bp, 0x7E00
MOV sp, bp

PUSH 'A'
PUSH 'B'
PUSH 'C'

POP bx
MOV al, bl
CALL _printchar

POP bx
MOV al, bl
CALL _printchar

MOV bx, sp
SUB bx, bp
ADD bx, 48 ;To get ascii number
MOV al, bl
CALL _printchar

This is the output:

CB.

like image 372
Erik W Avatar asked May 09 '15 18:05

Erik W


1 Answers

A really confusing thing about the stack is that it grows down.

Compared to most people's mental image of a stack, the stack you work with in assembly is "upside down". The "bottom" of the stack has the highest memory address, and the "top" has the lowest. When you push 2 bytes onto the stack, 2 bytes are subtracted from the stack pointer, not added to it. (If you think about it in terms of memory partitioning, this is actually safer)

So the result of your SUB was -2, which is '.' in ascii. You can't just switch the operands around, because the result needs to go into the first operand, so it should be a general purpose register. Instead, alter the MOV operations before the SUB.

like image 135
1.618 Avatar answered Oct 20 '22 02:10

1.618