Presentation is loading. Please wait.

Presentation is loading. Please wait.

Stack and Subroutines. Outline oStack organization oPUSH and POP instructions oCalling procedures oMacros oProgramming guidelines.

Similar presentations


Presentation on theme: "Stack and Subroutines. Outline oStack organization oPUSH and POP instructions oCalling procedures oMacros oProgramming guidelines."— Presentation transcript:

1 Stack and Subroutines

2 Outline oStack organization oPUSH and POP instructions oCalling procedures oMacros oProgramming guidelines

3 The stack oSpace used as temporary storage during the execution of the program oPurpose: osaving the return address when calling procedures osaving the contents of registers used in procedures opass parameters to procedures oallocate memory for local variables in procedures Contd…

4 The stack oA single access point. LIFO data structure oData is always accessed from the “top” of the stack oInsert is done by “pushing” data to the top of the stack oDelete is done by “popping” data from the top of the stack

5 Stack layout in memory In use Free SS SS:SP Original SP Direction of increasing memory addresses Stack grows in direction of decreasing memory addresses

6 Stack layout in memory oSS – Stack segment points to the beginning of the stack segment oSP – points always to the top of the stack oSP is decreased when data is pushed. E.g. if we push a word SP is decreased by 2 oSP is increased when data is popped. E.g. is we pope a word SP is popped by 2 oBP can point to any element in the stack oRemember that BP is the register that you use in your programs to access data from the stack

7 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 before push SP after push

8 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 after pop SP before pop

9 PUSH and POP oInstructions to access the stack oPUSH and POP always store/load words not bytes oIn 386 and above you can also push/pop doublewords oPUSH X oX can be immediate data, 16-bit register, segment register or 2 bytes of memory oPOP X oX can be 16-bit register, segment register except CS and memory location

10 PUSHA and POPA oIn 286 and later it is possible to push/pop the entire set of general purpose registers oAX,BX,CX,DX,SP,BP,SI,DI

11 Stack Initialization oLet’s assume that we decide to use 64 Kbytes for the stack starting at address 10000h oWe set SS=1000h and SP=0000h o64K cover addresses from 10000h to 1FFFFh oFirst PUSH decrements SP by 2 (0000h-2=FFFEh), data is stored in 1FFFFh and 1FFFEh

12 Using the stack oStoring oReturn address when a procedure is called oPreserve the contents of registers oLocal variables required by procedures oDynamically allocated memory oPass oParameters passed to procedures

13 Why preserving registers oRegisters are global variables in principle oRegisters can also be used as temporary storage in a procedure oIf a procedure needs to use registers as temporary storage and these registers contain “useful” global variables, their contents must be preserved oThe first instructions in the procedure should take care of this

14 Example: preserving registers PUSH AX; Place AX on the stack PUSH BX; Place BX on the stack PUSH CX; Place CX on the stack PUSH DX; Place DX on the stack PUSH SI; Place SI on the stack PUSH DI; Place DI on the stack ; code that modifies AX,BX,CX,SI,DI POP DI; Restore original value of DI POP SI; Restore original value of SI POP DX; Restore original value of DX POP CX; Restore original value of CX POP BX; Restore original value of BX POP AX; Restore original value of AX

15 Calling procedures and using the stack ocall proc_name oPushes the instruction pointer (IP) oPushes CS to the stack if the call is to a procedure outside the code segment oUnconditional jump to the label proc_name oret oPop saved IP and if necessary the saved CS and restores their values in the registers

16 Procedure example..start mov ax, 10h mov bx, 20h mov cx, 30h mov dx, 40h call AddRegs;this proc does AX + BX + CX + DX  AX call DosExit AddRegs add ax, bx add ax, cx add ax, dx ret

17 Direct access to the stack oPUSH/POP/CALL/RET modify the SP oWhen you need to access variables in the stack you need to manipulate the BP oExample: access the third word from the top of stack and return result in AX PUSH BP; Can you tell why ? MOV BP, SP ADD BP, 4 MOV AX, [BP] oWhen you need to allocate/deallocate memory in the stack you manipulate directly the SP

18 Procedures at a glance oProcedures can access global variables declared at the beginning of the program oProcedures can access global variables stored in registers oProcedures may have parameters passed to them oRegisters with global variables is a form of parameter passing oPushing parameters to the stack is another form of parameter passing oProcedures may need to preserve registers oProcedures may return results to the caller in registers or write results in memory

19 Guidelines for MP1 oThere should be a one-to-one match between push and pop oThe first pop is matched with the last push oSome of the functions you need to implement return values to memory and some return values in registers oPlayerStats [player1], [player2],[player3] oNewPlay, bx=1,2, or 3 of 3 player created oDo not push and pop registers that will store return values

20 Macros oProcedures have some extra overhead to execute (call/ret statements, push/pop IP, CS and data from the stack) oA macro is a piece of code which is “macroexpanded” whenever the name of the macro is encountered oNote the difference, a procedure is “called”, while a macro is just “expanded/inlined” in your program oMacros are faster than procedures (no call instructions, stack management etc.) oBut they might oSignificantly increase code size oHard to debug

21 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

22 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

23 Macro example ; Example: Using the macro in a program ; Variable Section varX1 DW 20 varX2 DW 4 varR RESW ; Code Section DIV16 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

24 Organizing your program oCreate a block diagram or pseudocode of your program in paper oControl flow oData flow oBreak the program into logical “components” that can be easily translated to procedures in your code oUse descriptive names for variables oNoun_type for types oNouns for variables oVerbs for procedures

25 Organizing your program oModular program organization helps debugging oMakes it easier to ‘isolate’ the bug in a single procedure oAll (Microsoft) programs contain bugs! oThis is overstated… oIt 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

26 Tracing bugs oThe debugging process: oSet breakpoints in your programs and use them as checkpoints for checking the contents of registers/memory oComment out code, this might help you find out whether the commented out code contains the bug oUse print statements (and you might not need the debugger!) oDisplay the values of critical data oDisplay the status of the program

27 Tracing bugs oForce registers and variables to test the output of the procedure oHelps you debug the procedure using as many inputs as possible oIf everything else fails oTest your logic oChange your algorithms

28 Procedures oLabeled sections of code that you can jump to or return from any point in your program oA procedure in your assembler is merely a non- dotted label oUse dotted labels if you want to set jump points within a procedure (local labels)

29 NASM directives oEXTERN, references to procedures defined in other files (e.g. libraries) oGLOBAL, makes your procedures available to other files, e.g. if you are writing a library oSEGMENT defines segments oSEGMENT stack oSEGMENT code

30 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 Contd…

31 Example of program structuring 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

32 Example of program structuring ;==== LIBMPXXX Routines (Your code will replace calls to these ;functions) extern LibKbdHandler extern LibMouseHandler extern LibDisplayResult extern MPXXXXIT ;====== Stack ============================================ ======== Contd…

33 Example of program structuring stkseg segment STACK; *** STACK SEGMENT *** resb 64*8; 64*8 = 512 Bytes of Stack stacktop: ;====== Begin Code/Data ========================================== codeseg segment CODE; *** CODE SEGMENT ***

34 Example of program structuring ;====== Variables =========================================== === inputValiddb 0; 0: InputBuffer is not ready ; 1: InputBuffer is ready ;-1: Esc key pressed operandsStrdb 'Operands: ','$' OutputBuffer16 times db 0; Contains formatted output db ‘$’; (Should be terminated with '$') Contd…

35 Example of program structuring MAXBUFLENGTHEQU 24 InputBufferMAXBUFLENGTH times db 0 ; Contains one line of user input db ‘$’ graphData%include “graphData.dat”; data GLOBAL outputBuffer, inputValid, operandsStr GLOBAL graphData

36 Example of program structuring ;====== Procedures =========================================== KbdHandler MouseHandler DisplayResult Contd…

37 Example of program structuring ;====== Program Initialization ===============================..start: mov ax, cs; Use common code & data segment mov ds, ax mov sp, stacktop; Initialize top of stack

38 Example of program structuring ;====== Main Procedure ======================================== MAIN: MOV AX, 0B800h ;Use extra segment to access video MOV ES, AX CALL MPXXXXIT ; Exit to DOS


Download ppt "Stack and Subroutines. Outline oStack organization oPUSH and POP instructions oCalling procedures oMacros oProgramming guidelines."

Similar presentations


Ads by Google