You are on page 1of 14

10/5/2016

Guidetox86Assembly

UniversityofVirginiaComputerScience
CS216:ProgramandDataRepresentation,Spring2006

27July2016

x86AssemblyGuide
Contents:Registers|MemoryandAddressing|Instructions|CallingConvention
Thisguidedescribesthebasicsof32bitx86assemblylanguageprogramming,coveringasmallbutuseful
subsetoftheavailableinstructionsandassemblerdirectives.Thereareseveraldifferentassemblylanguages
forgeneratingx86machinecode.TheonewewilluseinCS216istheMicrosoftMacroAssembler(MASM)
assembler.MASMusesthestandardIntelsyntaxforwritingx86assemblycode.
Thefullx86instructionsetislargeandcomplex(Intel'sx86instructionsetmanualscompriseover2900
pages),andwedonotcoveritallinthisguide.Forexample,thereisa16bitsubsetofthex86instruction
set.Usingthe16bitprogrammingmodelcanbequitecomplex.Ithasasegmentedmemorymodel,more
restrictionsonregisterusage,andsoon.Inthisguide,wewilllimitourattentiontomoremodernaspectsof
x86programming,anddelveintotheinstructionsetonlyinenoughdetailtogetabasicfeelforx86
programming.

Resources
GuidetoUsingAssemblyinVisualStudioatutorialonbuildinganddebuggingassemblycodein
VisualStudio
Intelx86InstructionSetReference
Intel'sPentiumManuals(thefullgorydetails)

Registers
Modern(i.e386andbeyond)x86processorshaveeight32bitgeneralpurposeregisters,asdepictedin
Figure1.Theregisternamesaremostlyhistorical.Forexample,EAXusedtobecalledtheaccumulatorsince
itwasusedbyanumberofarithmeticoperations,andECXwasknownasthecountersinceitwasusedto
holdaloopindex.Whereasmostoftheregistershavelosttheirspecialpurposesinthemoderninstruction
set,byconvention,twoarereservedforspecialpurposesthestackpointer(ESP)andthebasepointer
(EBP).
FortheEAX,EBX,ECX,andEDXregisters,subsectionsmaybeused.Forexample,theleastsignificant2bytes
ofEAXcanbetreatedasa16bitregistercalledAX.TheleastsignificantbyteofAXcanbeusedasasingle8
bitregistercalledAL,whilethemostsignificantbyteofAXcanbeusedasasingle8bitregistercalledAH.
Thesenamesrefertothesamephysicalregister.WhenatwobytequantityisplacedintoDX,theupdate
affectsthevalueofDH,DL,andEDX.Thesesubregistersaremainlyholdoversfromolder,16bitversionsof
theinstructionset.However,theyaresometimesconvenientwhendealingwithdatathataresmallerthan32
bits(e.g.1byteASCIIcharacters).
Whenreferringtoregistersinassemblylanguage,thenamesarenotcasesensitive.Forexample,thenames
EAXandeaxrefertothesameregister.

http://www.cs.virginia.edu/~evans/cs216/guides/x86.html

1/14

10/5/2016

Guidetox86Assembly

Figure1.x86Registers

MemoryandAddressingModes
DeclaringStaticDataRegions
Youcandeclarestaticdataregions(analogoustoglobalvariables)inx86assemblyusingspecialassembler
directivesforthispurpose.Datadeclarationsshouldbeprecededbythe.DATAdirective.Followingthis
directive,thedirectivesDB,DW,andDDcanbeusedtodeclareone,two,andfourbytedatalocations,
respectively.Declaredlocationscanbelabeledwithnamesforlaterreferencethisissimilartodeclaring
variablesbyname,butabidesbysomelowerlevelrules.Forexample,locationsdeclaredinsequencewillbe
locatedinmemorynexttooneanother.
Exampledeclarations:

.DATA

Declareabyte,referredtoaslocationvar,containingthe
value64.
var2 DB?
Declareanuninitializedbyte,referredtoaslocationvar2.
Declareabytewithnolabel,containingthevalue10.Its
DB10
locationisvar2+1.
Declarea2byteuninitializedvalue,referredtoaslocation
X
DW?
X.
Y
DD30000 Declarea4bytevalue,referredtoaslocationY,initialized
to30000.
var

DB64

Unlikeinhighlevellanguageswherearrayscanhavemanydimensionsandareaccessedbyindices,arrays
inx86assemblylanguagearesimplyanumberofcellslocatedcontiguouslyinmemory.Anarraycanbe
declaredbyjustlistingthevalues,asinthefirstexamplebelow.Twoothercommonmethodsusedfor
declaringarraysofdataaretheDUPdirectiveandtheuseofstringliterals.TheDUPdirectivetellsthe
assemblertoduplicateanexpressionagivennumberoftimes.Forexample,4DUP(2)isequivalentto2,
2,2,2.
Someexamples:
http://www.cs.virginia.edu/~evans/cs216/guides/x86.html

2/14

10/5/2016

Guidetox86Assembly

DD1,2,3 Declarethree4bytevalues,initializedto1,2,and3.The
valueoflocationZ+8willbe3.
DB10
bytes
Declare10uninitializedbytesstartingatlocationbytes.
DUP(?)
DD100
Declare1004bytewordsstartingatlocationarr,all
arr
DUP(0) initializedto0
DB
Declare6bytesstartingattheaddressstr,initializedtothe
str
'hello',0 ASCIIcharactervaluesforhelloandthenull(0)byte.
AddressingMemory
Modernx86compatibleprocessorsarecapableofaddressingupto232bytesofmemory:memoryaddresses
are32bitswide.Intheexamplesabove,whereweusedlabelstorefertomemoryregions,theselabelsare
actuallyreplacedbytheassemblerwith32bitquantitiesthatspecifyaddressesinmemory.Inadditionto
supportingreferringtomemoryregionsbylabels(i.e.constantvalues),thex86providesaflexiblescheme
forcomputingandreferringtomemoryaddresses:uptotwoofthe32bitregistersanda32bitsigned
constantcanbeaddedtogethertocomputeamemoryaddress.Oneoftheregisterscanbeoptionallypre
multipliedby2,4,or8.
Theaddressingmodescanbeusedwithmanyx86instructions(we'lldescribetheminthenextsection).Here
weillustratesomeexamplesusingthemovinstructionthatmovesdatabetweenregistersandmemory.This
instructionhastwooperands:thefirstisthedestinationandthesecondspecifiesthesource.
Someexamplesofmovinstructionsusingaddresscomputationsare:

moveax,[ebx] Movethe4bytesinmemoryattheaddresscontainedinEBX
intoEAX
mov[var],ebx MovethecontentsofEBXintothe4bytesatmemoryaddress
var.(Note,varisa32bitconstant).
moveax,[esi
Move4bytesatmemoryaddressESI+(4)intoEAX
4]
mov[esi+eax],
MovethecontentsofCLintothebyteataddressESI+EAX
cl
movedx,
[esi+4*ebx] Movethe4bytesofdataataddressESI+4*EBXintoEDX
Someexamplesofinvalidaddresscalculationsinclude:

moveax,[ebxecx]
Canonlyaddregistervalues
mov[eax+esi+edi],ebxAtmost2registersinaddresscomputation
SizeDirectives
Ingeneral,theintendedsizeoftheofthedataitematagivenmemoryaddresscanbeinferredfromthe
assemblycodeinstructioninwhichitisreferenced.Forexample,inalloftheaboveinstructions,thesizeof
thememoryregionscouldbeinferredfromthesizeoftheregisteroperand.Whenwewereloadinga32bit
register,theassemblercouldinferthattheregionofmemorywewerereferringtowas4byteswide.When
wewerestoringthevalueofaonebyteregistertomemory,theassemblercouldinferthatwewantedthe
addresstorefertoasinglebyteinmemory.
However,insomecasesthesizeofareferredtomemoryregionisambiguous.Considertheinstructionmov
[ebx],2.Shouldthisinstructionmovethevalue2intothesinglebyteataddressEBX?Perhapsitshould
movethe32bitintegerrepresentationof2intothe4bytesstartingataddressEBX.Sinceeitherisavalid
possibleinterpretation,theassemblermustbeexplicitlydirectedastowhichiscorrect.Thesizedirectives
BYTEPTR,WORDPTR,andDWORDPTRservethispurpose,indicatingsizesof1,2,and4bytes
respectively.
http://www.cs.virginia.edu/~evans/cs216/guides/x86.html

3/14

10/5/2016

Guidetox86Assembly

Forexample:

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

Move2intothesinglebyteattheaddressstoredinEBX.
Movethe16bitintegerrepresentationof2intothe2bytes
startingattheaddressinEBX.
Movethe32bitintegerrepresentationof2intothe4bytes
startingattheaddressinEBX.

Instructions
Machineinstructionsgenerallyfallintothreecategories:datamovement,arithmetic/logic,andcontrolflow.
Inthissection,wewilllookatimportantexamplesofx86instructionsfromeachcategory.Thissection
shouldnotbeconsideredanexhaustivelistofx86instructions,butratherausefulsubset.Foracompletelist,
seeIntel'sinstructionsetreference.
Weusethefollowingnotation:

<reg32>Any32bitregister(EAX,EBX,ECX,EDX,ESI,EDI,ESP,orEBP)
<reg16>
Any16bitregister(AX,BX,CX,orDX)
<reg8>
Any8bitregister(AH,BH,CH,DH,AL,BL,CL,orDL)
<reg>
Anyregister
Amemoryaddress(e.g.,[eax],[var+4],ordwordptr
<mem>
[eax+ebx])
<con32>
Any32bitconstant
<con16>
Any16bitconstant
<con8>
Any8bitconstant
<con>
Any8,16,or32bitconstant

DataMovementInstructions
movMove(Opcodes:88,89,8A,8B,8C,8E,...)
Themovinstructioncopiesthedataitemreferredtobyitssecondoperand(i.e.register
contents,memorycontents,oraconstantvalue)intothelocationreferredtobyitsfirstoperand
(i.e.aregisterormemory).Whileregistertoregistermovesarepossible,directmemoryto
memorymovesarenot.Incaseswherememorytransfersaredesired,thesourcememory
contentsmustfirstbeloadedintoaregister,thencanbestoredtothedestinationmemory
address.
Syntax
mov<reg>,<reg>
mov<reg>,<mem>
mov<mem>,<reg>
mov<reg>,<const>
mov<mem>,<const>
Examples
moveax,ebxcopythevalueinebxintoeax
movbyteptr[var],5storethevalue5intothebyteatlocationvar

http://www.cs.virginia.edu/~evans/cs216/guides/x86.html

4/14

10/5/2016

Guidetox86Assembly

pushPushstack(Opcodes:FF,89,8A,8B,8C,8E,...)
Thepushinstructionplacesitsoperandontothetopofthehardwaresupportedstackin
memory.Specifically,pushfirstdecrementsESPby4,thenplacesitsoperandintothe
contentsofthe32bitlocationataddress[ESP].ESP(thestackpointer)isdecrementedbypush
sincethex86stackgrowsdowni.e.thestackgrowsfromhighaddressestoloweraddresses.
Syntax
push<reg32>
push<mem>
push<con32>
Examples
pusheaxpusheaxonthestack
push[var]pushthe4bytesataddressvarontothestack
popPopstack
Thepopinstructionremovesthe4bytedataelementfromthetopofthehardwaresupported
stackintothespecifiedoperand(i.e.registerormemorylocation).Itfirstmovesthe4bytes
locatedatmemorylocation[SP]intothespecifiedregisterormemorylocation,andthen
incrementsSPby4.
Syntax
pop<reg32>
pop<mem>
Examples
popedipopthetopelementofthestackintoEDI.
pop[ebx]popthetopelementofthestackintomemoryatthefourbytesstartingat
locationEBX.
leaLoadeffectiveaddress
Theleainstructionplacestheaddressspecifiedbyitssecondoperandintotheregister
specifiedbyitsfirstoperand.Note,thecontentsofthememorylocationarenotloaded,only
theeffectiveaddressiscomputedandplacedintotheregister.Thisisusefulforobtaininga
pointerintoamemoryregion.
Syntax
lea<reg32>,<mem>
Examples
leaedi,[ebx+4*esi]thequantityEBX+4*ESIisplacedinEDI.
leaeax,[var]thevalueinvarisplacedinEAX.
leaeax,[val]thevaluevalisplacedinEAX.

ArithmeticandLogicInstructions
addIntegerAddition
Theaddinstructionaddstogetheritstwooperands,storingtheresultinitsfirstoperand.Note,
whereasbothoperandsmayberegisters,atmostoneoperandmaybeamemorylocation.
Syntax
add<reg>,<reg>
add<reg>,<mem>
add<mem>,<reg>
http://www.cs.virginia.edu/~evans/cs216/guides/x86.html

5/14

10/5/2016

Guidetox86Assembly

add<reg>,<con>
add<mem>,<con>
Examples
addeax,10EAXEAX+10
addBYTEPTR[var],10add10tothesinglebytestoredatmemoryaddressvar
subIntegerSubtraction
Thesubinstructionstoresinthevalueofitsfirstoperandtheresultofsubtractingthevalueof
itssecondoperandfromthevalueofitsfirstoperand.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)and
threeoperand(lasttwosyntaxlistingsabove).
Thetwooperandformmultipliesitstwooperandstogetherandstorestheresultinthefirst
operand.Theresult(i.e.first)operandmustbearegister.
Thethreeoperandformmultipliesitssecondandthirdoperandstogetherandstorestheresult
initsfirstoperand.Again,theresultoperandmustbearegister.Furthermore,thethirdoperand
isrestrictedtobeingaconstantvalue.
Syntax
imul<reg32>,<reg32>
imul<reg32>,<mem>
imul<reg32>,<reg32>,<con>
imul<reg32>,<mem>,<con>
Examples
imuleax,[var]multiplythecontentsofEAXbythe32bitcontentsofthememory
locationvar.StoretheresultinEAX.
http://www.cs.virginia.edu/~evans/cs216/guides/x86.html

6/14

10/5/2016

Guidetox86Assembly

imulesi,edi,25ESIEDI*25
idivIntegerDivision
Theidivinstructiondividesthecontentsofthe64bitintegerEDX:EAX(constructedby
viewingEDXasthemostsignificantfourbytesandEAXastheleastsignificantfourbytes)by
thespecifiedoperandvalue.ThequotientresultofthedivisionisstoredintoEAX,whilethe
remainderisplacedinEDX.
Syntax
idiv<reg32>
idiv<mem>
Examples
idivebxdividethecontentsofEDX:EAXbythecontentsofEBX.Placethequotientin
EAXandtheremainderinEDX.
idivDWORDPTR[var]dividethecontentsofEDX:EASbythe32bitvaluestoredat
memorylocationvar.PlacethequotientinEAXandtheremainderinEDX.
and,or,xorBitwiselogicaland,orandexclusiveor
Theseinstructionsperformthespecifiedlogicaloperation(logicalbitwiseand,or,and
exclusiveor,respectively)ontheiroperands,placingtheresultinthefirstoperandlocation.
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.

http://www.cs.virginia.edu/~evans/cs216/guides/x86.html

7/14

10/5/2016

Guidetox86Assembly

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,clStoreinEBXthefloorofresultofdividingthevalueofEBXby2nwheren
isthevalueinCL.

ControlFlowInstructions
Thex86processormaintainsaninstructionpointer(IP)registerthatisa32bitvalueindicatingthelocation
inmemorywherethecurrentinstructionstarts.Normally,itincrementstopointtothenextinstructionin
memorybeginsafterexecutionaninstruction.TheIPregistercannotbemanipulateddirectly,butisupdated
implicitlybyprovidedcontrolflowinstructions.
Weusethenotation<label>torefertolabeledlocationsintheprogramtext.Labelscanbeinserted
anywhereinx86assemblycodetextbyenteringalabelnamefollowedbyacolon.Forexample,
movesi,[ebp+8]
begin:xorecx,ecx
moveax,[esi]
Thesecondinstructioninthiscodefragmentislabeledbegin.Elsewhereinthecode,wecanrefertothe
memorylocationthatthisinstructionislocatedatinmemoryusingthemoreconvenientsymbolicname
begin.Thislabelisjustaconvenientwayofexpressingthelocationinsteadofits32bitvalue.
jmpJump
Transfersprogramcontrolflowtotheinstructionatthememorylocationindicatedbythe
operand.
http://www.cs.virginia.edu/~evans/cs216/guides/x86.html

8/14

10/5/2016

Guidetox86Assembly

Syntax
jmp<label>
Example
jmpbeginJumptotheinstructionlabeledbegin.
jconditionConditionalJump
Theseinstructionsareconditionaljumpsthatarebasedonthestatusofasetofconditioncodes
thatarestoredinaspecialregistercalledthemachinestatusword.Thecontentsofthemachine
statuswordincludeinformationaboutthelastarithmeticoperationperformed.Forexample,
onebitofthiswordindicatesifthelastresultwaszero.Anotherindicatesifthelastresultwas
negative.Basedontheseconditioncodes,anumberofconditionaljumpscanbeperformed.For
example,thejzinstructionperformsajumptothespecifiedoperandlabeliftheresultofthe
lastarithmeticoperationwaszero.Otherwise,controlproceedstothenextinstructionin
sequence.
Anumberoftheconditionalbranchesaregivennamesthatareintuitivelybasedonthelast
operationperformedbeingaspecialcompareinstruction,cmp(seebelow).Forexample,
conditionalbranchessuchasjleandjnearebasedonfirstperformingacmpoperationon
thedesiredoperands.
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,settingtheconditioncodesinthemachine
statuswordappropriately.Thisinstructionisequivalenttothesubinstruction,excepttheresult
ofthesubtractionisdiscardedinsteadofreplacingthefirstoperand.
Syntax
cmp<reg>,<reg>
cmp<reg>,<mem>
cmp<mem>,<reg>
cmp<reg>,<con>
Example
cmpDWORDPTR[var],10
jeqloop
Ifthe4bytesstoredatlocationvarareequaltothe4byteintegerconstant10,jumptothe
locationlabeledloop.
call,retSubroutinecallandreturn
http://www.cs.virginia.edu/~evans/cs216/guides/x86.html

9/14

10/5/2016

Guidetox86Assembly

Theseinstructionsimplementasubroutinecallandreturn.Thecallinstructionfirstpushes
thecurrentcodelocationontothehardwaresupportedstackinmemory(seethepush
instructionfordetails),andthenperformsanunconditionaljumptothecodelocationindicated
bythelabeloperand.Unlikethesimplejumpinstructions,thecallinstructionsavesthe
locationtoreturntowhenthesubroutinecompletes.
Theretinstructionimplementsasubroutinereturnmechanism.Thisinstructionfirstpopsa
codelocationoffthehardwaresupportedinmemorystack(seethepopinstructionfordetails).
Itthenperformsanunconditionaljumptotheretrievedcodelocation.
Syntax
call<label>
ret

CallingConvention
Toallowseparateprogrammerstosharecodeanddeveloplibrariesforusebymanyprograms,andto
simplifytheuseofsubroutinesingeneral,programmerstypicallyadoptacommoncallingconvention.The
callingconventionisaprotocolabouthowtocallandreturnfromroutines.Forexample,givenasetof
callingconventionrules,aprogrammerneednotexaminethedefinitionofasubroutinetodeterminehow
parametersshouldbepassedtothatsubroutine.Furthermore,givenasetofcallingconventionrules,high
levellanguagecompilerscanbemadetofollowtherules,thusallowinghandcodedassemblylanguage
routinesandhighlevellanguageroutinestocalloneanother.
Inpractice,manycallingconventionsarepossible.WewillusethewidelyusedClanguagecalling
convention.Followingthisconventionwillallowyoutowriteassemblylanguagesubroutinesthataresafely
callablefromC(andC++)code,andwillalsoenableyoutocallClibraryfunctionsfromyourassembly
languagecode.
TheCcallingconventionisbasedheavilyontheuseofthehardwaresupportedstack.Itisbasedonthe
push,pop,call,andretinstructions.Subroutineparametersarepassedonthestack.Registersaresaved
onthestack,andlocalvariablesusedbysubroutinesareplacedinmemoryonthestack.Thevastmajorityof
highlevelprocedurallanguagesimplementedonmostprocessorshaveusedsimilarcallingconventions.
Thecallingconventionisbrokenintotwosetsofrules.Thefirstsetofrulesisemployedbythecallerofthe
subroutine,andthesecondsetofrulesisobservedbythewriterofthesubroutine(thecallee).Itshouldbe
emphasizedthatmistakesintheobservanceoftheserulesquicklyresultinfatalprogramerrorssincethe
stackwillbeleftinaninconsistentstatethusmeticulouscareshouldbeusedwhenimplementingthecall
conventioninyourownsubroutines.

http://www.cs.virginia.edu/~evans/cs216/guides/x86.html

10/14

10/5/2016

Guidetox86Assembly

>
StackduringSubroutineCall
[ThankstoJamesPetersonforfindingandfixingthebugintheoriginalversionofthisfigure!]

Agoodwaytovisualizetheoperationofthecallingconventionistodrawthecontentsofthenearbyregion
ofthestackduringsubroutineexecution.Theimageabovedepictsthecontentsofthestackduringthe
executionofasubroutinewiththreeparametersandthreelocalvariables.Thecellsdepictedinthestackare
32bitwidememorylocations,thusthememoryaddressesofthecellsare4bytesapart.Thefirstparameter
residesatanoffsetof8bytesfromthebasepointer.Abovetheparametersonthestack(andbelowthebase
pointer),thecallinstructionplacedthereturnaddress,thusleadingtoanextra4bytesofoffsetfromthe
basepointertothefirstparameter.Whentheretinstructionisusedtoreturnfromthesubroutine,itwill
jumptothereturnaddressstoredonthestack.
CallerRules
Tomakeasubroutingcall,thecallershould:
1.Beforecallingasubroutine,thecallershouldsavethecontentsofcertainregistersthataredesignated
callersaved.ThecallersavedregistersareEAX,ECX,EDX.Sincethecalledsubroutineisallowed
tomodifytheseregisters,ifthecallerreliesontheirvaluesafterthesubroutinereturns,thecallermust
pushthevaluesintheseregistersontothestack(sotheycanberestoreafterthesubroutinereturns.
2.Topassparameterstothesubroutine,pushthemontothestackbeforethecall.Theparametersshould
bepushedininvertedorder(i.e.lastparameterfirst).Sincethestackgrowsdown,thefirstparameter
willbestoredatthelowestaddress(thisinversionofparameterswashistoricallyusedtoallow
functionstobepassedavariablenumberofparameters).
3.Tocallthesubroutine,usethecallinstruction.Thisinstructionplacesthereturnaddressontopof
theparametersonthestack,andbranchestothesubroutinecode.Thisinvokesthesubroutine,which
shouldfollowthecalleerulesbelow.
Afterthesubroutinereturns(immediatelyfollowingthecallinstruction),thecallercanexpecttofindthe
returnvalueofthesubroutineintheregisterEAX.Torestorethemachinestate,thecallershould:
1.Removetheparametersfromstack.Thisrestoresthestacktoitsstatebeforethecallwasperformed.
2.Restorethecontentsofcallersavedregisters(EAX,ECX,EDX)bypoppingthemoffofthestack.
Thecallercanassumethatnootherregistersweremodifiedbythesubroutine.
http://www.cs.virginia.edu/~evans/cs216/guides/x86.html

11/14

10/5/2016

Guidetox86Assembly

Example
Thecodebelowshowsafunctioncallthatfollowsthecallerrules.Thecalleriscallingafunction_myFunc
thattakesthreeintegerparameters.FirstparameterisinEAX,thesecondparameteristheconstant216the
thirdparameterisinmemorylocationvar.
push[var];Pushlastparameterfirst
push216;Pushthesecondparameter
pusheax;Pushfirstparameterlast
call_myFunc;Callthefunction(assumeCnaming)
addesp,12
Notethatafterthecallreturns,thecallercleansupthestackusingtheaddinstruction.Wehave12bytes(3
parameters*4byteseach)onthestack,andthestackgrowsdown.Thus,togetridoftheparameters,wecan
simplyadd12tothestackpointer.
Theresultproducedby_myFuncisnowavailableforuseintheregisterEAX.Thevaluesofthecallersaved
registers(ECXandEDX),mayhavebeenchanged.Ifthecallerusesthemafterthecall,itwouldhave
neededtosavethemonthestackbeforethecallandrestorethemafterit.
CalleeRules
Thedefinitionofthesubroutineshouldadheretothefollowingrulesatthebeginningofthesubroutine:
1.PushthevalueofEBPontothestack,andthencopythevalueofESPintoEBPusingthefollowing
instructions:
pushebp
movebp,esp
Thisinitialactionmaintainsthebasepointer,EBP.Thebasepointerisusedbyconventionasapoint
ofreferenceforfindingparametersandlocalvariablesonthestack.Whenasubroutineisexecuting,
thebasepointerholdsacopyofthestackpointervaluefromwhenthesubroutinestartedexecuting.
Parametersandlocalvariableswillalwaysbelocatedatknown,constantoffsetsawayfromthebase
pointervalue.Wepushtheoldbasepointervalueatthebeginningofthesubroutinesothatwecan
laterrestoretheappropriatebasepointervalueforthecallerwhenthesubroutinereturns.Remember,
thecallerisnotexpectingthesubroutinetochangethevalueofthebasepointer.Wethenmovethe
stackpointerintoEBPtoobtainourpointofreferenceforaccessingparametersandlocalvariables.
2.Next,allocatelocalvariablesbymakingspaceonthestack.Recall,thestackgrowsdown,sotomake
spaceonthetopofthestack,thestackpointershouldbedecremented.Theamountbywhichthestack
pointerisdecrementeddependsonthenumberandsizeoflocalvariablesneeded.Forexample,if3
localintegers(4byteseach)wererequired,thestackpointerwouldneedtobedecrementedby12to
makespacefortheselocalvariables(i.e.,subesp,12).Aswithparameters,localvariableswill
belocatedatknownoffsetsfromthebasepointer.
3.Next,savethevaluesofthecalleesavedregistersthatwillbeusedbythefunction.Tosaveregisters,
pushthemontothestack.ThecalleesavedregistersareEBX,EDI,andESI(ESPandEBPwillalso
bepreservedbythecallingconvention,butneednotbepushedonthestackduringthisstep).
Afterthesethreeactionsareperformed,thebodyofthesubroutinemayproceed.Whenthesubroutineis
returns,itmustfollowthesesteps:
1.LeavethereturnvalueinEAX.
2.Restoretheoldvaluesofanycalleesavedregisters(EDIandESI)thatweremodified.Theregister
contentsarerestoredbypoppingthemfromthestack.Theregistersshouldbepoppedintheinverse
orderthattheywerepushed.
http://www.cs.virginia.edu/~evans/cs216/guides/x86.html

12/14

10/5/2016

Guidetox86Assembly

3.Deallocatelocalvariables.Theobviouswaytodothismightbetoaddtheappropriatevaluetothe
stackpointer(sincethespacewasallocatedbysubtractingtheneededamountfromthestackpointer).
Inpractice,alesserrorpronewaytodeallocatethevariablesistomovethevalueinthebasepointer
intothestackpointer:movesp,ebp.Thisworksbecausethebasepointeralwayscontainsthe
valuethatthestackpointercontainedimmediatelypriortotheallocationofthelocalvariables.
4.Immediatelybeforereturning,restorethecaller'sbasepointervaluebypoppingEBPoffthestack.
Recallthatthefirstthingwedidonentrytothesubroutinewastopushthebasepointertosaveitsold
value.
5.Finally,returntothecallerbyexecutingaretinstruction.Thisinstructionwillfindandremovethe
appropriatereturnaddressfromthestack.
Notethatthecallee'srulesfallcleanlyintotwohalvesthatarebasicallymirrorimagesofoneanother.The
firsthalfoftherulesapplytothebeginningofthefunction,andarecommonlysaidtodefinetheprologueto
thefunction.Thelatterhalfoftherulesapplytotheendofthefunction,andarethuscommonlysaidto
definetheepilogueofthefunction.
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(the
basepointer),allocatinglocalvariablesbydecrementingthestackpointer,andsavingregistervaluesonthe
stack.
Inthebodyofthesubroutinewecanseetheuseofthebasepointer.Bothparametersandlocalvariablesare
locatedatconstantoffsetsfromthebasepointerforthedurationofthesubroutinesexecution.Inparticular,
wenoticethatsinceparameterswereplacedontothestackbeforethesubroutinewascalled,theyarealways
http://www.cs.virginia.edu/~evans/cs216/guides/x86.html

13/14

10/5/2016

Guidetox86Assembly

locatedbelowthebasepointer(i.e.athigheraddresses)onthestack.Thefirstparametertothesubroutine
canalwaysbefoundatmemorylocation[EBP+8],thesecondat[EBP+12],thethirdat[EBP+16].Similarly,
sincelocalvariablesareallocatedafterthebasepointerisset,theyalwaysresideabovethebasepointer(i.e.
atloweraddresses)onthestack.Inparticular,thefirstlocalvariableisalwayslocatedat[EBP4],thesecond
at[EBP8],andsoon.Thisconventionaluseofthebasepointerallowsustoquicklyidentifytheuseoflocal
variablesandparameterswithinafunctionbody.
Thefunctionepilogueisbasicallyamirrorimageofthefunctionprologue.Thecaller'sregistervaluesare
recoveredfromthestack,thelocalvariablesaredeallocatedbyresettingthestackpointer,thecaller'sbase
pointervalueisrecovered,andtheretinstructionisusedtoreturntotheappropriatecodelocationinthe
caller.
Credits:ThisguidewasoriginallycreatedbyAdamFerrarimanyyearsago,
andsinceupdatedbyAlanBatson,MikeLack,andAnitaJones.
Itwasrevisedfor216Spring2006byDavidEvans.

CS216:ProgramandDataRepresentation
UniversityofVirginia

http://www.cs.virginia.edu/~evans/cs216/guides/x86.html

DavidEvans
evans@cs.virginia.edu
UsingtheseMaterials

14/14

You might also like