Upload
kirk
View
37
Download
0
Tags:
Embed Size (px)
DESCRIPTION
ECE291. Lecture 5 Let’s get stacked. Lecture outline. Program stack Pushing and popping Program organization Debugging hints Assignments. Program stack. Key characteristics Stores temporary data during program execution One point of access – the top of the stack - PowerPoint PPT Presentation
Citation preview
ECE291ECE291
Lecture 5Lecture 5
Let’s get stackedLet’s get stacked
ECE 291 Lecture 5ECE 291 Lecture 5
Page Page 22 of 25 of 25
Lecture outlineLecture outline
Program stackProgram stack
Pushing and poppingPushing and popping
Program organizationProgram organization
Debugging hintsDebugging hints
AssignmentsAssignments
ECE 291 Lecture 5ECE 291 Lecture 5
Page Page 33 of 25 of 25
Program stackProgram stack
Key characteristicsKey characteristics
Stores temporary data during program executionStores temporary data during program execution
One point of access – the top of the stackOne point of access – the top of the stack
Last-in-first-out (LIFO) storageLast-in-first-out (LIFO) storage Data is retrieved in the reverse order from which it Data is retrieved in the reverse order from which it
was storedwas stored
Instructions that directly manipulate the stackInstructions that directly manipulate the stack PUSH – places data on top of stackPUSH – places data on top of stack POP – removes data from top of stack POP – removes data from top of stack
ECE 291 Lecture 5ECE 291 Lecture 5
Page Page 44 of 25 of 25
Program stackProgram stack
Implementation in memoryImplementation 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
ECE 291 Lecture 5ECE 291 Lecture 5
Page Page 55 of 25 of 25
Program stackProgram stack
Implementation in memoryImplementation in memory
SS – Stack segmentSS – Stack segment
SP – Stack pointer always points to the top of the stackSP – Stack pointer always points to the top of the stack SP initially points to top of stack (high memory address)SP initially points to top of stack (high memory address) SP decreases as data is PUSHedSP decreases as data is PUSHed
PUSH AX PUSH AX SUB SP, 2; MOV[SS:SP], AX SUB SP, 2; MOV[SS:SP], AX SP increases as data is POPedSP increases as data is POPed
POP AX POP AX MOV AX, [SS:SP]; ADD SP, 2 MOV AX, [SS:SP]; ADD SP, 2
BP – Base pointer can point to any element on the stackBP – Base pointer can point to any element on the stack
ECE 291 Lecture 5ECE 291 Lecture 5
Page Page 66 of 25 of 25
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
ECE 291 Lecture 5ECE 291 Lecture 5
Page Page 77 of 25 of 25
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
ECE 291 Lecture 5ECE 291 Lecture 5
Page Page 88 of 25 of 25
Push and popPush and pop
PUSH and POP always store or retrieve words PUSH and POP always store or retrieve words of data (never bytes)of data (never bytes)
80386 and above allow words or double words 80386 and above allow words or double words to be transferred to and from the stackto be transferred to and from the stack
Source of data for PUSHSource of data for PUSH Any internal 16-bit register, immediate data, any Any internal 16-bit register, immediate data, any
segment register, or any segment register, or any two bytes of memorytwo bytes of memory
Pop places data intoPop places data into Internal register, segment register (except CS), or a Internal register, segment register (except CS), or a
memory locationmemory location
ECE 291 Lecture 5ECE 291 Lecture 5
Page Page 99 of 25 of 25
Pusha and popaPusha and popa
80286 and later include PUSHA and 80286 and later include PUSHA and POPA to store and retrieve the contents POPA to store and retrieve the contents internal register set (AX, BX, CX, DX, SP, internal register set (AX, BX, CX, DX, SP, BP, SI, DI)BP, SI, DI)
ECE 291 Lecture 5ECE 291 Lecture 5
Page Page 1010 of 25 of 25
Stack initialization exampleStack initialization example
Assume that the stack segment resides in Assume that the stack segment resides in memory locations 10000h – 1FFFFhmemory locations 10000h – 1FFFFh
The stack segment is loaded with 1000hThe stack segment is loaded with 1000h
The SP is loaded with 0000hThe SP is loaded with 0000h This makes the stack 64KBThis makes the stack 64KB First PUSH does 0000h – 0002h = FFFEh, First PUSH does 0000h – 0002h = FFFEh,
storing data in 1FFFEh and 1FFFFhstoring data in 1FFFEh and 1FFFFh
ECE 291 Lecture 5ECE 291 Lecture 5
Page Page 1111 of 25 of 25
Stack useStack use
To storeTo store RegistersRegisters Return address information while procedures Return address information while procedures
are executingare executing Local variables that procedures may requireLocal variables that procedures may require Dynamically allocated memoryDynamically allocated memory
To passTo pass Parameters to procedures (function Parameters to procedures (function
arguments)arguments)
ECE 291 Lecture 5ECE 291 Lecture 5
Page Page 1212 of 25 of 25
Temporary register storageTemporary register storage
PUSH and POP registers to preserve their valuesPUSH and POP registers to preserve their valuesPUSH AXPUSH AX ; Place AX on the stack; Place AX on the stackPUSH BXPUSH BX ; Place BX on the stack; Place BX on the stack
……
< modify contents of AX and BX >< modify contents of AX and BX >
……
POP BXPOP BX ; Restore original value of BX; Restore original value of BXPOP AXPOP AX ; Restore original value of AX; Restore original value of AX
ECE 291 Lecture 5ECE 291 Lecture 5
Page Page 1313 of 25 of 25
Temporary register storageTemporary register storage
Why would you want to backup and restore Why would you want to backup and restore registers?registers?Because registers are themselves temporary Because registers are themselves temporary storage for instruction operands or memory storage for instruction operands or memory addressesaddressesYou might need to do a task that modifies You might need to do a task that modifies registers, but you might then need the original registers, but you might then need the original contents of those registers latercontents of those registers laterAny data that is an end result more than likely Any data that is an end result more than likely should go into a memory location (a variable)should go into a memory location (a variable)
ECE 291 Lecture 5ECE 291 Lecture 5
Page Page 1414 of 25 of 25
The stack and proceduresThe stack and procedures
call proc_namecall proc_name Pushes the instruction pointer and sometimes the Pushes the instruction pointer and sometimes the
code segment register onto the stackcode segment register onto the stack Performs an unconditional jump to the label Performs an unconditional jump to the label proc_nameproc_name
retret Pops saved IP and if necessary saved CS from the Pops saved IP and if necessary saved CS from the
stack and back into the IP and CS registersstack and back into the IP and CS registers This causes the instruction following the call This causes the instruction following the call
statement to be executed nextstatement to be executed next
More on all of this procedure stuff tomorrowMore on all of this procedure stuff tomorrow
ECE 291 Lecture 5ECE 291 Lecture 5
Page Page 1515 of 25 of 25
Program organizationProgram organization
Create block structure and/or pseudocode on Create block structure and/or pseudocode on paper to get a clear concept of program control paper to get a clear concept of program control flow and data structuresflow and data structuresBreak the total program into logical Break the total program into logical procedures/macrosprocedures/macrosUse jumps, loops, etc. where appropriateUse jumps, loops, etc. where appropriateUse descriptive names for variablesUse descriptive names for variables Noun_type for typesNoun_type for types Nouns for variablesNouns for variables Verbs for procedures/macrosVerbs for procedures/macros
ECE 291 Lecture 5ECE 291 Lecture 5
Page Page 1616 of 25 of 25
Program organizationProgram organization
Good program organization helps with debuggingGood program organization helps with debuggingPrograms do not work the first timePrograms do not work the first timeStrategy to find problemsStrategy to find problems
Use TD and set breakpoints to check program progressUse TD and set breakpoints to check program progress Use comments to temporarily remove sections of codeUse comments to temporarily remove sections of code Use “print” statements to announce milestones in the progrmUse “print” statements to announce milestones in the progrm
Test values and test casesTest values and test cases Try forcing registers or variables to test output of a procedureTry forcing registers or variables to test output of a procedure Use “print” statements to display critical dataUse “print” statements to display critical data
Double-check your logicDouble-check your logicTry a different algorithm if all else failsTry a different algorithm if all else fails
ECE 291 Lecture 5ECE 291 Lecture 5
Page Page 1717 of 25 of 25
NASM directivesNASM directives
IncludesIncludes %include “drive:\path\filename”%include “drive:\path\filename”DefinitionsDefinitions
DB/RESBDB/RESB define/reserve byte (8 bits)define/reserve byte (8 bits) DW/RESWDW/RESW define/reserve word (16 bits)define/reserve word (16 bits) DD/RESDDD/RESD define/reserve doubleword (32 bits)define/reserve doubleword (32 bits) EQUEQU names a constant (has no effect on names a constant (has no effect on
memory)memory)
LabelsLabels ““.” prefixed.” prefixed “local” to previous non-dotted label“local” to previous non-dotted label ““:” suffix:” suffix not required and doesn’t change labelnot required and doesn’t change label Global.localGlobal.local can access dotted local labels anywhere can access dotted local labels anywhere
bybyprepending previous non-dotted label prepending previous non-dotted label
ECE 291 Lecture 5ECE 291 Lecture 5
Page Page 1818 of 25 of 25
NASM directivesNASM directives
ProceduresProcedures Labeled sections of code you can jump to and Labeled sections of code you can jump to and
return from any point in your programreturn from any point in your program Procedures begin with merely a non-dotted Procedures begin with merely a non-dotted
labellabel Use dotted labels inside procedures to keep Use dotted labels inside procedures to keep
them local to the procedurethem local to the procedure Helps keep labels unique program-wideHelps keep labels unique program-wide
ECE 291 Lecture 5ECE 291 Lecture 5
Page Page 1919 of 25 of 25
NASM directivesNASM directives
MacrosMacros Procedures require some overhead in memory and Procedures require some overhead in memory and
execution timeexecution time NASM replaces macro call with the macro code itselfNASM replaces macro call with the macro code itself AdvantagesAdvantages
Faster (no call instruction)Faster (no call instruction)
Readability – easier to understand program functionReadability – easier to understand program function DrawbacksDrawbacks
Using the macro multiple times duplicates codeUsing the macro multiple times duplicates code
Tricky to debug sometimes (especially when you have Tricky to debug sometimes (especially when you have nested macros)nested macros)
ECE 291 Lecture 5ECE 291 Lecture 5
Page Page 2020 of 25 of 25
NASM directivesNASM directives
References to proceduresReferences to procedures EXTERN EXTERN namename – gives you access to procedures and – gives you access to procedures and
variables in other files (such as library files)variables in other files (such as library files) GLOBAL GLOBAL namename – makes your procedures and – makes your procedures and
variables available to other files (as if you were variables available to other files (as if you were creating a library)creating a library)
Segment definitionSegment definition SEGMENT SEGMENT namename Examples:Examples: SEGMENT STACKSEGMENT STACK
SEGMENT CODESEGMENT CODE
ECE 291 Lecture 5ECE 291 Lecture 5
Page Page 2121 of 25 of 25
Example program structureExample program structure
; ECE291:MPXXX; ECE291:MPXXX
; In this MP you will develop a program which take input; In this MP you will develop a program which take input
; from the keyboard; from the keyboard
;======;====== ConstantsConstants ==================================================================================================
;ASCII values for common characters;ASCII values for common characters
CR CR EQUEQU 13 13 ; EQU’s have no effect on memory; EQU’s have no effect on memory
LF LF EQUEQU 10 10 ; They are preprocessor directives only; They are preprocessor directives only
ESCKEY ESCKEY EQUEQU 27 27 ; LF gets replace with 10 when assembled; LF gets replace with 10 when assembled
;====== ;====== ExternalsExternals ==================================================================================================
; -- LIB291 Routines; -- LIB291 Routines
externextern dspmsg, dspout, kbdin dspmsg, dspout, kbdin
externextern rsave, rrest, binasc rsave, rrest, binasc
ECE 291 Lecture 5ECE 291 Lecture 5
Page Page 2222 of 25 of 25
Example program structureExample program structure;==== 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 ***
ECE 291 Lecture 5ECE 291 Lecture 5
Page Page 2323 of 25 of 25
Example program structureExample program structure;====== 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
ECE 291 Lecture 5ECE 291 Lecture 5
Page Page 2424 of 25 of 25
Example program structureExample program structure
;====== ;====== ProceduresProcedures ======================================================================================
KbdHandlerKbdHandler
<Your code here> <Your code here>
MouseHandlerMouseHandler
<Your code here><Your code here>
DisplayResultDisplayResult
<Your code here><Your code here>
;====== ;====== Program InitializationProgram Initialization =============================== ===============================
..start:..start:
mov ax, csmov ax, cs ; Use common code & data segment; Use common code & data segment
mov ds, axmov ds, ax
mov sp, stacktopmov sp, stacktop ; Initialize top of stack; Initialize top of stack
ECE 291 Lecture 5ECE 291 Lecture 5
Page Page 2525 of 25 of 25
Example program structureExample program structure;====== ;====== Main ProcedureMain Procedure ======================================== ========================================MAIN:MAIN:
MOV AX, 0B800h ;Use extra segment to access videoMOV AX, 0B800h ;Use extra segment to access video MOV ES, AXMOV ES, AX
<here comes your main procedure><here comes your main procedure>
CALL MPXXXXIT ; Exit to DOSCALL MPXXXXIT ; Exit to DOS