1 / 26

ECE291

ECE291. Lecture 5 Program Stack. Lecture Outline. Exam 1 Code Example Program stack Pushing and popping Program organization Debugging hints. Code Example.

molimo
Download Presentation

ECE291

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. ECE291 Lecture 5 Program Stack

  2. Lecture Outline • Exam 1 • Code Example • Program stack • Pushing and popping • Program organization • Debugging hints ECE 291 Lecture 5 Slide 2 of 26

  3. Code Example • Johnny is a freshman in LAS, and with fake ID in hand, he is going out to Kam’s on yet another Tuesday night because LAS majors can do things like that • Oh wait, Kam’s lets in 13 year olds, so Johnny doesn’t even need to use his fake ID • Before leaving, Johnny’s Engineering friends remind him, “Beer before liquor, never been sicker” • Let’s write some code to determine if Johnny will get sick tonight ECE 291 Lecture 5 Slide 3 of 26

  4. JohnnysNightAtKams() • Purpose: Determines if Johnny violates the rule, “Beer before liquor, never been sicker” • Inputs: Drinks - an array containing Johnny’s drinks for the night • A value 1 represents a beer • A value 2 represents a shot of liquor • A value -1 means Johnny is done drinking • Outputs: If Johnny gets sick, he’ll need to be carried home, so we’ll set the carry flag if this happens, or clear it otherwise ECE 291 Lecture 5 Slide 4 of 26

  5. JohnnysNightAtKams() .Liquor cmp ah, 1 je .Sick .LoopContinue inc si jmp .DrinkLoop .Sick stc ; sets the carry flag jmp .Done .NoMoreDrinks clc ; clears the carry flag .Done pop si ; stack stuff - pop ax ; restores registers ret JohnnysNightAtKams push ax ; stack stuff - push si ; saves registers xor ax, ax xor si, si .DrinkLoop mov al, [Drinks + si] cmp al, -1 je .NoMoreDrinks cmp al, 2 je .Liquor ; Use AH as flag ; AH = 1 means Johnny had beer mov ah, 1 jmp .LoopContinue ECE 291 Lecture 5 Slide 5 of 26

  6. Program Stack • Stores temporary data during program execution • One point of access – the top of the stack • Last-in-first-out (LIFO) storage • Data is retrieved in the reverse order from which it was stored • Instructions that directly manipulate the stack • PUSH – places data on top of stack • POP – removes data from top of stack ECE 291 Lecture 5 Slide 6 of 26

  7. Program Stack Implementation in memory Original SP In use Stack grows in direction of decreasing memory addresses In use Direction of increasing memory addresses In use In use In use SS:SP In use Free Free Free SS Free ECE 291 Lecture 5 Slide 7 of 26

  8. Program Stack Implementation • SS – Stack segment • SP – Stack pointer always points to the top of the stack • SP initially points to top of stack (high memory address) • SP decreases as data is PUSHed • PUSH AX  SUB SP, 2; MOV[SS:SP], AX • SP increases as data is POPed • POP AX  MOV AX, [SS:SP]; ADD SP, 2 • BP – Base pointer can point to any element on the stack ECE 291 Lecture 5 Slide 8 of 26

  9. PUSH Example 69 To address 12FFF F8 25 Register array 14 03800 AX 6A 037FF PUSH BX BX 6AB3 B3 037FE CX DX SP before push SP after push SP 0800 SS 0300 03000 Stack segment ECE 291 Lecture 5 Slide 9 of 26

  10. POP Example 69 To address 0FFFF F8 25 14 01008 Register array 6A 01007 POP AX 6AB3 392F AX B3 01006 6AB3 BX CX SP after pop DX SP before pop SP 1006 SS 0000 00000 Stack segment ECE 291 Lecture 5 Slide 10 of 26

  11. PUSH and POP • PUSH and POP always store or retrieve words of data (never bytes) • 80386 and above allow words or double words to be transferred to and from the stack • Source of data for PUSH • Any internal 16-bit register, immediate data, any segment register, or any two bytes of memory • Pop places data into • Internal register, segment register (except CS), or a memory location ECE 291 Lecture 5 Slide 11 of 26

  12. PUSHA and POPA • 80286 and later include PUSHA and POPA to store and retrieve the contents of all general purpose registers (AX, BX, CX, DX, SP, BP, SI, DI) • You can use them without penalty but keep in mind that they are inefficient – in many cases you’ll be saving registers that you’re not modifying ECE 291 Lecture 5 Slide 12 of 26

  13. Stack Initialization Example • Assume that the stack segment resides in memory locations 10000h – 1FFFFh • The stack segment is loaded with 1000h • The SP is loaded with 0000h • This makes the stack 64KB • First PUSH does 0000h – 0002h = FFFEh, storing data in 1FFFEh and 1FFFFh ECE 291 Lecture 5 Slide 13 of 26

  14. Stack Use • To store • Registers • Return address information while procedures are executing • Local variables that procedures may require • Dynamically allocated memory • To pass parameters to procedures (function arguments) ECE 291 Lecture 5 Slide 14 of 26

  15. Temporary Register Storage PUSH and POP registers to preserve their values PUSH AX ; Place AX on the stack PUSH BX ; Place BX on the stack … < modify contents of AX and BX > … POP BX ; Restore original value of BX POP AX ; Restore original value of AX ECE 291 Lecture 5 Slide 15 of 26

  16. Temporary Register Storage • Why would you want to backup and restore registers? • Registers are themselves temporary storage for instruction operands or memory addresses • You might need to do a task that modifies one or more registers, but you might then need the original contents of those registers later • Any data that is an end result more than likely should go into a memory location (a variable) ECE 291 Lecture 5 Slide 16 of 26

  17. Procedures and the Stack • call proc_name • Pushes the instruction pointer and sometimes the code segment register onto the stack • Performs an unconditional jump to the label proc_name • ret • Pops saved IP and if necessary saved CS from the stack and back into the IP and CS registers • This causes the instruction following the call statement to be executed next • More on all of this procedure stuff tomorrow ECE 291 Lecture 5 Slide 17 of 26

  18. Program Organization • Create block structure and/or pseudocode on paper to get a clear concept of program control flow and data structures • Break the total program into logical procedures/macros • Use jumps, loops, etc. where appropriate • Use descriptive names for variables and code lables • Noun_type for types • Nouns for variables • Verbs for procedures/macros ECE 291 Lecture 5 Slide 18 of 26

  19. Program Organization • Good program organization helps with debugging • Almost always, programs do not work the first time • Strategy to find problems • Use TD and set breakpoints to check program progress • Use comments to temporarily remove sections of code • Use “print” statements to announce milestones in the program • Test values and test cases • Try forcing registers or variables to test output of a procedure • Use “print” statements to display critical data • Double-check your logic • Try a different algorithm if all else fails ECE 291 Lecture 5 Slide 19 of 26

  20. NASM Directives • Includes %include “drive:\path\filename” • Copies entire source file contents into the .asm file • Definitions • DB/RESB define/reserve byte (8 bits) • DW/RESW define/reserve word (16 bits) • DD/RESD define/reserve doubleword (32 bits) • TIMES <#> <dir> repeats the following directive a certain number of times • EQU names a constant (has no effect on memory) • Labels • “.” prefixed “local” to previous non-dotted label • “:” suffix not required and doesn’t change label • Global.local can access dotted local labels anywhere by prepending previous non-dotted label ECE 291 Lecture 5 Slide 20 of 26

  21. NASM Directives • %if … %endif • Used to conditionally include/exclude sections of code • To comment out a large section of code:%if 0 ; if false  won’t include code!<instructions to comment out>%endif • This is MUCH easier than putting semi-colons on every line! ECE 291 Lecture 5 Slide 21 of 26

  22. NASM directives • References to procedures • EXTERN name – gives you access to procedures and variables in other files (such as library files) • GLOBAL name – makes your procedures and variables available to other files (as if you were creating a library) • Segment definition • SEGMENT name • Examples: SEGMENT STACK SEGMENT CODE ECE 291 Lecture 5 Slide 22 of 26

  23. Example program structure ; 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 ECE 291 Lecture 5 Slide 23 of 26

  24. Example program structure ;==== LIBMPXXX Routines (Your code will replace calls to these ;functions) extern LibKbdHandler extern LibMouseHandler extern LibDisplayResult extern MPXXXXIT ;====== Stack ==================================================== stkseg segment STACK ; *** STACK SEGMENT *** resb 64*8 ; 64*8 = 512 Bytes of Stack stacktop: ;====== Begin Code/Data========================================== codeseg segmentCODE ; *** CODE SEGMENT *** ECE 291 Lecture 5 Slide 24 of 26

  25. Example program structure ;====== Variables============================================== inputValid resb 1 ; 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 24 InputBuffer MAXBUFLENGTH times db 0 ; Contains one line of user input db ‘$’ graphData %include “graphData.dat” ; data GLOBAL outputBuffer, inputValid, operandsStr GLOBAL graphData ECE 291 Lecture 5 Slide 25 of 26

  26. Example program structure ;====== Procedures=========================================== KbdHandler <Your code here> ret MouseHandler <Your code here> ret DisplayResult <Your code here> ret ;====== Program Initialization =============================== ..start: mov ax, cs ; Use common code & data segment mov ds, ax mov sp, stacktop ; Initialize top of stack ECE 291 Lecture 5 Slide 26 of 26

More Related