Download - Stack and Subroutines
Stack and SubroutinesStack and Subroutines
OutlineOutline
o Stack organization o PUSH and POP instructionso Calling procedureso Macroso Programming guidelines
The stackThe stack
o Space used as temporary storage during the execution of the program
o Purpose: o saving the return address when calling
procedureso saving the contents of registers used in
procedures o pass parameters to procedureso allocate memory for local variables in
procedures
Contd…
The stackThe stack
o A single access point. LIFO data structureo Data is always accessed from the “top” of
the stacko Insert is done by “pushing” data to the top
of the stacko Delete is done by “popping” data from the
top of the stack
Stack layout in memoryStack 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
Stack layout in memoryStack layout in memory
o SS – Stack segment points to the beginning of the stack segment
o SP – points always to the top of the stacko SP is decreased when data is pushed. E.g.
if we push a word SP is decreased by 2o SP is increased when data is popped. E.g.
is we pope a word SP is popped by 2o BP can point to any element in the stack
o Remember that BP is the register that you use in your programs to access data from the stack
Push examplePush 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
Pop examplePop 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
PUSH and POPPUSH and POP
o Instructions to access the stacko PUSH and POP always store/load words not
byteso In 386 and above you can also push/pop
doublewordso PUSH X
o X can be immediate data, 16-bit register, segment register or 2 bytes of memory
o POP Xo X can be 16-bit register, segment register
except CS and memory location
PUSHA and POPAPUSHA and POPA
o In 286 and later it is possible to push/pop the entire set of general purpose registerso AX,BX,CX,DX,SP,BP,SI,DI
Stack InitializationStack Initialization
o Let’s assume that we decide to use 64 Kbytes for the stack starting at address 10000h
o We set SS=1000h and SP=0000ho 64K cover addresses from 10000h to
1FFFFho First PUSH decrements SP by 2 (0000h-
2=FFFEh), data is stored in 1FFFFh and 1FFFEh
Using the stackUsing the stack
o Storingo Return address when a procedure is calledo Preserve the contents of registerso Local variables required by procedureso Dynamically allocated memory
o Passo Parameters passed to procedures
Why preserving registersWhy preserving registers
o Registers are global variables in principleo Registers can also be used as temporary
storage in a procedureo If a procedure needs to use registers as
temporary storage and these registers contain “useful” global variables, their contents must be preserved
o The first instructions in the procedure should take care of this
Example: Example: preserving registerspreserving 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
Calling procedures Calling procedures and using the stackand using the stack
o call proc_nameo Pushes the instruction pointer (IP) o Pushes CS to the stack if the call is to a
procedure outside the code segmento Unconditional jump to the label proc_name
o ret o Pop saved IP and if necessary the saved CS
and restores their values in the registers
Procedure exampleProcedure 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
Direct access Direct access to the stackto the stack
o PUSH/POP/CALL/RET modify the SPo When you need to access variables in the
stack you need to manipulate the BPo 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]
o When you need to allocate/deallocate memory in the stack you manipulate directly the SP
Procedures at a glanceProcedures at a glance
o Procedures can access global variables declared at the beginning of the program
o Procedures can access global variables stored in registers
o Procedures may have parameters passed to them o Registers with global variables is a form of
parameter passingo Pushing parameters to the stack is another
form of parameter passingo Procedures may need to preserve registerso Procedures may return results to the caller in
registers or write results in memory
Guidelines for MP1Guidelines for MP1
o There should be a one-to-one match between push and pop
o The first pop is matched with the last pusho Some of the functions you need to implement
return values to memory and some return values in registerso PlayerStats [player1], [player2],[player3]o NewPlay, bx=1,2, or 3 of 3 player created
o Do not push and pop registers that will store return values
MacrosMacros
o Procedures have some extra overhead to execute (call/ret statements, push/pop IP, CS and data from the stack)
o A macro is a piece of code which is “macroexpanded” whenever the name of the macro is encountered
o Note the difference, a procedure is “called”, while a macro is just “expanded/inlined” in your program
o Macros are faster than procedures (no call instructions, stack management etc.)
o But they mighto Significantly increase code size o Hard to debug
Macro formatMacro 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
Macro exampleMacro example
%macro DIV16 3 ; result=x/yMOV AX, %{2} ; take the dividendCWD ; sign-extend it to DX:AXIDIV %{3} ; divideMOV %{1},AX ; store quotient in result%endmacro
Macro exampleMacro 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
Organizing your programOrganizing your program
o Create a block diagram or pseudocode of your program in papero Control flowo Data flow
o Break the program into logical “components” that can be easily translated to procedures in your code
o Use descriptive names for variableso Noun_type for typeso Nouns for variableso Verbs for procedures
Organizing your programOrganizing your program
o Modular program organization helps debuggingo Makes it easier to ‘isolate’ the bug in a
single procedureo All (Microsoft) programs contain bugs!
o This is overstated…o It really means that you shouldn’t expect
your program to work the first time you run it…
o …but you shouldn’t feel bad about it either, relax and trace the bug
Tracing bugsTracing bugs
o The debugging process:o Set breakpoints in your programs and use
them as checkpoints for checking the contents of registers/memory
o Comment out code, this might help you find out whether the commented out code contains the bug
o Use print statements (and you might not need the debugger!)o Display the values of critical datao Display the status of the program
Tracing bugsTracing bugs
o Force registers and variables to test the output of the procedureo Helps you debug the procedure using as
many inputs as possible o If everything else fails
o Test your logic o Change your algorithms
ProceduresProcedures
o Labeled sections of code that you can jump to or return from any point in your program
o A procedure in your assembler is merely a non-dotted label
o Use dotted labels if you want to set jump points within a procedure (local labels)
NASM directivesNASM directives
o EXTERN, references to procedures defined in other files (e.g. libraries)
o GLOBAL, makes your procedures available to other files, e.g. if you are writing a library
o SEGMENT defines segmentso SEGMENT stacko SEGMENT code
Example of Example of program structuringprogram structuring
; ECE291:MPXXX; In this MP you will develop a program which take
input; from the keyboard
;====== Constants =================================================
;ASCII values for common charactersCR EQU 13 ; EQU’s have no effect on
memory
Contd…
Example of Example of program structuringprogram structuring
LF EQU 10 ; They are preprocessor directives only
ESCKEY EQU 27 ; LF gets replace with 10 when assembled
;====== Externals =================================================
; -- LIB291 Routinesextern dspmsg, dspout, kbdinextern rsave, rrest, binasc
Example of Example of program structuringprogram structuring
;==== LIBMPXXX Routines (Your code will replace calls to these ;functions)
extern LibKbdHandlerextern LibMouseHandlerextern LibDisplayResultextern MPXXXXIT
;====== Stack ====================================================
Contd…
Example of Example of program structuringprogram structuring
stkseg segment STACK ; *** STACK SEGMENT *** resb 64*8 ; 64*8 = 512 Bytes of Stackstacktop:
;====== Begin Code/Data ==========================================
codeseg segment CODE ; *** CODE SEGMENT ***
Example of Example of program structuringprogram 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 outputdb ‘$’ ; (Should be terminated
with '$') Contd…
Example of Example of program structuringprogram structuring
MAXBUFLENGTH EQU 24InputBuffer MAXBUFLENGTH times db 0
; Contains one line of user input
db ‘$’graphData %include “graphData.dat” ; data
GLOBAL outputBuffer, inputValid, operandsStr GLOBAL graphData
Example of Example of program structuringprogram structuring
;====== Procedures ===========================================KbdHandler
<Your code here> MouseHandler
<Your code here>DisplayResult
<Your code here>
Contd…
Example of Example of program structuringprogram structuring
;====== Program Initialization ===============================
..start: mov ax, cs ; Use common code &
data segment mov ds, ax mov sp, stacktop ; Initialize top of stack
Example of Example of program structuringprogram 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