100% found this document useful (1 vote)
94 views14 pages

Guide To x86 Assembly

This document provides an overview of 32-bit x86 assembly language programming using MASM syntax. It describes the x86 registers, memory addressing modes, basic instructions, and calling conventions. The registers section outlines the 8 general purpose 32-bit registers and how they relate to smaller register subsets. Memory and addressing explains how to declare static data regions and arrays, and how memory addresses can be computed. The instructions section gives examples of common data movement, arithmetic/logic, and control flow instructions.

Uploaded by

Paulo Vaz
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
94 views14 pages

Guide To x86 Assembly

This document provides an overview of 32-bit x86 assembly language programming using MASM syntax. It describes the x86 registers, memory addressing modes, basic instructions, and calling conventions. The registers section outlines the 8 general purpose 32-bit registers and how they relate to smaller register subsets. Memory and addressing explains how to declare static data regions and arrays, and how memory addresses can be computed. The instructions section gives examples of common data movement, arithmetic/logic, and control flow instructions.

Uploaded by

Paulo Vaz
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

UniversityofVirginiaComputerScience

CS216:ProgramandDataRepresentation,Spring2006

27July2016

x86AssemblyGuide
Contents:Registers|MemoryandAddressing|Instructions|CallingConvention
Thisguidedescribesthebasicsof32bitx86assemblylanguageprogramming,coveringasmallbut
usefulsubsetoftheavailableinstructionsandassemblerdirectives.Thereareseveraldifferent
assemblylanguagesforgeneratingx86machinecode.TheonewewilluseinCS216istheMicrosoft
MacroAssembler(MASM)assembler.MASMusesthestandardIntelsyntaxforwritingx86assembly
code.
Thefullx86instructionsetislargeandcomplex(Intel'sx86instructionsetmanualscompriseover2900
pages),andwedonotcoveritallinthisguide.Forexample,thereisa16bitsubsetofthex86
instructionset.Usingthe16bitprogrammingmodelcanbequitecomplex.Ithasasegmentedmemory
model,morerestrictionsonregisterusage,andsoon.Inthisguide,wewilllimitourattentiontomore
modernaspectsofx86programming,anddelveintotheinstructionsetonlyinenoughdetailtogeta
basicfeelforx86programming.

Resources
GuidetoUsingAssemblyinVisualStudioatutorialonbuildinganddebuggingassemblycode
inVisualStudio
Intelx86InstructionSetReference
Intel'sPentiumManuals(thefullgorydetails)

Registers
Modern(i.e386andbeyond)x86processorshaveeight32bitgeneralpurposeregisters,asdepictedin
Figure1.Theregisternamesaremostlyhistorical.Forexample,EAXusedtobecalledtheaccumulator
sinceitwasusedbyanumberofarithmeticoperations,andECXwasknownasthecountersinceitwas
usedtoholdaloopindex.Whereasmostoftheregistershavelosttheirspecialpurposesinthemodern
instructionset,byconvention,twoarereservedforspecialpurposesthestackpointer(ESP)andthe
basepointer(EBP).
FortheEAX,EBX,ECX,andEDXregisters,subsectionsmaybeused.Forexample,theleastsignificant2
bytesofEAXcanbetreatedasa16bitregistercalledAX.TheleastsignificantbyteofAXcanbeused
asasingle8bitregistercalledAL,whilethemostsignificantbyteofAXcanbeusedasasingle8bit
registercalledAH.Thesenamesrefertothesamephysicalregister.Whenatwobytequantityisplaced
intoDX,theupdateaffectsthevalueofDH,DL,andEDX.Thesesubregistersaremainlyholdoversfrom
older,16bitversionsoftheinstructionset.However,theyaresometimesconvenientwhendealingwith
datathataresmallerthan32bits(e.g.1byteASCIIcharacters).
Whenreferringtoregistersinassemblylanguage,thenamesarenotcasesensitive.Forexample,the
namesEAXandeaxrefertothesameregister.

Figure1.x86Registers

MemoryandAddressingModes
DeclaringStaticDataRegions
Youcandeclarestaticdataregions(analogoustoglobalvariables)inx86assemblyusingspecial
assemblerdirectivesforthispurpose.Datadeclarationsshouldbeprecededbythe.DATAdirective.
Followingthisdirective,thedirectivesDB,DW,andDDcanbeusedtodeclareone,two,andfourbyte
datalocations,respectively.Declaredlocationscanbelabeledwithnamesforlaterreferencethisis
similartodeclaringvariablesbyname,butabidesbysomelowerlevelrules.Forexample,locations
declaredinsequencewillbelocatedinmemorynexttooneanother.
Exampledeclarations:

.DATA

Declareabyte,referredtoaslocationvar,containing
thevalue64.
Declareanuninitializedbyte,referredtoaslocation
var2 DB?
var2.
Declareabytewithnolabel,containingthevalue10.Its
DB10
locationisvar2+1.
Declarea2byteuninitializedvalue,referredtoas
X
DW?
locationX.
Y
DD30000 Declarea4bytevalue,referredtoaslocationY,
initializedto30000.
var

DB64

Unlikeinhighlevellanguageswherearrayscanhavemanydimensionsandareaccessedbyindices,
arraysinx86assemblylanguagearesimplyanumberofcellslocatedcontiguouslyinmemory.Anarray
canbedeclaredbyjustlistingthevalues,asinthefirstexamplebelow.Twoothercommonmethods
usedfordeclaringarraysofdataaretheDUPdirectiveandtheuseofstringliterals.TheDUPdirective
tellstheassemblertoduplicateanexpressionagivennumberoftimes.Forexample,4DUP(2)is
equivalentto2,2,2,2.
Someexamples:

DD1,2,3 Declarethree4bytevalues,initializedto1,2,and3.
ThevalueoflocationZ+8willbe3.
DB10

bytesDUP(?)
arr
str

Declare10uninitializedbytesstartingatlocationbytes.

DD100
Declare1004bytewordsstartingatlocationarr,all
DUP(0) initializedto0
Declare6bytesstartingattheaddressstr,initializedto
DB
'hello',0 theASCIIcharactervaluesforhelloandthenull(0)
byte.

AddressingMemory
Modernx86compatibleprocessorsarecapableofaddressingupto232bytesofmemory:memory
addressesare32bitswide.Intheexamplesabove,whereweusedlabelstorefertomemoryregions,
theselabelsareactuallyreplacedbytheassemblerwith32bitquantitiesthatspecifyaddressesin
memory.Inadditiontosupportingreferringtomemoryregionsbylabels(i.e.constantvalues),thex86
providesaflexibleschemeforcomputingandreferringtomemoryaddresses:uptotwoofthe32bit
registersanda32bitsignedconstantcanbeaddedtogethertocomputeamemoryaddress.Oneofthe
registerscanbeoptionallypremultipliedby2,4,or8.
Theaddressingmodescanbeusedwithmanyx86instructions(we'lldescribetheminthenextsection).
Hereweillustratesomeexamplesusingthemovinstructionthatmovesdatabetweenregistersand
memory.Thisinstructionhastwooperands:thefirstisthedestinationandthesecondspecifiesthe
source.
Someexamplesofmovinstructionsusingaddresscomputationsare:

Movethe4bytesinmemoryattheaddresscontainedin
EBXintoEAX
MovethecontentsofEBXintothe4bytesatmemory
mov[var],ebx
addressvar.(Note,varisa32bitconstant).
moveax,[esi
Move4bytesatmemoryaddressESI+(4)intoEAX
4]
mov[esi+eax],
MovethecontentsofCLintothebyteataddressESI+EAX
cl
movedx,
[esi+4*ebx] Movethe4bytesofdataataddressESI+4*EBXintoEDX
moveax,[ebx]

Someexamplesofinvalidaddresscalculationsinclude:

moveax,[ebxecx]
Canonlyaddregistervalues
mov[eax+esi+edi],ebxAtmost2registersinaddresscomputation
SizeDirectives
Ingeneral,theintendedsizeoftheofthedataitematagivenmemoryaddresscanbeinferredfromthe
assemblycodeinstructioninwhichitisreferenced.Forexample,inalloftheaboveinstructions,the
sizeofthememoryregionscouldbeinferredfromthesizeoftheregisteroperand.Whenwewere
loadinga32bitregister,theassemblercouldinferthattheregionofmemorywewerereferringtowas4
byteswide.Whenwewerestoringthevalueofaonebyteregistertomemory,theassemblercouldinfer
thatwewantedtheaddresstorefertoasinglebyteinmemory.
However,insomecasesthesizeofareferredtomemoryregionisambiguous.Considertheinstruction
mov[ebx],2.Shouldthisinstructionmovethevalue2intothesinglebyteataddressEBX?Perhaps
itshouldmovethe32bitintegerrepresentationof2intothe4bytesstartingataddressEBX.Since
eitherisavalidpossibleinterpretation,theassemblermustbeexplicitlydirectedastowhichiscorrect.
ThesizedirectivesBYTEPTR,WORDPTR,andDWORDPTRservethispurpose,indicatingsizesof
1,2,and4bytesrespectively.
Forexample:

movBYTEPTR
[ebx],2

Move2intothesinglebyteattheaddressstoredinEBX.

movWORDPTR
[ebx],2
movDWORDPTR
[ebx],2

Movethe16bitintegerrepresentationof2intothe2
bytesstartingattheaddressinEBX.
Movethe32bitintegerrepresentationof2intothe4
bytesstartingattheaddressinEBX.

Instructions
Machineinstructionsgenerallyfallintothreecategories:datamovement,arithmetic/logic,andcontrol
flow.Inthissection,wewilllookatimportantexamplesofx86instructionsfromeachcategory.This
sectionshouldnotbeconsideredanexhaustivelistofx86instructions,butratherausefulsubset.Fora
completelist,seeIntel'sinstructionsetreference.
Weusethefollowingnotation:

<reg32>
<reg16>
<reg8>
<reg>
<mem>
<con32>
<con16>
<con8>
<con>

Any32bitregister(EAX,EBX,ECX,EDX,ESI,EDI,ESP,or
EBP)
Any16bitregister(AX,BX,CX,orDX)
Any8bitregister(AH,BH,CH,DH,AL,BL,CL,orDL)
Anyregister
Amemoryaddress(e.g.,[eax],[var+4],ordwordptr
[eax+ebx])
Any32bitconstant
Any16bitconstant
Any8bitconstant
Any8,16,or32bitconstant

DataMovementInstructions
movMove(Opcodes:88,89,8A,8B,8C,8E,...)
Themovinstructioncopiesthedataitemreferredtobyitssecondoperand(i.e.register
contents,memorycontents,oraconstantvalue)intothelocationreferredtobyitsfirst
operand(i.e.aregisterormemory).Whileregistertoregistermovesarepossible,direct
memorytomemorymovesarenot.Incaseswherememorytransfersaredesired,the
sourcememorycontentsmustfirstbeloadedintoaregister,thencanbestoredtothe
destinationmemoryaddress.
Syntax
mov<reg>,<reg>
mov<reg>,<mem>
mov<mem>,<reg>
mov<reg>,<const>
mov<mem>,<const>
Examples
moveax,ebxcopythevalueinebxintoeax
movbyteptr[var],5storethevalue5intothebyteatlocationvar

pushPushstack(Opcodes:FF,89,8A,8B,8C,8E,...)
Thepushinstructionplacesitsoperandontothetopofthehardwaresupportedstackin
memory.Specifically,pushfirstdecrementsESPby4,thenplacesitsoperandintothe
contentsofthe32bitlocationataddress[ESP].ESP(thestackpointer)isdecrementedby
pushsincethex86stackgrowsdowni.e.thestackgrowsfromhighaddressestolower
addresses.
Syntax
push<reg32>
push<mem>
push<con32>
Examples
pusheaxpusheaxonthestack
push[var]pushthe4bytesataddressvarontothestack
popPopstack
Thepopinstructionremovesthe4bytedataelementfromthetopofthehardware
supportedstackintothespecifiedoperand(i.e.registerormemorylocation).Itfirstmoves
the4byteslocatedatmemorylocation[SP]intothespecifiedregisterormemory
location,andthenincrementsSPby4.
Syntax
pop<reg32>
pop<mem>
Examples
popedipopthetopelementofthestackintoEDI.
pop[ebx]popthetopelementofthestackintomemoryatthefourbytesstartingat
locationEBX.
leaLoadeffectiveaddress
Theleainstructionplacestheaddressspecifiedbyitssecondoperandintotheregister
specifiedbyitsfirstoperand.Note,thecontentsofthememorylocationarenotloaded,
onlytheeffectiveaddressiscomputedandplacedintotheregister.Thisisusefulfor
obtainingapointerintoamemoryregion.
Syntax
lea<reg32>,<mem>
Examples
leaedi,[ebx+4*esi]thequantityEBX+4*ESIisplacedinEDI.
leaeax,[var]thevalueinvarisplacedinEAX.
leaeax,[val]thevaluevalisplacedinEAX.

ArithmeticandLogicInstructions
addIntegerAddition
Theaddinstructionaddstogetheritstwooperands,storingtheresultinitsfirstoperand.
Note,whereasbothoperandsmayberegisters,atmostoneoperandmaybeamemory
location.
Syntax
add<reg>,<reg>
add<reg>,<mem>
add<mem>,<reg>
add<reg>,<con>
add<mem>,<con>

Examples
addeax,10EAXEAX+10
addBYTEPTR[var],10add10tothesinglebytestoredatmemoryaddress
var
subIntegerSubtraction
Thesubinstructionstoresinthevalueofitsfirstoperandtheresultofsubtractingthe
valueofitssecondoperandfromthevalueofitsfirstoperand.Aswithadd
Syntax
sub<reg>,<reg>
sub<reg>,<mem>
sub<mem>,<reg>
sub<reg>,<con>
sub<mem>,<con>
Examples
subal,ahALALAH
subeax,216subtract216fromthevaluestoredinEAX
inc,decIncrement,Decrement
Theincinstructionincrementsthecontentsofitsoperandbyone.Thedecinstruction
decrementsthecontentsofitsoperandbyone.
Syntax
inc<reg>
inc<mem>
dec<reg>
dec<mem>
Examples
deceaxsubtractonefromthecontentsofEAX.
incDWORDPTR[var]addonetothe32bitintegerstoredatlocationvar
imulIntegerMultiplication
Theimulinstructionhastwobasicformats:twooperand(firsttwosyntaxlistingsabove)
andthreeoperand(lasttwosyntaxlistingsabove).
Thetwooperandformmultipliesitstwooperandstogetherandstorestheresultinthefirst
operand.Theresult(i.e.first)operandmustbearegister.
Thethreeoperandformmultipliesitssecondandthirdoperandstogetherandstoresthe
resultinitsfirstoperand.Again,theresultoperandmustbearegister.Furthermore,the
thirdoperandisrestrictedtobeingaconstantvalue.
Syntax
imul<reg32>,<reg32>
imul<reg32>,<mem>
imul<reg32>,<reg32>,<con>
imul<reg32>,<mem>,<con>
Examples
imuleax,[var]multiplythecontentsofEAXbythe32bitcontentsofthe
memorylocationvar.StoretheresultinEAX.
imulesi,edi,25ESIEDI*25
idivIntegerDivision

Theidivinstructiondividesthecontentsofthe64bitintegerEDX:EAX(constructedby
viewingEDXasthemostsignificantfourbytesandEAXastheleastsignificantfour
bytes)bythespecifiedoperandvalue.Thequotientresultofthedivisionisstoredinto
EAX,whiletheremainderisplacedinEDX.
Syntax
idiv<reg32>
idiv<mem>
Examples
idivebxdividethecontentsofEDX:EAXbythecontentsofEBX.Placethe
quotientinEAXandtheremainderinEDX.
idivDWORDPTR[var]dividethecontentsofEDX:EASbythe32bitvalue
storedatmemorylocationvar.PlacethequotientinEAXandtheremainderinEDX.
and,or,xorBitwiselogicaland,orandexclusiveor
Theseinstructionsperformthespecifiedlogicaloperation(logicalbitwiseand,or,and
exclusiveor,respectively)ontheiroperands,placingtheresultinthefirstoperand
location.
Syntax
and<reg>,<reg>
and<reg>,<mem>
and<mem>,<reg>
and<reg>,<con>
and<mem>,<con>
or<reg>,<reg>
or<reg>,<mem>
or<mem>,<reg>
or<reg>,<con>
or<mem>,<con>
xor<reg>,<reg>
xor<reg>,<mem>
xor<mem>,<reg>
xor<reg>,<con>
xor<mem>,<con>
Examples
andeax,0fHclearallbutthelast4bitsofEAX.
xoredx,edxsetthecontentsofEDXtozero.
notBitwiseLogicalNot
Logicallynegatestheoperandcontents(thatis,flipsallbitvaluesintheoperand).
Syntax
not<reg>
not<mem>
Example
notBYTEPTR[var]negateallbitsinthebyteatthememorylocationvar.

negNegate
Performsthetwo'scomplementnegationoftheoperandcontents.
Syntax
neg<reg>
neg<mem>
Example
negeaxEAXEAX
shl,shrShiftLeft,ShiftRight
Theseinstructionsshiftthebitsintheirfirstoperand'scontentsleftandright,paddingthe
resultingemptybitpositionswithzeros.Theshiftedoperandcanbeshiftedupto31places.
Thenumberofbitstoshiftisspecifiedbythesecondoperand,whichcanbeeitheran8bit
constantortheregisterCL.Ineithercase,shiftscountsofgreaterthen31areperformed
modulo32.
Syntax
shl<reg>,<con8>
shl<mem>,<con8>
shl<reg>,<cl>
shl<mem>,<cl>
shr<reg>,<con8>
shr<mem>,<con8>
shr<reg>,<cl>
shr<mem>,<cl>
Examples
shleax,1MultiplythevalueofEAXby2(ifthemostsignificantbitis0)
shrebx,clStoreinEBXthefloorofresultofdividingthevalueofEBXby2n
wherenisthevalueinCL.

ControlFlowInstructions
Thex86processormaintainsaninstructionpointer(IP)registerthatisa32bitvalueindicatingthe
locationinmemorywherethecurrentinstructionstarts.Normally,itincrementstopointtothenext
instructioninmemorybeginsafterexecutionaninstruction.TheIPregistercannotbemanipulated
directly,butisupdatedimplicitlybyprovidedcontrolflowinstructions.
Weusethenotation<label>torefertolabeledlocationsintheprogramtext.Labelscanbeinserted
anywhereinx86assemblycodetextbyenteringalabelnamefollowedbyacolon.Forexample,
movesi,[ebp+8]
begin:xorecx,ecx
moveax,[esi]
Thesecondinstructioninthiscodefragmentislabeledbegin.Elsewhereinthecode,wecanreferto
thememorylocationthatthisinstructionislocatedatinmemoryusingthemoreconvenientsymbolic
namebegin.Thislabelisjustaconvenientwayofexpressingthelocationinsteadofits32bitvalue.
jmpJump
Transfersprogramcontrolflowtotheinstructionatthememorylocationindicatedbythe
operand.
Syntax
jmp<label>

Example
jmpbeginJumptotheinstructionlabeledbegin.
jconditionConditionalJump
Theseinstructionsareconditionaljumpsthatarebasedonthestatusofasetofcondition
codesthatarestoredinaspecialregistercalledthemachinestatusword.Thecontentsof
themachinestatuswordincludeinformationaboutthelastarithmeticoperationperformed.
Forexample,onebitofthiswordindicatesifthelastresultwaszero.Anotherindicatesif
thelastresultwasnegative.Basedontheseconditioncodes,anumberofconditional
jumpscanbeperformed.Forexample,thejzinstructionperformsajumptothespecified
operandlabeliftheresultofthelastarithmeticoperationwaszero.Otherwise,control
proceedstothenextinstructioninsequence.
Anumberoftheconditionalbranchesaregivennamesthatareintuitivelybasedonthelast
operationperformedbeingaspecialcompareinstruction,cmp(seebelow).Forexample,
conditionalbranchessuchasjleandjnearebasedonfirstperformingacmpoperation
onthedesiredoperands.
Syntax
je<label>(jumpwhenequal)
jne<label>(jumpwhennotequal)
jz<label>(jumpwhenlastresultwaszero)
jg<label>(jumpwhengreaterthan)
jge<label>(jumpwhengreaterthanorequalto)
jl<label>(jumpwhenlessthan)
jle<label>(jumpwhenlessthanorequalto)
Example
cmpeax,ebx
jledone
IfthecontentsofEAXarelessthanorequaltothecontentsofEBX,jumptothelabel
done.Otherwise,continuetothenextinstruction.
cmpCompare
Comparethevaluesofthetwospecifiedoperands,settingtheconditioncodesinthe
machinestatuswordappropriately.Thisinstructionisequivalenttothesubinstruction,
excepttheresultofthesubtractionisdiscardedinsteadofreplacingthefirstoperand.
Syntax
cmp<reg>,<reg>
cmp<reg>,<mem>
cmp<mem>,<reg>
cmp<reg>,<con>
Example
cmpDWORDPTR[var],10
jeqloop
Ifthe4bytesstoredatlocationvarareequaltothe4byteintegerconstant10,jumpto
thelocationlabeledloop.
call,retSubroutinecallandreturn
Theseinstructionsimplementasubroutinecallandreturn.Thecallinstructionfirst
pushesthecurrentcodelocationontothehardwaresupportedstackinmemory(seethe
pushinstructionfordetails),andthenperformsanunconditionaljumptothecodelocation
indicatedbythelabeloperand.Unlikethesimplejumpinstructions,thecallinstruction
savesthelocationtoreturntowhenthesubroutinecompletes.

Theretinstructionimplementsasubroutinereturnmechanism.Thisinstructionfirstpops
acodelocationoffthehardwaresupportedinmemorystack(seethepopinstructionfor
details).Itthenperformsanunconditionaljumptotheretrievedcodelocation.
Syntax
call<label>
ret

CallingConvention
Toallowseparateprogrammerstosharecodeanddeveloplibrariesforusebymanyprograms,andto
simplifytheuseofsubroutinesingeneral,programmerstypicallyadoptacommoncallingconvention.
Thecallingconventionisaprotocolabouthowtocallandreturnfromroutines.Forexample,givenaset
ofcallingconventionrules,aprogrammerneednotexaminethedefinitionofasubroutinetodetermine
howparametersshouldbepassedtothatsubroutine.Furthermore,givenasetofcallingconvention
rules,highlevellanguagecompilerscanbemadetofollowtherules,thusallowinghandcoded
assemblylanguageroutinesandhighlevellanguageroutinestocalloneanother.
Inpractice,manycallingconventionsarepossible.WewillusethewidelyusedClanguagecalling
convention.Followingthisconventionwillallowyoutowriteassemblylanguagesubroutinesthatare
safelycallablefromC(andC++)code,andwillalsoenableyoutocallClibraryfunctionsfromyour
assemblylanguagecode.
TheCcallingconventionisbasedheavilyontheuseofthehardwaresupportedstack.Itisbasedonthe
push,pop,call,andretinstructions.Subroutineparametersarepassedonthestack.Registersare
savedonthestack,andlocalvariablesusedbysubroutinesareplacedinmemoryonthestack.Thevast
majorityofhighlevelprocedurallanguagesimplementedonmostprocessorshaveusedsimilarcalling
conventions.
Thecallingconventionisbrokenintotwosetsofrules.Thefirstsetofrulesisemployedbythecallerof
thesubroutine,andthesecondsetofrulesisobservedbythewriterofthesubroutine(thecallee).It
shouldbeemphasizedthatmistakesintheobservanceoftheserulesquicklyresultinfatalprogram
errorssincethestackwillbeleftinaninconsistentstatethusmeticulouscareshouldbeusedwhen
implementingthecallconventioninyourownsubroutines.

>
StackduringSubroutineCall
[ThankstoJamesPetersonforfindingandfixingthebugintheoriginalversionofthisfigure!]

Agoodwaytovisualizetheoperationofthecallingconventionistodrawthecontentsofthenearby
regionofthestackduringsubroutineexecution.Theimageabovedepictsthecontentsofthestackduring
theexecutionofasubroutinewiththreeparametersandthreelocalvariables.Thecellsdepictedinthe
stackare32bitwidememorylocations,thusthememoryaddressesofthecellsare4bytesapart.The
firstparameterresidesatanoffsetof8bytesfromthebasepointer.Abovetheparametersonthestack
(andbelowthebasepointer),thecallinstructionplacedthereturnaddress,thusleadingtoanextra4
bytesofoffsetfromthebasepointertothefirstparameter.Whentheretinstructionisusedtoreturn
fromthesubroutine,itwilljumptothereturnaddressstoredonthestack.
CallerRules
Tomakeasubroutingcall,thecallershould:
1.Beforecallingasubroutine,thecallershouldsavethecontentsofcertainregistersthatare
designatedcallersaved.ThecallersavedregistersareEAX,ECX,EDX.Sincethecalled
subroutineisallowedtomodifytheseregisters,ifthecallerreliesontheirvaluesafterthe
subroutinereturns,thecallermustpushthevaluesintheseregistersontothestack(sotheycanbe
restoreafterthesubroutinereturns.
2.Topassparameterstothesubroutine,pushthemontothestackbeforethecall.Theparameters
shouldbepushedininvertedorder(i.e.lastparameterfirst).Sincethestackgrowsdown,thefirst
parameterwillbestoredatthelowestaddress(thisinversionofparameterswashistoricallyused
toallowfunctionstobepassedavariablenumberofparameters).
3.Tocallthesubroutine,usethecallinstruction.Thisinstructionplacesthereturnaddressontop
oftheparametersonthestack,andbranchestothesubroutinecode.Thisinvokesthesubroutine,
whichshouldfollowthecalleerulesbelow.
Afterthesubroutinereturns(immediatelyfollowingthecallinstruction),thecallercanexpecttofind
thereturnvalueofthesubroutineintheregisterEAX.Torestorethemachinestate,thecallershould:
1.Removetheparametersfromstack.Thisrestoresthestacktoitsstatebeforethecallwas
performed.
2.Restorethecontentsofcallersavedregisters(EAX,ECX,EDX)bypoppingthemoffofthe
stack.Thecallercanassumethatnootherregistersweremodifiedbythesubroutine.
Example
Thecodebelowshowsafunctioncallthatfollowsthecallerrules.Thecalleriscallingafunction

_myFuncthattakesthreeintegerparameters.FirstparameterisinEAX,thesecondparameteristhe
constant216thethirdparameterisinmemorylocationvar.
push[var];Pushlastparameterfirst
push216;Pushthesecondparameter
pusheax;Pushfirstparameterlast
call_myFunc;Callthefunction(assumeCnaming)
addesp,12
Notethatafterthecallreturns,thecallercleansupthestackusingtheaddinstruction.Wehave12
bytes(3parameters*4byteseach)onthestack,andthestackgrowsdown.Thus,togetridofthe
parameters,wecansimplyadd12tothestackpointer.
Theresultproducedby_myFuncisnowavailableforuseintheregisterEAX.Thevaluesofthecaller
savedregisters(ECXandEDX),mayhavebeenchanged.Ifthecallerusesthemafterthecall,itwould
haveneededtosavethemonthestackbeforethecallandrestorethemafterit.
CalleeRules
Thedefinitionofthesubroutineshouldadheretothefollowingrulesatthebeginningofthesubroutine:
1.PushthevalueofEBPontothestack,andthencopythevalueofESPintoEBPusingthe
followinginstructions:
pushebp
movebp,esp
Thisinitialactionmaintainsthebasepointer,EBP.Thebasepointerisusedbyconventionasa
pointofreferenceforfindingparametersandlocalvariablesonthestack.Whenasubroutineis
executing,thebasepointerholdsacopyofthestackpointervaluefromwhenthesubroutine
startedexecuting.Parametersandlocalvariableswillalwaysbelocatedatknown,constant
offsetsawayfromthebasepointervalue.Wepushtheoldbasepointervalueatthebeginningof
thesubroutinesothatwecanlaterrestoretheappropriatebasepointervalueforthecallerwhen
thesubroutinereturns.Remember,thecallerisnotexpectingthesubroutinetochangethevalue
ofthebasepointer.WethenmovethestackpointerintoEBPtoobtainourpointofreferencefor
accessingparametersandlocalvariables.
2.Next,allocatelocalvariablesbymakingspaceonthestack.Recall,thestackgrowsdown,soto
makespaceonthetopofthestack,thestackpointershouldbedecremented.Theamountby
whichthestackpointerisdecrementeddependsonthenumberandsizeoflocalvariablesneeded.
Forexample,if3localintegers(4byteseach)wererequired,thestackpointerwouldneedtobe
decrementedby12tomakespacefortheselocalvariables(i.e.,subesp,12).Aswith
parameters,localvariableswillbelocatedatknownoffsetsfromthebasepointer.
3.Next,savethevaluesofthecalleesavedregistersthatwillbeusedbythefunction.Tosave
registers,pushthemontothestack.ThecalleesavedregistersareEBX,EDI,andESI(ESPand
EBPwillalsobepreservedbythecallingconvention,butneednotbepushedonthestackduring
thisstep).
Afterthesethreeactionsareperformed,thebodyofthesubroutinemayproceed.Whenthesubroutineis
returns,itmustfollowthesesteps:
1.LeavethereturnvalueinEAX.
2.Restoretheoldvaluesofanycalleesavedregisters(EDIandESI)thatweremodified.The
registercontentsarerestoredbypoppingthemfromthestack.Theregistersshouldbepoppedin
theinverseorderthattheywerepushed.
3.Deallocatelocalvariables.Theobviouswaytodothismightbetoaddtheappropriatevalueto
thestackpointer(sincethespacewasallocatedbysubtractingtheneededamountfromthestack
pointer).Inpractice,alesserrorpronewaytodeallocatethevariablesistomovethevalueinthe
basepointerintothestackpointer:movesp,ebp.Thisworksbecausethebasepointer

alwayscontainsthevaluethatthestackpointercontainedimmediatelypriortotheallocationof
thelocalvariables.
4.Immediatelybeforereturning,restorethecaller'sbasepointervaluebypoppingEBPoffthe
stack.Recallthatthefirstthingwedidonentrytothesubroutinewastopushthebasepointerto
saveitsoldvalue.
5.Finally,returntothecallerbyexecutingaretinstruction.Thisinstructionwillfindandremove
theappropriatereturnaddressfromthestack.
Notethatthecallee'srulesfallcleanlyintotwohalvesthatarebasicallymirrorimagesofoneanother.
Thefirsthalfoftherulesapplytothebeginningofthefunction,andarecommonlysaidtodefinethe
prologuetothefunction.Thelatterhalfoftherulesapplytotheendofthefunction,andarethus
commonlysaidtodefinetheepilogueofthefunction.
Example
Hereisanexamplefunctiondefinitionthatfollowsthecalleerules:
.486
.MODELFLAT
.CODE
PUBLIC_myFunc
_myFuncPROC
;SubroutinePrologue
pushebp;Savetheoldbasepointervalue.
movebp,esp;Setthenewbasepointervalue.
subesp,4;Makeroomforone4bytelocalvariable.
pushedi;Savethevaluesofregistersthatthefunction
pushesi;willmodify.ThisfunctionusesEDIandESI.
;(noneedtosaveEBX,EBP,orESP)
;SubroutineBody
moveax,[ebp+8];Movevalueofparameter1intoEAX
movesi,[ebp+12];Movevalueofparameter2intoESI
movedi,[ebp+16];Movevalueofparameter3intoEDI
mov[ebp4],edi;MoveEDIintothelocalvariable
add[ebp4],esi;AddESIintothelocalvariable
addeax,[ebp4];Addthecontentsofthelocalvariable
;intoEAX(finalresult)
;SubroutineEpilogue
popesi;Recoverregistervalues
popedi
movesp,ebp;Deallocatelocalvariables
popebp;Restorethecaller'sbasepointervalue
ret
_myFuncENDP
END
ThesubroutineprologueperformsthestandardactionsofsavingasnapshotofthestackpointerinEBP
(thebasepointer),allocatinglocalvariablesbydecrementingthestackpointer,andsavingregister
valuesonthestack.
Inthebodyofthesubroutinewecanseetheuseofthebasepointer.Bothparametersandlocalvariables
arelocatedatconstantoffsetsfromthebasepointerforthedurationofthesubroutinesexecution.In
particular,wenoticethatsinceparameterswereplacedontothestackbeforethesubroutinewascalled,
theyarealwayslocatedbelowthebasepointer(i.e.athigheraddresses)onthestack.Thefirst
parametertothesubroutinecanalwaysbefoundatmemorylocation[EBP+8],thesecondat[EBP+12],
thethirdat[EBP+16].Similarly,sincelocalvariablesareallocatedafterthebasepointerisset,they
alwaysresideabovethebasepointer(i.e.atloweraddresses)onthestack.Inparticular,thefirstlocal
variableisalwayslocatedat[EBP4],thesecondat[EBP8],andsoon.Thisconventionaluseofthe
basepointerallowsustoquicklyidentifytheuseoflocalvariablesandparameterswithinafunction
body.

Thefunctionepilogueisbasicallyamirrorimageofthefunctionprologue.Thecaller'sregistervalues
arerecoveredfromthestack,thelocalvariablesaredeallocatedbyresettingthestackpointer,the
caller'sbasepointervalueisrecovered,andtheretinstructionisusedtoreturntotheappropriatecode
locationinthecaller.
Credits:ThisguidewasoriginallycreatedbyAdamFerrarimanyyearsago,
andsinceupdatedbyAlanBatson,MikeLack,andAnitaJones.
Itwasrevisedfor216Spring2006byDavidEvans.

CS216:ProgramandDataRepresentation
UniversityofVirginia

DavidEvans
[email protected]
UsingtheseMaterials

You might also like