Home > Software design >  How do I correctly manipulate the stack in assembly?
How do I correctly manipulate the stack in assembly?

Time:09-18

Q1) I have seen assembly code that uses [rsp 4] to access variables on the stack while others use [rbp-4]. I assume that they are both correct and that the only difference is which end of the stack frame is used.

Q2) When entering a function, we are supposed to push [rsp], and upon leaving pop rsp. However, when I leave these instructions out the code runs just fine. Why are they required? Example code is given below in test.asm.

Q3) When leaving the program in main, we are to return exit code e.g. 0 xor rdi rdi. However, when I leave this command out it still works. Same example as below in test.asm.

Q4) Is push 5 the same as mov [rsp], 5?

; test.asm
; Compiled as such (Linking with MSVC):
; nasm -f win64 -o test.obj test.asm
; /LINK /DEFAULTLIB:msvcrt.lib /DEFAULTLIB:legacy_stdio_definitions.lib /DEFAULTLIB:Kernel32.lib /SUBSYSTEM:console test.obj /OUT:test.exe
; Gives output:
; 1
; 2

bits 64
default rel

segment .data
    ifmt:    db "%d, 0xd, 0xa, 0x0

segment .text
    global main
    extern printf

PrintInt:
    sub     rsp, 40
    mov     rdx, rcx
    lea     rcx, [ifmt]
    call    printf
    add     rsp, 40
    ret

main:
    sub     rsp, 24
    mov     rcx, 1
    call    PrintInt
    mov     rcx, 2
    call    PrintInt
    add     rsp, 24
    ret

CodePudding user response:

Q1. That is correct.

Q2. push rsp, push [rsp], and pop rsp are almost never correct. There might be some specialized uses, but not for beginners. You are probably thinking of push rbp and pop rbp, which are required only if you are using rbp within the function.

Q3. When returning from main, set eax to the exit status, not edi. If you call the exit function, then pass the status as a parameter to the exit function in ecx. If the caller doesn't use the exit status, then you won't notice a difference if you don't set it.

Q4. push 5 is the same as lea rsp, [rsp-8]; mov qword [rsp], 5.

  • Related