I am learning x86 assembly using Nasm on Linux(Debian 12).
I already know what is stack, so I thought when we code in assembly, we implement it ourselves.
But I saw instructions like push and pop which are meant for operations on stack. So is there a stack already implemented and ready to use? if yes, then how is it used and how can we use it. I created a strlen function in asm
section .data
hello db "Hello World!",10,0
section .text
global _start
_start:
mov rax,hello
call strlen
mov rax,1
mov rdi,1
mov rsi,hello
syscall
mov rax,60
mov rdi,0
syscall
strlen:
mov rdx,0
strlen_loop:
cmp byte[rax],0
jz strlen_finished
inc rdx
inc rax
jmp strlen_loop
strlen_finished:
ret
This calculates the length of the string and prints it. I could use push rax to put the value of the rax onto the stack so that the value which was already in rax doesn't get lost. So we only use this already implemented stack this way or does the processor also uses this stack in some other ways? And what is the difference between this stack and the stack that we will create ourselves?
I was expecting that we ourselves had to implement the stack to keep track of the functions local variables and stuff.
push,pop,call,ret. You (the programmer) can also use the stack, e.g., to pass parameters to subroutines or to store local variables/arrays. Check your favourite x86 assembly guide for an introduction -- IMO as it is the question is too broad for stackoverflow.called yourstrlen. Consult the basic architecture manual section 6.2 STACKS. Ask a specific question if you get stuck.sp/esp/rspregisters (in combination withsssegment if the segment matters). For instance, to initialise an array variable on the stack you probably wouldn't loop forpushinstructions that implicitly use the stack pointer register, but rather subtract the entire array size using one instruction (egsub rsp, 256) and then copy to the memory explicitly pointed to byrspusing a normal memory copy.