today’s topics parameter passing on the system stack parameter passing on the system stack...
Post on 31-Dec-2015
225 Views
Preview:
TRANSCRIPT
Today’s topicsToday’s topics
Parameter passing on the system Parameter passing on the system stackstack Register indirect and base-indexed Register indirect and base-indexed
addressing modesaddressing modes ““Random” numbersRandom” numbers Intro to arraysIntro to arrays
CALL and RET InstructionsCALL and RET Instructions
The The CALLCALL instruction calls a instruction calls a procedure procedure Pushes the Pushes the offsetoffset of the of the next instructionnext instruction
onto the stackonto the stack copies the copies the addressaddress of the of the called called
procedureprocedure into into EIPEIP The The RETRET instruction returns from a instruction returns from a
procedureprocedure pops top of stack into pops top of stack into EIPEIP
Nested procedure callsNested procedure calls Any procedure might Any procedure might callcall another another
procedureprocedure Return addresses are “stacked” Return addresses are “stacked”
(LIFO)(LIFO) retret instructions must follow the order instructions must follow the order
on the stackon the stack One very good reason not to One very good reason not to jmpjmp out of out of
a procedure!a procedure! It is essential that the stack be It is essential that the stack be
properly aligned when the properly aligned when the RETRET instruction is executed !!instruction is executed !!
ParametersParameters
Definitions:Definitions: ArgumentArgument ( (actual parameteractual parameter) is a value ) is a value
or reference or reference passedpassed toto a procedure. a procedure. ParameterParameter ( (formal parameterformal parameter) is a ) is a
value or reference value or reference received byreceived by a a procedureprocedure
Register vs. Stack Register vs. Stack ParametersParameters
Register parameters require Register parameters require dedicating a register to each dedicating a register to each parameter.parameter.
Stack parameters make better use of Stack parameters make better use of system resourcessystem resources
Example:Example: two ways of calling two ways of calling SummationSummation
procedure.procedure.Method 1 Method 1 (parameters in (parameters in registers)registers)::pushad ;save registersmov ebx,lowmov ecx,highcall Summationpopad ;restore registers
Method 2Method 2(parameters on (parameters on stack)stack)::push lowpush highcall Summation
Register vs. Stack Register vs. Stack ParametersParameters Of course, methods of calling a Of course, methods of calling a
procedure and passing parameters procedure and passing parameters depend on the procedure depend on the procedure implementation … and vice-versa.implementation … and vice-versa.
some “setup” is involved (in the calling some “setup” is involved (in the calling procedure)procedure)
some “bookkeeping” is involved (in the some “bookkeeping” is involved (in the called procedure)called procedure)
Parameters in registers require Parameters in registers require register managementregister management
Parameters on the system stack Parameters on the system stack require stack managementrequire stack management
RETRET Instruction Instruction Pops stack into the instruction pointer Pops stack into the instruction pointer
(EIP)(EIP) Transfers control to the target Transfers control to the target
address.address. Syntax:Syntax:
RETRET RETRET nn
Optional operand Optional operand nn causes causes nn to be to be added to the stack pointer after EIP is added to the stack pointer after EIP is assigned a value.assigned a value. Equivalent to popping the return address Equivalent to popping the return address
and and nn additional bytes additional bytes off the stack off the stack
Parameter ClassificationsParameter Classifications An An input parameterinput parameter is data passed by a calling is data passed by a calling
program to a procedure. program to a procedure. The called procedure is not expected to modify the The called procedure is not expected to modify the
corresponding parameter variable, and even if it does, the corresponding parameter variable, and even if it does, the modification is confined to the procedure itself.modification is confined to the procedure itself.
An output parameter is created by passing the address of a variable when a procedure is called. The “address of” a variable is the same thing as a
“pointer to” or a “reference to” the variable. In MASM, we use OFFSET.
The procedure does not use any existing data from the variable, but it fills in new contents before it returns.
An input-output parameter is the address of a variable which contains input that will be both used and modified by the procedure. The content is modified at the memory address passed by
the calling procedure.
Stack FrameStack Frame Also known as an Also known as an activation recordactivation record Area of the stack used for a Area of the stack used for a
procedure's return address, passed procedure's return address, passed parameters, saved registers, and local parameters, saved registers, and local variablesvariables
Created by the following steps:Created by the following steps: Calling program pushes arguments onto Calling program pushes arguments onto
the stack and calls the procedure.the stack and calls the procedure. The called procedure pushes EBP onto the The called procedure pushes EBP onto the
stack, and sets EBP to ESP.stack, and sets EBP to ESP.
Addressing modesAddressing modes ImmediateImmediate Set register to a constantSet register to a constant
DirectDirect Set register to address of globalSet register to address of global
RegisterRegister Use register as operandUse register as operand
Register indirectRegister indirect Access memory through address Access memory through address in a in a registerregister
IndexedIndexed “array” element, using offset in register“array” element, using offset in register
Base-indexedBase-indexed Start address in one register; offset in Start address in one register; offset in another, add and access another, add and access
memorymemory
StackStack Memory area specified and Memory area specified and maintained maintained as a stack; stack as a stack; stack pointer in registerpointer in register
Offset (branch) Offset (branch) ““goto” address; may be goto” address; may be computedcomputed
Register indirect modeRegister indirect mode [reg] means “contents of memory at the [reg] means “contents of memory at the
addressaddress in in reg reg ”” It’s OK to add a constant (named or literal)It’s OK to add a constant (named or literal)
Example:Example: movmov [edx+12], eax[edx+12], eax We have used register indirect with We have used register indirect with espesp to to
reference the value at the top of the reference the value at the top of the system stacksystem stack
NOTE:NOTE: register indirect is a register indirect is a memory referencememory reference There are no memory-memory instructionsThere are no memory-memory instructions E.G., E.G., movmov [edx],[eax] is [edx],[eax] is WRONGWRONG!!
Explicit Access to Stack Explicit Access to Stack ParametersParameters
A procedure can explicitly access stack A procedure can explicitly access stack parameters using constant offsets from parameters using constant offsets from EBP.EBP. Example: [ebp + 8]Example: [ebp + 8]
EBP is often called the EBP is often called the base pointerbase pointer or or frame pointerframe pointer because it is (should be) because it is (should be) set to the base address of the stack set to the base address of the stack frame.frame.
EBP does not change value during the EBP does not change value during the procedure.procedure.
EBP must be restored to its original EBP must be restored to its original value when a procedure returns.value when a procedure returns.
Explicit Access to Stack Explicit Access to Stack ParametersParameters
Remember that the return address is Remember that the return address is pushed onto the stack pushed onto the stack afterafter the the parameters are pushed.parameters are pushed.
Programmer is responsible for Programmer is responsible for managing the stack.managing the stack.
Stack Frame ExampleStack Frame Example
.datax DWORD 175y DWORD 37Z DWORD ?.codemain PROCpush x push y push OFFSET zcall SumTwo...
SYSTEMSYSTEM STACKSTACK
[ESP][ESP] Return Return addressaddress
[ESP+4][ESP+4] @ z@ z
[ESP+8][ESP+8] 3737
[ESP+12][ESP+12] 175175
Note: @ means “address of”
Stack Frame ExampleStack Frame ExampleSumTwo PROC
push ebpmov ebp,espmov eax,[ebp+16]
;175 in eaxadd eax,[ebp+12]
;175+37 = 212 in eaxmov ebx,[ebp+8]
;@z in ebxmov [ebx],eax
;store 212 in zpop ebpret 12
SumTwo ENDP
SYSTEMSYSTEM STACKSTACK
[EBP][EBP] old EBPold EBP
[EBP+4][EBP+4] Return Return addressaddress
[EBP+8][EBP+8] @ z@ z
[EBP+12][EBP+12] 3737
[EBP+16][EBP+16] 175175
Note: @ means “address of”
Trouble-Shooting TipsTrouble-Shooting Tips Save and restore registers when they Save and restore registers when they
are modified by a procedure.are modified by a procedure. Except a register that returns a function Except a register that returns a function
resultresult Do not pass an immediate value to a
procedure that expects a reference parameter. Dereferencing its address will likely
cause a general-protection fault.
Random NumbersRandom Numbers Irvine library has random integer Irvine library has random integer
generatorgenerator "pseudo-random" numbers"pseudo-random" numbers
RandomizeRandomize procedure procedure Initializes sequence based on system Initializes sequence based on system
clock (random clock (random seedseed)) Call Call onceonce at the beginning of the program at the beginning of the program Without Without RandomizeRandomize, program gets the , program gets the
same sequence every time it is executed.same sequence every time it is executed.
Limiting random valuesLimiting random values RandomRangeRandomRange procedure procedure
Accepts N > 0 in Accepts N > 0 in eaxeax Returns random integer in [0 .. N-1] in Returns random integer in [0 .. N-1] in eaxeax
To generate a random number in To generate a random number in [lo .. hi]:[lo .. hi]: Find number of integers possible in [lo .. Find number of integers possible in [lo ..
hi] : hi] : range = hi – lo +1range = hi – lo +1 Put Put rangerange in in eaxeax, and call , and call
RandomRangeRandomRange Result in Result in eaxeax is in [0 .. is in [0 .. range range -1]-1] Add Add lolo to to eaxeax..
RandomRange ExampleRandomRange Example Get a random integer in range [18 .. Get a random integer in range [18 ..
31]31]
movmov eax,hieax,hi ;31;31
subsub eax,loeax,lo ;31-18 = 13;31-18 = 13
incinc eaxeax ;14;14
callcall RandomRangeRandomRange ;eax in [0..13];eax in [0..13]
addadd eax,loeax,lo ;eax in [18..31];eax in [18..31]
Questions on random numbers?Questions on random numbers?
Arrays in MASMArrays in MASM
Declaration (in data segment)Declaration (in data segment)MAX_SIZE = 100MAX_SIZE = 100
.data.data
listlist DWORDDWORD MAX_SIZEMAX_SIZE DUP(?)DUP(?)
Defines an array of 100 uninitialized Defines an array of 100 uninitialized 32-bit integers32-bit integers
Array elements are in contiguous Array elements are in contiguous memorymemory
Arrays in MASMArrays in MASM
DeclarationDeclarationMAX_SIZE = 100MAX_SIZE = 100
.data.data
listlist DWORDDWORD MAX_SIZEMAX_SIZEDUP(?)DUP(?)
countcount DWORDDWORD 00
What happens (in HLL) if we reference What happens (in HLL) if we reference list[100] ?list[100] ? Compile-time errorCompile-time error
What happens in MASM if we go beyond What happens in MASM if we go beyond the end of the array?the end of the array? Not predictableNot predictable
Array address calculationsArray address calculations Array declaration defines a name for Array declaration defines a name for
the first element onlythe first element only HLLs reference it as HLLs reference it as list[0]list[0]
All other elements are accessed by All other elements are accessed by calculating the actual addresscalculating the actual address
General formula for array address General formula for array address calculation:calculation: address of list[k] = list + (k * sizeof address of list[k] = list + (k * sizeof
element)element) Example:Example:
address of 4address of 4thth element ( element (list list [3]) is [3]) is address of address of listlist + (3 * sizeof DWORD) + (3 * sizeof DWORD)
Array references in MASMArray references in MASM
Several methodsSeveral methods indexedindexed base-indexedbase-indexed othersothers
Addressing modesAddressing modes ImmediateImmediate Set register to a constantSet register to a constant
DirectDirect Set register to address of globalSet register to address of global
RegisterRegister Use register as operandUse register as operand
Register indirectRegister indirect Access memory through address Access memory through address in a in a registerregister
IndexedIndexed “array” element, using offset in register“array” element, using offset in register
Base-indexedBase-indexed Start address in one register; offset in Start address in one register; offset in another, add and access another, add and access
memorymemory
StackStack Memory area specified and Memory area specified and maintained maintained as a stack; stack as a stack; stack pointer in registerpointer in register
Offset (branch) Offset (branch) ““goto” address; may be goto” address; may be computedcomputed
Indexed addressingIndexed addressing Array element, using Array element, using offsetoffset in register in register Examples:Examples:
movmov edi,0edi,0 ;high-level ;high-level notationnotation
movmov list[edi],eaxlist[edi],eax ;list[0];list[0]
addadd edi,edi,44 ;see note ;see note belowbelow
movmov list[edi],ebxlist[edi],ebx ;list[1];list[1] This means "add the This means "add the valuevalue in [ ] to in [ ] to addressaddress of of
list list "" NoteNote: Add 4 because these array elements are : Add 4 because these array elements are
DWORDDWORD if BYTE, add 1if BYTE, add 1 if WORD, add 2if WORD, add 2 if QWORD, add 8if QWORD, add 8 etc.etc.
Base-indexed addressingBase-indexed addressing Start address in one register; offset in Start address in one register; offset in
another, then add the registers to another, then add the registers to access memoryaccess memory
Examples:Examples:movmov edx,OFFSET listedx,OFFSET listmovmov ecx,12ecx,12movmov eax,[edx+ecx]eax,[edx+ecx]movmov ebx,4ebx,4movmov eax,[edx+ebx]eax,[edx+ebx]movmov [edx+ecx],eax[edx+ecx],eax
Processing Arrays in MASMProcessing Arrays in MASM
Example: Display an array of Example: Display an array of integersintegers
Assumptions:Assumptions: Already initializedAlready initialized Number of elements is stored in Number of elements is stored in countcount Assume global declarationsAssume global declarations Assume elements are DWORD (32-bit)Assume elements are DWORD (32-bit) Many possible solutionsMany possible solutions
Display: version 0.1 (Display: version 0.1 (register register indirectindirect))
displaydisplay PROCPROCmovmov esi,OFFSET listesi,OFFSET list;@list;@listmovmov ecx,countecx,count ;ecx is loop ;ecx is loop controlcontrol
more:more:movmov eax,[esi]eax,[esi] ;get current ;get current elementelementcallcall PrintDecPrintDeccallcall CrlfCrlfaddadd esi,4esi,4 ;next ;next elementelementlooploop moremore
endMore:endMore:retret
displaydisplay ENDPENDP
Display: version 0.2 (Display: version 0.2 (indexedindexed))displaydisplay PROCPROC
movmov esi,0esi,0 ;esi is ;esi is “index”“index”movmov ecx,countecx,count ;ecx is loop ;ecx is loop controlcontrol
more:more:movmov eax,list[esi]eax,list[esi] ;get current ;get current elt.elt.callcall PrintDecPrintDeccallcall CrlfCrlfaddadd esi,4esi,4 ;next ;next elementelementlooploop moremore
endMore:endMore:retret
displaydisplay ENDPENDP
Display: version 0.3 (Display: version 0.3 (base-base-indexedindexed))
displaydisplay PROCPROCmovmov ebx,OFFSET listebx,OFFSET list ;@list;@listmovmov ecx,countecx,count ;ecx is loop ;ecx is loop controlcontrolmovmov edx,0edx,0 ;edx is ;edx is element ptrelement ptr
more:more:movmov eax,[ebx+edx]eax,[ebx+edx]callcall WriteDecWriteDeccallcall CrlfCrlfaddadd edx,4edx,4looploop moremore
endMore:endMore:retret
displaydisplay ENDPENDP
top related