You are on page 1of 6

Chapter5Procedures

Essentialsof80x86AssemblyLanguage,SecondEdition
byRichardC.Detmer
JonesandBartlettLearning2012Citation

Recommend?

5.1The80x86Stack
Programsinthisbookhaveallocatedstackswiththecode
.STACK4096
This.STACKdirectivetellstheassemblertoreserve4096bytesofuninitializedstorage.Theoperatingsystem
initializesthestackpointerregisterESPtotheaddressofthefirstbyteabovethe4096bytesinthestack.A
largerorsmallerstackcouldbeallocated,dependingontheanticipatedusageintheprogram.
Thestackismostoftenusedbypushingdoublewordsonit,orbypoppingthemoffit.Thisisdoneautomatically
aspartoftheexecutionofcallandreturninstructions(seeSections5.2).Itisalsodonemanuallywith
pushandpopinstructions.Thissectioncoversthemechanicsofpushandpopinstructions,describinghow
theyusethestack.
Sourcecodeforapushinstructionhasthesyntax
pushsource
Thesourceoperandcanbearegister16,aregister32,asegmentregister,awordinmemory,adoublewordin
memory,animmediatebyte,animmediateword,oranimmediatedoubleword.Theonlybytesizeoperandis
immediate,andissignextendedtoawordordoublewordtogetthevalueactuallypushedonthestack.Figure
5.1listssomeallowableoperandtypes,omittingsegmentregistersthatwewillnotuse.Theusualmnemonicfor
apushinstructionisjustpush.However,ifthereisambiguityaboutthesizeoftheoperand(astherewouldbe
withasmallimmediatevalue)thenyoucanusepushworpushdmnemonicstospecifywordsizeor
doublewordsizeoperands,respectively.TheWORDPTRandDWORDPTRoperatorsareusedwithmemory
operandswhenneeded.
Operand
EAXorAX
ECXorCX
EDXorDX
EBXorBX
ESPorSP
EBPorBP
ESIorSI
EDIorDI
memoryword
memorydoubleword
immediatebyte
immediateword
immediatedoubleword

Opcode
50
51
52
53
54
55
56
57
FF
FF
6A
68
68

Figure5.1:pushinstructions

BytesofObjectCode
1
1
1
1
1
1
1
1
2+
2+
2
3
5

Whenapushinstructionisexecutedforadoublewordsizeoperand,thestackpointerESPisdecrementedby
4.RecallthatinitiallyESPcontainstheaddressofthebytejustabovetheallocatedspace.Subtracting4makes
ESPpointtothetopdoublewordinthestack.TheoperandisthenstoredattheaddressinESP,thatis,atthe
highmemoryendofthestackspace.Executionissimilarforawordsizeoperand,exceptthatESPis
decrementedby2beforetheoperandisstored.
Example
Wenowshowanexampleofexecutionoftwopushinstructions.ItassumesthatESPinitiallycontains
00600200.ThefirstpushdecrementsESPto006001FCandthenstoresthecontentsofEAXatthataddress.
Noticethattheloworderandhighorderbytesarereversedinmemory.ThesecondpushdecrementsESPto
006001F8andstoresFFFFFF10(24010)atthataddress.

Youcanusethedebuggertowatchtheseinstructionsactuallyexecute.Afteryouassembleaprogramstarting
with
moveax,83b547a2h
pusheax
pushd240
theassemblylistingdisplays
00000000B883B547A2moveax,83b547a2h
0000000550pusheax
0000000668FFFFFF10pushd240
ThisisexpectedfromtheopcodeslistedinFigure3.1formovandFigure5.1forpush.Figure5.2showsthe
WinDbgdisplayaftertheEAXregisterhasbeeninitializedwith83B547A2.Wejustwanttoseethetopfewbytes
ofthestack,sowenotethatESPcontains0036FF80.(Itmighthaveanothervalueatanothertimeoronanother
computer.)Todisplaythetop16bytes,weopenamemoryviewstartingataddress0x36FF70.Thesebytesare
shownonthetoptwolinesofthememorywindow.Noticethatthestackcontains"junk"valueszerosinthis
case.


Figure5.2:Stacktestpriortopushoperation

Figure5.3:EAXhasbeenpushedontothestack
Nowexecutethepushinstruction.TheresultingdisplayisshowninFigure5.3.NoticethatESPnowcontains
0036FF7C,thatis,ithasbeendecrementedby4.Thelast4bytesonthesecondmemoryline(inred)showthe
doublewordstoredatthenewstackpointeraddress.ThebytesfromEAXhavebeenstoredbackwardin
memory.Finally,executethepushdinstruction.TheresultingdisplayisshowninFigure5.4.ESPnowcontains
0036FF78,againdecrementedby4.Thefirst4bytesofthesecondmemorylineshowthevalueof240,again
withthebytesofFFFFFF10storedinreverseorder.
Ifadditionaloperandswerepushedontothestack,ESPwouldbedecrementedfurtherandthenewvalues
stored.Nopushinstructionaffectsanyflagbit.
Noticethatastack"growsdownward,"contrarytotheimagethatyoumayhaveofatypicalsoftwarestack.[1]
Alsonoticethattheonlyvalueonthestackthatisreadilyavailableisthelastonepusheditisattheaddressin
ESP.Furthermore,ESPchangesfrequentlyasyoupushvaluesandasprocedurecallsaremade.Inthenext
sectionyouwilllearnawaytoestablishafixedreferencepointinthemiddleofthestackusingtheEBPregister,
sothatvaluesnearthatpointcanbeaccessedwithouthavingtopopoffalltheintermediatevalues.


Figure5.4:240hasbeenpushedontothestack
Popinstructionsdotheoppositejobofpushinstructions.Eachpopinstructionhastheformat
popdestination
wheredestinationcanreferenceawordordoublewordinmemory,anyregister16,anyregister32,orany
segmentregisterexceptCS.(ThepushinstructiondoesnotexcludeCS.)Thepopinstructiongetsa
doublewordsizevaluefromthestackbycopyingthedoublewordattheaddressinESPtothedestination,then
incrementingESPby4.Theoperationforawordsizevalueissimilar,exceptthatESPisincrementedby2.
Figure5.5givesinformationaboutpopinstructionsfordifferentdestinationoperands.Segmentregistersare
againomitted.Popinstructionsdonotaffectflags.
Example
Hereisanexampletoshowhowpopinstructionswork.ThedoublewordattheaddressinESPiscopiedtoECX
beforeESPisincrementedby4.Thevaluespoppedfromthestackarephysicallystillthereeventhoughthey
logicallyhavebeenremoved.Noteagainthatthebytesofadoublewordarestoredbackwardinmemoryinthe
80x86architecture.

Operand
EAXorAX
ECXorCX
EDXorDX
EBXorBX

Opcode
58
59
5A
5B

BytesofObjectCode
1
1
1
1

ESPorSP
EBPorBP
ESIorSI
EDIorDI
memoryword
memorydoubleword

5C
5D
5E
5F
8F
8F

1
1
1
1
2+
2+

Figure5.5:popinstructions
Wehavenotedpreviouslythatregistersareascarceresourcewhenprogramming.Oneuseofpushandpop
instructionsistotemporarilysavethecontentsofaregisteronthestack.Suppose,forexample,thatyouare
usingEDXtostoresomeprogramvariable,butneedtodoadivisionthatrequiresyoutoextendadividendinto
EDX:EAXpriortotheoperation.OnewaytoavoidlosingthevalueinEDXistopushitonthestack.
pushedxsavevariable
cdqextenddividendtoquadword
idivdivisordivide
popedxrestorevariable
Thisexampleassumesthatyoudon'tneedtheremainderthedivisionoperationputsinEDX.Ifyoudoneedthe
remainder,itcouldbecopiedsomewhereelsebeforepoppingthesavedvaluebacktoEDX.
Astheaboveexampleshows,pushandpopinstructionsareoftenusedinpairs.Whenweexaminehowthe
stackisusedtopassparameterstoprocedures,youwillseeawaytologicallydiscardvaluesfromthestack
withoutpoppingthemtoadestinationlocation.
Ina32bitenvironmentthestackiscreatedonadoublewordboundary,thatis,theaddressinESPwillbea
multipleof4.Itisimportanttokeepthestacktoponadoublewordboundaryforcertainsystemcalls.Therefore,
withfewexceptions,youshouldalwayspushdoublewordvaluesonthestack,eventhoughthe80x86
architectureallowswordstobeused.
Inadditiontotheordinarypushandpopinstructions,therearespecialmnemonicstopushandpopflag
registers.Thesearepushf(pushfdfortheextendedflagregister)andpopf(popfdfortheextendedflag
register).ThesearesummarizedinFigure5.6.Theyaresometimesusedinprocedurecode.Obviously,popf
andpopfdinstructionschangeflagvaluesthesearetheonlypushorpopinstructionsthatchangeflags.
Instruction
pushf/pushfd

Opcode
9C

BytesofObjectCode
1

popf/popfd

9D

Figure5.6:pushfandpopfinstructions
The80x86architecturehaspushadandpopadinstructionsthatpushorpopallgeneralpurposeregisterswitha
singleinstruction.Thesearerarelyusefulanddonotworkin64bitmode,sotheyarenotusedinthisbook.
Exercises5.1
1. Foreachinstruction,givetheopcodeandthenumberofbytesofobjectcodeincludingprefix
bytes.Assumethatdoublereferencesadoublewordinmemory.
a. pushax
b. pushd10
c. pushebp
d. popebx
e. popdouble

f. popdx
g. pushfd
2. Foreachpartofthisproblem,assumethe"before"valueswhenthegiveninstructionsare
executed.Givetherequested"after"values.Traceexecutionoftheinstructionsbydrawing
picturesofthestack

(a)

(b)

(c)

Before
ESP:06001000

Instructions
pushecx

After
ESP,ECX

ECX:01A25B74

pushd10

ESP:02000B7C

pushd20

EBX:12345678

pushebx

ESP:0010F83A

pusheax

EAX:12345678

pushd30

ESP,EBX

ESP,EAX,EBX,ECX

popebx

popecx

3. Manymicroprocessorsdonothaveaninstructionequivalenttoxchg.Withsuchsystems,a
sequenceofinstructionslikethefollowingcanbeusedtoexchangethecontentsoftworegisters:
pusheax
pushebx
popeax
popebx
ExplainwhythissequenceworkstoexchangethecontentsoftheEAXandEBXregisters.
Comparethenumberofbytesofcoderequiredtoexecutethissequencewiththoserequiredforthe
instructionxchgeax,ebx.
4. Anotheralternativetothexchginstructionistouse
pusheax
moveax,ebx
popebx
ExplainwhythissequenceworkstoexchangethecontentsoftheEAXandEBXregisters.
Comparethenumberofbytesofcoderequiredtoexecutethissequencewiththoserequiredforthe
instructionxchgeax,ebx.
[1]Ofcourse,ifyoudrawthepicturesothatlowermemoryaddressesareatthetop,thenit"growsupward."The

author'spreferenceistodrawthepicturessothatwhenESPisdecremented,its"pointer"movesdown.

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

You might also like