; show_ESP.asm
; A program that displays how esp changes at run time.
; Program displays magnitude of esp changes when 16-bit and 32-bit values
; are pushed on the stack.

.386
.MODEL FLAT

ExitProcess PROTO NEAR32 stdcall, dwExitCode:DWORD

INCLUDE IO.H        ; header file for input/output

cr      EQU     0dh     ; carriage return character
Lf      EQU     0ah     ; line feed

.STACK  4096            ; reserve 4096-byte stack

.DATA                   ; reserve storage for data
orig_SP DWORD   ?
info16  BYTE    "16-bit value diff: ", 0
info32  BYTE    "32-bit value diff: ", 0
result  BYTE    11 DUP (?), 0
endl    BYTE    cr, Lf, 0

.CODE                           ; start of main program code
_main:
        ; First experiment with 16-bit value
        mov     eax, esp        ; get esp
        mov     [orig_SP], eax  ; remember esp value

        push    ax              ; esp decreases by 2
        sub     eax, esp        ; calculate number of bytes on the stack
        add     esp, 2          ; restore esp without pop
        
        dtoa    result, eax     ; convert to ASCII characters
        output  info16          ; output info
        output  result          ; output result
        output  endl            ; output end of line

        ; Second experiment with 32-bit value
        push    eax             ; esp decreases by 4
        mov     eax, [orig_SP]  ; get esp value
        sub     eax, esp        ; calculate number of bytes on the stack
        add     esp, 4          ; restore esp without pop

        dtoa    result, eax     ; convert to ASCII characters
        output  info32          ; output info
        output  result          ; output result
        output  endl            ; output end of line
                
        INVOKE  ExitProcess, 0  ; exit with return code 0

END _main                      ; end of source code and public entry point

; The program generates output:
;	16-bit value diff:           2
;	32-bit value diff:           4