The Stack Stack, Procedures and Macros. Outline Stack organization PUSH and POP instructions Calling...

32
The Stack Stack, Procedures and Macros

Transcript of The Stack Stack, Procedures and Macros. Outline Stack organization PUSH and POP instructions Calling...

Page 1: The Stack Stack, Procedures and Macros. Outline Stack organization PUSH and POP instructions Calling procedures Macros Programming guidelines.

The Stack

Stack, Procedures and Macros

Page 2: The Stack Stack, Procedures and Macros. Outline Stack organization PUSH and POP instructions Calling procedures Macros Programming guidelines.

Outline

• Stack organization • PUSH and POP instructions• Calling procedures• Macros• Programming guidelines

Page 3: The Stack Stack, Procedures and Macros. Outline Stack organization PUSH and POP instructions Calling procedures Macros Programming guidelines.

The stack

• Space used as temporary storage during the execution of the program

• Purpose: – saving the return address when calling procedures– saving the contents of registers used in procedures – pass parameters to procedures– allocate memory for local variables in procedures

• A single access point. LIFO data structure– Data is always accessed from the “top” of the stack– Insert is done by “pushing” data to the top of the stack– Delete is done by “popping” data from the top of the stack

Page 4: The Stack Stack, Procedures and Macros. Outline Stack organization PUSH and POP instructions Calling procedures Macros Programming guidelines.

Stack layout in memory

In use

In use

In use

In use

In use

In use

Free

Free

Free

Free SS

SS:SP

Original SP

Direction of increasing memory addresses

Stack grows in direction of decreasing memory addresses

Page 5: The Stack Stack, Procedures and Macros. Outline Stack organization PUSH and POP instructions Calling procedures Macros Programming guidelines.

Stack layout in memory

• SS – Stack segment points to the beginning of the stack segment

• SP – points always to the top of the stack– SP is decreased when data is pushed. E.g. if we push a

word SP is decreased by 2– SP is increased when data is popped. E.g. is we pope a

word SP is popped by 2

• BP can point to any element in the stack– Remember that BP is the register that you use in your

programs to access data from the stack

Page 6: The Stack Stack, Procedures and Macros. Outline Stack organization PUSH and POP instructions Calling procedures Macros Programming guidelines.

Push example

6AB3

0800

0300

6A

B3

037FF

03800

037FE

03000

To address 12FFF

Stack segment

SS

SP

DX

CX

BX

AX

Register array

PUSH BX

SP b

efor

e pu

sh

SP afte

r pus

h

Page 7: The Stack Stack, Procedures and Macros. Outline Stack organization PUSH and POP instructions Calling procedures Macros Programming guidelines.

Pop example

392F

1006

0000

39

2F

01007

01008

01006

00000

To address 0FFFF

Stack segment

SS

SP

DX

CX

BX

AX

Register array

POP BX

SP a

fter p

op

SP bef

ore

pop

Page 8: The Stack Stack, Procedures and Macros. Outline Stack organization PUSH and POP instructions Calling procedures Macros Programming guidelines.

PUSH and POP

• Instructions to access the stack• PUSH and POP always store/load words not bytes• In 386 and above you can also push/pop

doublewords• PUSH X

– X can be immediate data, 16-bit register, segment register or 2 bytes of memory

• POP X– X can be 16-bit register, segment register except CS and

memory location

Page 9: The Stack Stack, Procedures and Macros. Outline Stack organization PUSH and POP instructions Calling procedures Macros Programming guidelines.

PUSHA and POPA

• In 286 and later it is possible to push/pop the entire set of general purpose registers– AX,BX,CX,DX,SP,BP,SI,DI

Page 10: The Stack Stack, Procedures and Macros. Outline Stack organization PUSH and POP instructions Calling procedures Macros Programming guidelines.

Stack Initialization

• Let’s assume that we decide to use 64 Kbytes for the stack starting at address 10000h

• We set SS=1000h and SP=0000h– 64K cover addresses from 10000h to 1FFFFh

• First PUSH decrements SP by 2 (0000h-2=FFFEh), data is stored in 1FFFFh and 1FFFEh

Page 11: The Stack Stack, Procedures and Macros. Outline Stack organization PUSH and POP instructions Calling procedures Macros Programming guidelines.

Using the stack

• Storing– Return address when a procedure is called– Preserve the contents of registers– Local variables required by procedures– Dynamically allocated memory

• Pass– Parameters passed to procedures

Page 12: The Stack Stack, Procedures and Macros. Outline Stack organization PUSH and POP instructions Calling procedures Macros Programming guidelines.

Why preserving registers

• Registers are global variables in principle• Registers can also be used as temporary storage in a

procedure• If a procedure needs to use registers as temporary

storage and these registers contain “useful” global variables, their contents must be preserved

• The first instructions in the procedure should take care of this

Page 13: The Stack Stack, Procedures and Macros. Outline Stack organization PUSH and POP instructions Calling procedures Macros Programming guidelines.

Example: preserving registers

PUSH AX ; Place AX on the stackPUSH BX ; Place BX on the stackPUSH CX ; Place CX on the stackPUSH DX ; Place DX on the stackPUSH SI ; Place SI on the stackPUSH DI ; Place DI on the stack; code that modifies AX,BX,CX,SI,DIPOP DI ; Restore original value of DIPOP SI ; Restore original value of SIPOP DX ; Restore original value of DXPOP CX ; Restore original value of CXPOP BX ; Restore original value of BXPOP AX ; Restore original value of AX

Page 14: The Stack Stack, Procedures and Macros. Outline Stack organization PUSH and POP instructions Calling procedures Macros Programming guidelines.

Calling procedures and using the stack

• call proc_name– Pushes the instruction pointer (IP) – Pushes CS to the stack if the call is to a procedure outside

the code segment– Unconditional jump to the label proc_name

• ret – Pop saved IP and if necessary the saved CS and restores

their values in the registers

Page 15: The Stack Stack, Procedures and Macros. Outline Stack organization PUSH and POP instructions Calling procedures Macros Programming guidelines.

Procedure example

..startmov ax, 10hmov bx, 20hmov cx, 30hmov dx, 40hcall AddRegs ;this proc does AX + BX + CX + DX AXcall DosExit

AddRegsadd ax, bxadd ax, cxadd ax, dx

ret

Page 16: The Stack Stack, Procedures and Macros. Outline Stack organization PUSH and POP instructions Calling procedures Macros Programming guidelines.

Direct access to the stack

• PUSH/POP/CALL/RET modify the SP• When you need to access variables in the stack you

need to manipulate the BP– Example: access the third word from the top of stack and

return result in AXPUSH BP ; Can you tell why ?MOV BP, SPADD BP, 4MOV AX, [BP]

• When you need to allocate/deallocate memory in the stack you manipulate directly the SP

Page 17: The Stack Stack, Procedures and Macros. Outline Stack organization PUSH and POP instructions Calling procedures Macros Programming guidelines.

Procedures at a glance

• Procedures can access global variables declared at the beginning of the program

• Procedures can access global variables stored in registers • Procedures may have parameters passed to them

– Registers with global variables is a form of parameter passing

– Pushing parameters to the stack is another form of parameter passing

• Procedures may need to preserve registers• Procedures may return results to the caller in registers or write

results in memory

Page 18: The Stack Stack, Procedures and Macros. Outline Stack organization PUSH and POP instructions Calling procedures Macros Programming guidelines.

Macros

• Procedures have some extra overhead to execute (call/ret statements, push/pop IP, CS and data from the stack)

• A macro is a piece of code which is “macroexpanded” whenever the name of the macro is encountered

• Note the difference, a procedure is “called”, while a macro is just “expanded/inlined” in your program

• Macros are faster than procedures (no call instructions, stack management etc.)

• But they might– Significantly increase code size

– Hard to debug

Page 19: The Stack Stack, Procedures and Macros. Outline Stack organization PUSH and POP instructions Calling procedures Macros Programming guidelines.

Macro format

%macro MACRO_NAME num_args

;

; your code, use %{1} to access the first

; argument, %{2} to access the second

; argument and so on

%end macro

Page 20: The Stack Stack, Procedures and Macros. Outline Stack organization PUSH and POP instructions Calling procedures Macros Programming guidelines.

Macro example

%macro DIV16 3 ; result=x/y

MOV AX, %{2} ; take the dividend

CWD ; sign-extend it to DX:AX

IDIV %{3} ; divide

MOV %{1},AX ; store quotient in result

%endmacro

Page 21: The Stack Stack, Procedures and Macros. Outline Stack organization PUSH and POP instructions Calling procedures Macros Programming guidelines.

Macro example

; Example: Using the macro in a program; Variable Section

varX1 DW 20varX2 DW 4varR RESW

; Code SectionDIV16 word [varR], word [varX1], word [varX2]

; Will actually generate the following code inline in your; program for every instantiation of the DIV16 macro (You ; won’t actually see this unless you debug the program).; MOV AX, word [varX1]; CWD; IDIV word [varX2]; MOV word [varR], AX

Page 22: The Stack Stack, Procedures and Macros. Outline Stack organization PUSH and POP instructions Calling procedures Macros Programming guidelines.

Organizing your program

• Create a block diagram or pseudocode of your program in paper– Control flow– Data flow

• Break the program into logical “components” that can be easily translated to procedures in your code

• Use descriptive names for variables– Noun_type for types– Nouns for variables– Verbs for procedures

Page 23: The Stack Stack, Procedures and Macros. Outline Stack organization PUSH and POP instructions Calling procedures Macros Programming guidelines.

Organizing your program

• Modular program organization helps debugging– Makes it easier to ‘isolate’ the bug in a single procedure

• All (Microsoft) programs contain bugs!– This is overstated…– It really means that you shouldn’t expect your program to

work the first time you run it…– …but you shouldn’t feel bad about it either, relax and trace

the bug

Page 24: The Stack Stack, Procedures and Macros. Outline Stack organization PUSH and POP instructions Calling procedures Macros Programming guidelines.

Tracing bugs

• The debugging process:– Set breakpoints in your programs and use them as

checkpoints for checking the contents of registers/memory– Comment out code, this might help you find out whether the

commented out code contains the bug

• Use print statements (and you might not need the debugger!)– Display the values of critical data– Display the status of the program

Page 25: The Stack Stack, Procedures and Macros. Outline Stack organization PUSH and POP instructions Calling procedures Macros Programming guidelines.

Tracing bugs

• Force registers and variables to test the output of the procedure– Helps you debug the procedure using as many inputs as

possible

• If everything else fails– Test your logic – Change your algorithms

Page 26: The Stack Stack, Procedures and Macros. Outline Stack organization PUSH and POP instructions Calling procedures Macros Programming guidelines.

Procedures

• Labeled sections of code that you can jump to or return from any point in your program

• A procedure in your assembler is merely a non-dotted label

• Use dotted labels if you want to set jump points within a procedure (local labels)

Page 27: The Stack Stack, Procedures and Macros. Outline Stack organization PUSH and POP instructions Calling procedures Macros Programming guidelines.

NASM directives

• EXTERN, references to procedures defined in other files (e.g. libraries)

• GLOBAL, makes your procedures available to other files, e.g. if you are writing a library

• SEGMENT defines segments– SEGMENT stack– SEGMENT code

Page 28: The Stack Stack, Procedures and Macros. Outline Stack organization PUSH and POP instructions Calling procedures Macros Programming guidelines.

Example of program structuring

; ECE291:MPXXX

; In this MP you will develop a program which take input

; from the keyboard

;====== Constants =================================================

;ASCII values for common characters

CR EQU 13 ; EQU’s have no effect on memory

LF EQU 10 ; They are preprocessor directives only

ESCKEY EQU 27 ; LF gets replace with 10 when assembled

;====== Externals =================================================

; -- LIB291 Routines

extern dspmsg, dspout, kbdin

extern rsave, rrest, binasc

Page 29: The Stack Stack, Procedures and Macros. Outline Stack organization PUSH and POP instructions Calling procedures Macros Programming guidelines.

Example of program structuring

;==== LIBMPXXX Routines (Your code will replace calls to these ;functions)

extern LibKbdHandlerextern LibMouseHandlerextern LibDisplayResultextern MPXXXXIT

;====== Stack ====================================================stkseg segment STACK ; *** STACK SEGMENT *** resb 64*8 ; 64*8 = 512 Bytes of Stackstacktop:

;====== Begin Code/Data ==========================================codeseg segment CODE ; *** CODE SEGMENT ***

Page 30: The Stack Stack, Procedures and Macros. Outline Stack organization PUSH and POP instructions Calling procedures Macros Programming guidelines.

Example of program structuring

;====== Variables ==============================================inputValid db 0 ; 0: InputBuffer is not ready

; 1: InputBuffer is ready;-1: Esc key pressed

operandsStr db 'Operands: ','$'

OutputBuffer 16 times db 0 ; Contains formatted output

db ‘$’ ; (Should be terminated with '$')

MAXBUFLENGTH EQU 24InputBuffer MAXBUFLENGTH times db 0

; Contains one line of user inputdb ‘$’

graphData %include “graphData.dat” ; data

GLOBAL outputBuffer, inputValid, operandsStr GLOBAL graphData

Page 31: The Stack Stack, Procedures and Macros. Outline Stack organization PUSH and POP instructions Calling procedures Macros Programming guidelines.

Example of program structuring

;====== Procedures ===========================================

KbdHandler

<Your code here>

MouseHandler

<Your code here>

DisplayResult

<Your code here>

;====== Program Initialization ===============================

..start:

mov ax, cs ; Use common code & data segment

mov ds, ax

mov sp, stacktop ; Initialize top of stack

Page 32: The Stack Stack, Procedures and Macros. Outline Stack organization PUSH and POP instructions Calling procedures Macros Programming guidelines.

Example of program structuring

;====== Main Procedure ========================================MAIN:

MOV AX, 0B800h ;Use extra segment to access video MOV ES, AX

<here comes your main procedure>

CALL MPXXXXIT ; Exit to DOS