mahmood
mahmood

Reputation: 24705

Using CALL, RET in assembly x86

Consider the following simple assembly code which uses push, pop and call

CDSEG SEGMENT
MAIN PROC FAR
    ASSUME CS:CDSEG,DS:DTSEG
    MOV AX,DTSEG
    MOV DS,AX

    MOV AX,1010H        ; (1)
    PUSH AX             ; (2)
    CALL FOO            ; (3)
    ADD AX,2            ; (7)
MAIN ENDP   
FOO PROC   
    POP AX              ; (4)
    ADD AX,1            ; (5)
    RET                 ; (6)
FOO ENDP
END MAIN

What I expect, is to see

(1) ax = 1010h, stack=????
(2) ax = 1010h, stack=1010h
(3) 
(4) ax = 1010h, stack=????
(5) ax = 1011h
(6)
(7) ax = 1012h

but, the emulator shows

(1) ax = 1010h, stack=????
(2) ax = 1010h, stack=1010h
(3) 
(4) ax = 000Ch, stack=????
(5) ax = 000Dh
(6) The control never goes back to the main proc
(7) ???

What is the fault?

Upvotes: 1

Views: 8776

Answers (1)

Michael
Michael

Reputation: 58447

CALL pushes the return address on the stack, which is what allows RET to return to that address. When you POP AX in FOO you're popping the return address off the stack. The value you PUSHed before the CALL is not at the top of the stack when you enter FOO, but rather at [SP+2].

Upvotes: 6

Related Questions