You are on page 1of 7

Chapter5Procedures

Essentialsof80x86AssemblyLanguage,SecondEdition
byRichardC.Detmer
JonesandBartlettLearning2012Citation

Recommend?

5.232BitProcedureswithValueParameters
Thewordprocedureisusedinhighlevellanguagestodescribeasubprogramthatisalmostaselfcontained
unit.Themainprogramoranothersubprogramcancallaprocedurebyincludingastatementthatconsistsofthe
procedurenamefollowedbyaparenthesizedlistofargumentstobeassociatedwiththeprocedure'sformal
parameters.
Manyhighlevellanguagesdistinguishbetweenaprocedurethatperformsanactionandafunctionthatreturnsa
value.Afunctionissimilartoaprocedureexceptthatitiscalledbyusingitsnameandargumentlistinan
expression.Itreturnsavalueassociatedwithitsnamethisvalueisthenusedintheexpression.All
subprogramsinC/C++aretechnicallyfunctionsinthissense,buttheselanguagesallowforfunctionsthatreturn
novalue.
Inassemblylanguageandinsomehighlevellanguagesthetermprocedureisusedtodescribebothtypesof
subprograms:thosethatreturnvaluesandthosethatdonot.Thewordprocedureisusedinbothsensesinthis
book.
Proceduresarevaluableinassemblylanguageforthesamereasonsasinhighlevellanguagestheyhelp
divideprogramsintomanageabletasksandtheyisolatecodethatcanbeusedmultipletimeswithinasingle
program,orthatcanbesavedandreusedinotherprograms.Sometimesassemblylanguagecanbeusedto
writemoreefficientcodethanisproducedbyahighlevellanguagecompilerandthiscodecanbeputina
procedurecalledbyahighlevelprogramthatdoestasksthatdon'tneedtobeasefficient.
Recallthemajormainconceptslistedintheintroductiontothischapter:(1)howtotransfercontrolfromacalling
programtoaprocedureandback,(2)howtopassparametervaluestoaprocedureandresultsbackfromthe
procedure,and(3)howtowriteprocedurecodethatisindependentofthecallingprogram.Thesecanbehandled
inmanywaysinassemblylanguage,andthissectiondescribesoneparticularprotocol,calledcdeclinMicrosoft
documentation.ItisthedefaultconventionusedinCprogramsintheVisualStudioenvironment.Figure5.7
givesacompleteconsole32programthatisusedtoillustrateaspectsofthisprotocol.

Callproceduretoevaluate3*x+7*y
Author:R.Detmer
Date:10/2010
.586
.MODELFLAT
.STACK4096
.DATA
number1DWORD12
number2DWORD5
.CODE
mainPROC
pushnumber22ndparameter
pushnumber11stparameter
callfctn1fctn1(number1,number2)
addesp,8removeparametersfromstack

moveax,0exitwithreturncode0
ret
mainENDP
intfctn1(intx,inty)
returns3*x+7*y
fctn1PROC
pushebpsavebasepointer
movebp,espestablishstackframe
pushebxsaveEBX
moveax,[ebp+8]x
imuleax,33*x
movebx,[ebp+12]y
imulebx,77*y
addeax,ebx3*x+7*y
popebxrestoreEBX
popebprestoreEBP
retreturn
fctn1ENDP
END
Figure5.7:Procedureexample
Thecodeforaprocedurealwaysfollowsa.CODEdirective.ThebodyofaprocedureisbracketedbyPROCand
ENDPdirectives.Eachofthesedirectiveshasalabelthatgivesthenameoftheprocedure.mainisaprocedure
inaconsole32program.Additionalassemblylanguageprocedurescangointhesamecodesegmentbeforeor
afterprogramsmain.Theycanevenbeinseparatefiles.
Let'sfirstlookathowtotransfercontrolfrommaintotheprocedurefctn1.Thisisdonebytheinstruction
callfctn1
Ingeneral,acallinstructionsavestheaddressofthenextinstruction(theoneimmediatelyfollowingthecall),
thentransferscontroltotheprocedurecode.ItdoesthisbypushingEIPontothestackandthenchangingEIP
tocontaintheaddressofthefirstinstructionoftheprocedure.
Transferringcontrolbackfromaprocedureisaccomplishedbyreversingtheabovesteps.Aret(return)
instructionpopsthestackintoEIP,sothatthenextinstructiontobeexecutedistheoneattheaddressthat
waspushedonthestackbythecall.Thereisalmostalwaysatleastoneretinstructioninaprocedureand
therecanbemorethanone.Ifthereisonlyoneret,itisordinarilythelastinstructionintheproceduresince
subsequentinstructionswouldbeunreachablewithout"spaghetticode."Althoughacallinstructionmust
identifyitsdestination,theretdoesnotcontrolwilltransfertotheinstructionfollowingthemostrecentcall.
Theaddressofthatinstructionisstoredonthe80x86stack.
Thesyntaxofthe80x86callstatementis
calldestination
Figure5.8listssomeofthe80x86callinstructions.Nocallinstructionmodifiesanyflag.Alloftheprocedure
callsusedinthisbookwillbethefirsttype,nearrelative.Foranearrelativecall,the5bytesoftheinstruction
consistoftheE8opcodeplusthedisplacementfromthenextinstructiontothefirstinstructionoftheprocedure.
Thetransferofcontrolwhenaprocedureiscalledissimilartothetransferofarelativejump,exceptthattheold
contentsofEIParepushed.
Nearindirectcallsencodearegister32orareferencetoadoublewordinmemory.Whenthecallisexecuted,

thecontentsofthatregisterordoublewordareusedastheaddressoftheprocedure.Thismakesitpossiblefor
acallinstructiontogotodifferentproceduresdifferenttimes.
Operand
nearrelative
nearindirectusingregister
nearindirectusingmemory
fardirect
farindirect

Opcode
E8
FF
FF
9A
FF

BytesofObjectCode
5
2
2+
7
6+

Figure5.8:callinstructions
AllfarcallsmustprovidebothnewCScontentsandnewEIPcontents.Withfardirectcalls,bothoftheseare
codedintheinstruction,andthese6bytesplusthe1fortheopcodemakethe7seeninFigure5.8.Withfar
indirectcalls,thesearelocatedata6byteblockinmemory,andtheaddressofthatblockiscodedinthe
instruction.TheextrabyteisaModR/Mbyte.Farcallswereveryimportantwhenthesegmentedmemorymodel
wasused.
Thereturninstructionretisusedtotransfercontrolfromaprocedurebodybacktothecallingpoint.Itsbasic
operationissimpleitsimplypopstheaddresspreviouslystoredonthestackandloadsitintotheinstruction
pointerEIP.Sincethestackcontainstheaddressoftheinstructionfollowingthecall,executionwillcontinueat
thatpoint.AnearreturnjusthastorestoreEIP.Afarreturninstructionreversesthestepsofafarcall,restoring
bothEIPandCSbothofthesevaluesarepoppedfromthestack.Noretinstructionchangesanyflag.
Therearetwoformatsfortheretinstruction.Themorecommonformhasnooperand,andissimplycoded
ret
Theotherversionhasasingleoperand,andiscoded
retcount
TheoperandcountisaddedtothecontentsofESPaftercompletionoftheotherstepsofthereturnprocess
(poppingEIPand,forafarprocedure,CS).Thiscanbeusefulifothervalues(parametersinparticular)have
beensavedonthestackjustfortheprocedurecallthisisnotusedwiththecdeclprotocol,however.Figure5.9
liststhevariousformatsofretinstructions.
Type
near
near
far
far

Operand
none
immediate
none
immediate

Opcode
C3
C2
CB
CA

BytesofObjectCode
1
3
1
3

Figure5.9:retinstructions
Usingahighlevellanguage,aproceduredefinitionoftenincludesparameters(sometimescalledformal
parameters)thatareassociatedwitharguments(alsocalledactualparameters)whentheprocedureiscalled.
Fortheprocedure'spassbyvalue(in)parameters,valuesofthearguments(whichmaybeexpressions)are
copiedtotheparameterswhentheprocedureiscalled,andthesevaluesarethenreferencedintheprocedure
usingtheirlocalnames(theidentifiersusedtodefinetheparameters).Reference(passbylocationorinout)
parametersassociateaparameteridentifierwithanargumentthatisasinglevariable,andcanbeusedtopass
avalueeithertotheprocedurefromthecallerorfromtheprocedurebacktothecaller.Referenceparametersare
coveredinthenextsection.
OurexamplecodeinFigure5.7hastwoarguments(number1andnumber2)inmainthatarepassedbyvalueto
twoparameters(xandy)infctn1.Wenowlookathowtopassparametervaluestoaprocedureandresultsback
fromtheprocedure.Thesecondpartofthisissimpleiftheprocedurereturnsasingledoublewordvalue,thenit

putsthatvalueinEAXtobeusedbythecallingprogram.Noticethatthisisexactlywhatfctn1doesinthe
programinFigure5.7aftersomepreliminaries(explainednext),itcomputesthedesiredvalueinEAXwhereitis
availablebackinmain.Withthecdeclprotocol,onlytheEAXregistermaybeusedforthispurpose.
Doublewordparametersarepassedtotheprocedurebypushingthemonthestack.Inthecdeclprotocol,the
parametersarepushedonthestackintheoppositeorderinwhichtheyappearintheparameterlistthelast
parametervalueispushedfirstandthefirstparametervalueispushedlast.Thecodethatcallsfctn1inmainis
pushnumber22ndparameter
pushnumber11stparameter
callfctn1fctn1(number1,number2)
addesp,8removeparametersfromstack
Thefirsttwostatementsobviouslypushtheargumentvaluesonthestackpriortotheprocedurecall.The
purposeofthelaststatementistoremovethevaluesfromthestackfollowingreturnfromtheprocedure.Ifthe
stackisnotcleanedupandaprogramrepeatedlycallsaprocedure,eventuallythestackwillfillupcausinga
runtimeerrorwithmodernoperatingsystems.Argumentscouldberemovedusingthealternativeformoftheret
statementthatspecifiesanoperand,butthecdeclprotocolspecificallyleavesthestackcleanuptasktothe
callingprogram.Theargumentscouldberemovedbypoppingthevaluesoffthestack,butitismoreefficientto
simplyaddthenumberofbytesofparameterstoESP,movingthestackpointerabovethevalues.
Now,welookathowaprocedureretrievesparametervaluesfromthestack.Uponentrytotheprocedure,the
stacklooksliketheleftillustrationinFigure5.10.Thetwoargumentsnowtheparametervalueshavebeen
pushedonthestackbythecallingprogramandthereturnaddresshasbeenpushedonthestackbythecall
instruction.Thefirstinstructionsexecutedbytheprocedureare
pushebpsavebasepointer
movebp,espestablishstackframe
pushebxsaveEBX
Thisisknownasentrycode.Thefirsttwoinstructionswillalwaysbethepairshown.TheypreserveEBPso
thatitcanberestoredbeforereturning,andsetEBPtopointatafixedplaceinthestackthatcanbeusedto
locateparameters.ThethirdinstructionisneededinthisproceduresothatEBXcanbeusedforcomputations
withintheprocedureandthenrestoredbeforereturnthismakesitsuseintheproceduretransparenttothe
callingprogram.Afterthesethreeinstructionsareexecuted,thestacklooksliketherightillustrationinFigure
5.10.
Thereare8bytesstoredbetweentheaddressstoredinEBPandthefirstparameter(x)value.Parameter1can
bereferencedusingbasedaddressingby[ebp+8].Thesecondparameter(y)valueis4byteshigheronthe
stackitsreferenceis[ebp+12].Thecode
moveax,[ebp+8]x
imuleax,33*x
movebx,[ebp+12]y
imulebx,77*y
addeax,ebx3*x+7*y
copiesthevalueofthefirstparameterfromthestackintoEAXandthevalueofthesecondparameterfromthe
stackintoEBXinordertocomputethedesiredpromisedresult.


Figure5.10:Establishingbasepointerinprocedureentrycode
YoumaywonderwhyEBPisusedatall.WhynotjustuseESPasabaseregister?Theprincipalreasonisthat
ESPislikelytochange,buttheinstructionmovebp,esploadsEBPwithafixedreferencepointinthestack.
Thisfixedreferencepointwillnotchangeasotherinstructionsintheprocedureareexecuted,evenifthestack
isusedforotherpurposes,forexample,topushadditionalregistersortocallotherprocedures.
Wenowcometothethirdmajorconcept,howtowriteprocedurecodethatisindependentofandpreservesthe
environmentforthecallingprogram.Youhavealreadyseenmostofthecodeforthis.Basically,theentrycode
pusheseachregisterthatwillbeusedbytheprocedure,andtheexitcodepopsthemintheoppositeorder.
Obviously,youmustnotsaveandrestoreEAXwhenavalueisbeingreturnedinEAX.Theexitcodeforour
exampleconsistsof
popebxrestoreEBX
popebprestoreEBP
retreturn
EBPisalwaysrestoredlastsinceitisalwayssavedfirst.ThisexampleonlyusedEBXforcomputations,butit
isnotunusualtosaveandrestoreseveralregisters.Figure5.11summarizesthecdeclprotocol.


Figure5.11:cdeclprotocol
Exercises5.2
1. Supposethattheprocedureexercise1iscalledbytheinstruction
callexercise1
Ifthiscallstatementisataddress00402000andESPcontains00406000beforethecall,what
returnaddresswillbeonthestackwhenthefirstinstructionofprocedureexercise1isexecuted?
WhatwillbethevalueinESP?
2. Supposethataprocedurebeginswiththisentrycode
pushebpsaveEBP
movebp,espnewbasepointer
pushecxsaveregisters
pushesi

Assumethatthisprocedurehasthreedoublewordparameterswhoseformalorderisfirstx,theny,
andlastz.Drawapictureofthestackfollowingexecutionoftheabovecode.Includeparameters,
returnaddress,andshowthebytestowhichEBPandESPpoint.Givethebasedaddresswith
whicheachparametercanbereferenced.
ProgrammingExercises5.2
Foreachoftheseexercisesfollowthecdeclprotocolforthespecifiedprocedureandwriteashortconsole32
testdriverprogramtotesttheprocedure.
1. WriteaprocedurediscrthatcouldbedescribedinC/C++by
intdiscr(inta,intb,intc)
//returnthediscriminantb*b4*a*c
thatis,itsnameisdiscr,ithasthreedoublewordintegerparameters,anditisavaluereturning
procedure.
2. Writeavaluereturningproceduremin2tofindthesmalleroftwodoublewordintegerparameters.
3. Writeavaluereturningproceduremax3tofindthelargestofthreedoublewordintegerparameters.
4. ProgrammingExercise4.3.6hasanalgorithmforfindingthegreatestcommondivisoroftwo
positiveintegers.Writeaproceduregcdtoimplementthisalgorithm.Itmightbedescribedin
C/C++byintgcd(intnumber1,intnumber2),thatis,itsnameisgcd,ithastwo
doublewordintegerparameters,anditisavaluereturningprocedure.

UseofcontentonthissiteissubjecttotherestrictionssetforthintheTermsofUse.
PageLayoutandDesign2015SkillsoftIrelandLimitedAllrightsreserved,individualcontentisownedby
respectivecopyrightholder.
Feedback|PrivacyandCookiePolicy(Updated12/2014)|v.4.0.78.153

You might also like