TheArtofAssembly
Language
ISBN:1886411972
byRandall
Hyde
NoStarchPress©2003(903
pages)
Presentingassembly
languagefromthehigh-level
programmer'spointofview,
thisguideexplainshowto
edit,compile,andrunan
HLAprogram,converthigh
levelcontrolstructures,
translatearithmetic
expressions,andmore.
CDContent
TableofContents
TheArtofAssemblyLanguage
Hello,WorldofAssembly
Chapter1 Language
Chapter2 - DataRepresentation
MemoryAccessand
Chapter3 Organization
Constants,Variables,and
Chapter4 DataTypes
Chapter5 - ProceduresandUnits
Chapter6 - Arithmetic
LowLevelControl
Chapter7 Structures
Chapter8 - Files
Chapter9 - AdvancedArithmetic
MacrosandtheHLA
Chapter10 CompileTimeLanguage
Chapter11 - BITManipulation
Chapter12 - TheStringInstructions
Chapter13 - TheMMXInstructionSet
Chapter14 - ClassesandObjects
MixedLanguage
Chapter15 Programming
AppendixA - ASCIICharacterSet
The80×86Instruction
AppendixB Set
Index
ListofFigures
ListofTables
ListofListings
CDContent
BackCover
Assemblylanguageiseasierthanever,thanksto
moderndevelopmenttoolsandTheArtofAssembly
Language.
Afteradecadeofrigorousend-usertestingofthe
onlineversion,TheArtofAssemblyLanguageisan
indispensablereferenceforusingassemblytowrite
powerfulprogramsandsolvereal-worldproblems.
Hydehasupdatedhisbooktoincludethelatestin32bitx86architecture,aswellastheHighLevel
Assembler(HLA),arevolutionarytoolthatleverages
yourknowledgeofhighlevelprogramminglanguages
likeC/C++andPascal/Delphitostreamlineyour
learningprocess.
Learnhowto:
Edit,compile,andrunaHighLevelAssembler
(HLA)program
Declareanduseconstants,scalarvariables,
integers,reals,datatypes,pointers,arrays,
records/structures,unions,andnamespaces
Translatearithmeticexpressions(integerand
floatingpoint)
Converthighlevelcontrolstructures
Interfacewithhighlevelprogramminglanguages
AbouttheAuthor
RandallHydehastaughtassemblylanguageatthe
universitylevelforoveradecade,andhasdeveloped
severalcommercialsoftwaresystems.Hiswebsite,
“Webster:ThePlaceontheNettoLearnAssembly
LanguageProgramming,”isthepremierdestinationfor
anyonelearningassembly.HydeistheauthorofHow
toProgramtheAppleIIUsing6502Assembly
Languageandco-authorofTheWaiteGroup’sMASM
6.0Bible.
TheArtofAssemblyLanguage
RandallHyde
NOSTARCHPRESS
SanFrancisco
Copyright©2003RandallHyde.
Allrightsreserved.Nopartofthisworkmaybereproducedortransmitted
inanyformorbyanymeans,electronicormechanical,including
photocopying,recording,orbyanyinformationstorageorretrieval
system,withoutthepriorwrittenpermissionofthecopyrightownerand
thepublisher.
12345678910–06050403
NoStarchPressandtheNoStarchPresslogoareregisteredtrademarks
ofNoStarchPress,Inc.Otherproductandcompanynamesmentioned
hereinmaybethetrademarksoftheirrespectiveowners.Ratherthan
useatrademarksymbolwitheveryoccurrenceofatrademarkedname,
weareusingthenamesonlyinaneditorialfashionandtothebenefitof
thetrademarkowner,withnointentionofinfringementofthetrademark.
Publisher:WilliamPollock
ManagingEditor:KarolJurado
CoverandInteriorDesign:OctopodStudios
Copyeditor:KenyonBrown
Proofreader:StephanieProvines
Compositor:Wedobooks
DistributedtothebooktradeintheUnitedStatesbyPublishersGroup
West,1700FourthStreet,Berkeley,CA94710;phone:800-788-3123;
fax:510-658-1834.
DistributedtothebooktradeinCanadabyJacquelineGross&
Associates,Inc.,OneAtlanticAvenue,Suite105,Toronto,OntarioM6K
3E7Canada;phone:416-531-6737;fax416-531-4259.
ForinformationontranslationsorbookdistributorsoutsidetheUnited
States,pleasecontactNoStarchPress,Inc.directly:
NoStarchPress,Inc.
555DeHaroStreet,Suite250,SanFrancisco,CA94107
phone:415-863-9900;fax:415-863-9950;;
Theinformationinthisbookisdistributedonan"AsIs"basis,without
warranty.Whileeveryprecautionhasbeentakeninthepreparationof
thiswork,neithertheauthornorNoStarchPress,Inc.shallhaveany
liabilitytoanypersonorentitywithrespecttoanylossordamagecaused
orallegedtobecauseddirectlyorindirectlybytheinformationcontained
init.
LibraryofCongressCataloguing-in-PublicationData
Hyde,Randall.
Theartofassemblylanguage/RandallHyde.
p.cm.
1-886411-97-2
1.Assemblylanguage(Computerprogramlanguage)2.Programming
languages(Electroniccomputers)
I.Title.
QA76.73.A8H972003
005.13′6–dc212003000471
ACKNOWLEDGMENTS
Thisbookhasliterallytakenoveradecadetocreate.Itstartedoutas
"HowtoProgramtheIBMPC,Using8088AssemblyLanguage"way
backin1989.Ioriginallywrotethisbookforthestudentsinmyassembly
languagecourseatCalPolyPomonaandUCRiverside.Overtheyears,
hundredsofstudentshavemadesmallandlargecontributions(it's
amazinghowalittleextracreditcanmotivatesomestudents).I'vealso
receivedthousandsofcommentsviatheInternetafterplacinganearly,
16-biteditionofthisbookonmywebsiteatUCRiverside.Ioweeveryone
whohascontributedtothiseffortmygratitude.
IwouldalsoliketospecificallythankMaryPhillips,whospentseveral
monthshelpingmeproofreadmuchofthe16-biteditionuponwhichI've
basedthisbook.Maryisawonderfulpersonandagreatfriend.
IalsooweadeepdebtofgratitudetoWilliamPollockatNoStarchPress,
whorescuedthisbookfromobscurity.Heistheoneresponsiblefor
convincingmetospendsometimebeatingonthisbooktocreatea
publishableentityfromit.IwouldalsoliketothankKarolJuradofor
shepherdingthisprojectfromitsinception—it'sbeenalong,hardroad.
Thanks,Karol.
Chapter1:Hello,WorldofAssemblyLanguage
DownloadCDContent
1.1ChapterOverview
Thischapterisa"quick-start"chapterthatletsyoustartwritingbasic
assemblylanguageprogramsasrapidlyaspossible.Thischapter:
PresentsthebasicsyntaxofanHLA(HighLevelAssembly)
program
IntroducesyoutotheIntelCPUarchitecture
Providesahandfulofdatadeclarations,machineinstructions,
andhighlevelcontrolstatements
DescribessomeutilityroutinesyoucancallintheHLAStandard
Library
Showsyouhowtowritesomesimpleassemblylanguage
programs
Bytheconclusionofthischapter,youshouldunderstandthebasicsyntax
ofanHLAprogramandshouldunderstandtheprerequisitesthatare
neededtostartlearningnewassemblylanguagefeaturesinthechapters
thatfollow.
1.2TheAnatomyofanHLAProgram
AtypicalHLAprogramtakestheformshowninFigure1-1.
Figure1-1:BasicHLAProgram.
pgmIDinthetemplateaboveisauser-definedprogramidentifier.You
mustpickanappropriate,descriptivenameforyourprogram.In
particular,pgmIDwouldbeahorriblechoiceforanyrealprogram.Ifyou
arewritingprogramsaspartofacourseassignment,yourinstructorwill
probablygiveyouthenametouseforyourmainprogram.Ifyouare
writingyourownHLAprogram,youwillhavetochooseanappropriate
nameforyourproject.
IdentifiersinHLAareverysimilartoidentifiersinmosthighlevel
languages.HLAidentifiersmaybeginwithanunderscoreoran
alphabeticcharacter,andmaybefollowedbyzeroormorealphanumeric
orunderscorecharacters.HLA'sidentifiersarecaseneutral.Thismeans
thattheidentifiersarecasesensitiveinsofarasyoumustalwaysspellan
identifierexactlythesamewayinyourprogram(evenwithrespectto
upperandlowercase).However,unlikecasesensitivelanguageslike
C/C++,youmaynotdeclaretwoidentifiersintheprogramwhosename
differsonlybyalphabeticcase.
Atraditionalfirstprogrampeoplewrite,popularizedbyKernighanand
Ritchie'sTheCProgrammingLanguageistheHelloWorldprogram.This
programmakesanexcellentconcreteexampleforsomeonewhois
learninganewlanguage.Listing1-1presentstheHLAHelloWorld
program.
Listing1-1:TheHelloWorldProgram.
programhelloWorld;
#include("stdlib.hhf");
beginhelloWorld;
stdout.put("Hello,WorldofAssemblyLanguage",nl);
endhelloWorld;
The#includestatementinthisprogramtellstheHLAcompilerto
includeasetofdeclarationsfromthestdlib.hhf(StandardLibrary,HLA
headerfile).Amongotherthings,thisfilecontainsthedeclarationofthe
stdout.putcodethatthisprogramuses.
Thestdout.putstatementistheprintstatementfortheHLAlanguage.
Youuseittowritedatatothestandardoutputdevice(generallythe
console).ToanyonefamiliarwithI/Ostatementsinahighlevellanguage,
itshouldbeobviousthatthisstatementprintsthephrase"Hello,Worldof
AssemblyLanguage."Thenlappearingattheendofthisstatementisa
constant,alsodefinedinstdlib.hhf,thatcorrespondstothenewline
sequence.
Notethatsemicolonsfollowtheprogram,begin,stdout.put,and
endstatements.[1]Technicallyspeaking,asemicolondoesnotfollowthe
#includestatement.Itispossibletocreateincludefilesthatgenerate
anerrorifasemicolonfollowsthe#includestatement,soyoumay
wanttogetinthehabitofnotputtingasemicolonhere.
The#includeisyourfirstintroductiontoHLAdeclarations.The
#includeitselfisn'tactuallyadeclaration,butitdoestelltheHLA
compilertosubstitutethefilestdlib.hhfinplaceofthe#include
directive,thusinsertingseveraldeclarationsatthispointinyourprogram.
MostHLAprogramsyouwillwritewillneedtoincludeoneormoreofthe
HLAStandardLibraryheaderfiles(stdlib.hhfactuallyincludesallthe
StandardLibrarydefinitionsintoyourprogram).
Compilingthisprogramproducesaconsoleapplication.Runningthis
programinacommandwindowprintsthespecifiedstringandthen
controlreturnsbacktothecommandlineinterpreter(orshellinUNIX
terminology).
HLAisafree-formatlanguage.Therefore,youmaysplitstatements
acrossmultiplelinesifthishelpstomakeyourprogramsmorereadable.
Forexample,youcouldwritethestdout.putstatementintheHello
Worldprogramasfollows:
stdout.put
(
"Hello,WorldofAssemblyLanguage",
nl
);
Anotheritemyou'llseeappearinginsamplecodethroughoutthistextis
thatHLAautomaticallyconcatenatesanyadjacentstringconstantsit
findsinyoursourcefile.Therefore,thestatementaboveisalso
equivalentto:
stdout.put
(
"Hello,"
"WorldofAssemblyLanguage",
nl
);
Indeed,nl(thenewline)isreallynothingmorethanastringconstant,so
(technically)thecommabetweenthenlandtheprecedingstringisn't
necessary.You'lloftenseetheabovewrittenas:
stdout.put("Hello,WorldofAssemblyLanguage"nl);
Noticethelackofacommabetweenthestringconstantandnl;this
turnsouttobeperfectlylegalinHLA,thoughitonlyappliestocertain
constants;youmaynot,ingeneral,dropthecomma.Alaterchapterwill
explainindetailhowthisworks.Thisdiscussionappearsherebecause
you'llprobablyseethis"trick"employedbysamplecodepriortothe
formalexplanation.
[1]Technically,fromalanguagedesignpointofview,thesearenotall
statements.However,thischapterwillnotmakethatdistinction.
1.3RunningYourFirstHLAProgram
ThewholepurposeoftheHelloWorldprogramistoprovideasimple
examplebywhichsomewhoislearninganewprogramminglanguage
canfigureouthowtousethetoolsneededtocompileandrunprograms
inthatlanguage.True,theHelloWorldprogramintheprevioussection
helpsdemonstratetheformatandsyntaxofasimpleHLAprogram,but
therealpurposebehindaprogramlikeHelloWorldistolearnhowto
createandrunaprogramfrombeginningtoend.Althoughtheprevious
sectionpresentsthelayoutofanHLAprogram,itdidnotdiscusshowto
edit,compile,andrunthatprogram.Thissectionwillbrieflycoverthose
details.
AllofthesoftwareyouneedtocompileandrunHLAprogramscanbe
foundontheCD-ROMaccompanyingthisbook.Thesoftwarecanalso
befoundatthefollowingwebaddress:
(Notethatthelatestversionofthesoftwarecanalwaysbefoundon
Webster,soyoumightwanttovisitWebstertogetanyupdatesthatmay
haveappearedsincetheproductionoftheCD-ROM;note,however,that
allthesoftwareappearinginthistextworksjustfinewiththesoftware
appearingontheCD-ROM.)
ThissectionwillnotdescribehowtoinstallandsetuptheHLAsystem.
Thoseinstructionschangeovertimeandanyattempttodescribethe
installationofHLAonthesepageswouldbewastedbecausesuch
instructionswouldbecomeobsolete.The readme.txtfileintheroot
directoryoftheCD-ROMistheplacetogotolearnhowtoinstallHLAon
yoursystem.Fromthispointforward,thistextwillassumethatyou've
successfullyinstalledHLAandothernecessarytoolsonyoursystem
(thoseinstructionsalsoshowyouhowtocompileandrunyourfirst
program,sowe'llskipdetailsfromthatdiscussion,aswell).
Theprocessofcreating,compiling,andrunninganHLAprogramisvery
similartotheprocessyou'duseforaprogramwritteninanycomputer
language.Thefirststepistocreateoredityoursourcefileusingatext
editor.HLAisnotan"integrateddevelopmentsystem"(IDE)thatallows
youtoedit,compile,testanddebug,andrunyourapplicationallfrom
withinthesameprogram(likemanysoftwaredevelopmenttools).
Therefore,you'regoingtoneedatexteditorinordertocreateandedit
HLAprograms.
WindowsandLinuxbothprovideaplethoraoftexteditoroptions.You
canevenusethetexteditorprovidedwithotherlanguages'IDEsto
createandeditHLAprograms(e.g.,VisualC++,Borland'sDelphi,
Borland'sKylix,andsimilarpackages).TheonlyrestrictionisthatHLA
expectsASCIItextfiles,sotheeditoryouusemustbecapableof
manipulatingtextfiles.NotethatunderWindowsyoucanalwaysuse
notepad.exetocreateHLAprograms;underLinuxyoucanusejoe,vi,or
emacsifyoudon'tprefersomeothereditor.
TheHLAcompiler[2]isatraditionalcommandlinecompiler.Thismeans
thatyouneedtorunitfromaWindows'commandlinepromptoraLinux
shell.Todoso,you'dtypesomethinglikethefollowingintothecompile
linepromptorshellwindow:
hlahw.hla
ThiscommandtellsHLAtocompilethehw.hla(HelloWorld)programto
anexecutablefile.Assumingtherearenoerrors,youcanrunthe
resultingprogrambytypingthefollowingcommandintoyourcommand
promptwindow(Windows):
hw
orintotheshellinterpreterwindow(Linux):
./hw
Ifyou'rehavingproblemsgettingtheprogramtocompileandrun
properly,pleaseseetheHLAinstallationinstructionsintheHLA
ReferenceManualontheaccompanyingCD-ROM.Theseinstructions
describeingreatdetailhowtoinstall,setup,anduseHLA.
[2]Traditionally,programmershavealwayscalledtranslatorsforassembly
languagesassemblersratherthancompilers.However,becauseofHLA's
highlevelfeatures,itismorepropertocallHLAacompilerratherthanan
assembler.
1.4SomeBasicHLADataDeclarations
HLAprovidesawidevarietyofconstant,type,anddatadeclaration
statements.Laterchapterswillcoverthedeclarationsectioninmore
detail,butit'simportanttoknowhowtodeclareafewsimplevariablesin
anHLAprogram.
HLApredefinesseveraldifferentsignedintegertypesincludingint8,
int16,andint32,correspondingto8-bit(onebyte)signedintegers,16-bit
(twobyte)signedintegers,and32-bit(fourbyte)signedintegers,
respectively.[3]TypicalvariabledeclarationsoccurintheHLAstatic
variablesection.Atypicalsetofvariabledeclarationstakestheform
showninFigure1-2.
Figure1-2:StaticVariableDeclarations.
ThosewhoarefamiliarwiththePascallanguageshouldbecomfortable
withthisdeclarationsyntax.Thisexampledemonstrateshowtodeclare
threeseparateintegers,i8,i16,andi32.Ofcourse,inarealprogramyou
shouldusevariablenamesthatarealittlemoredescriptive.Whilenames
like"i8"and"i32"describethetypeoftheobject,theydonotdescribeits
purpose.Variablenamesshoulddescribethepurposeoftheobject.
Inthestaticdeclarationsection,youcanalsogiveavariableaninitial
valuethattheoperatingsystemwillassigntothevariablewhenitloads
theprogramintomemory.Figure1-3providesthesyntaxforthis.
Figure1-3:StaticVariableInitialization.
Itisimportanttorealizethattheexpressionfollowingtheassignment
operator(":=")mustbeaconstantexpression.Youcannotassignthe
valuesofothervariableswithinastaticvariabledeclaration.
Thosefamiliarwithotherhighlevellanguages(especiallyPascal)should
notethatyoumayonlydeclareonevariableperstatement.Thatis,HLA
doesnotallowacomma-delimitedlistofvariablenamesfollowedbya
colonandatypeidentifier.Eachvariabledeclarationconsistsofasingle
identifier,acolon,atypeID,andasemicolon.
Listing1-2providesasimpleHLAprogramthatdemonstratestheuseof
variableswithinanHLAprogram.
Listing1-2:VariableDeclarationandUse.
ProgramDemoVars;
#include("stdlib.hhf")
static
InitDemo:int32:=5;
NotInitialized:int32;
beginDemoVars;
//Displaythevalueofthepre-initializedvariable:
stdout.put("InitDemo'svalueis",InitDemo,nl);
//Inputanintegervaluefromtheuseranddisplaythatval
stdout.put("Enteranintegervalue:");
stdin.get(NotInitialized);
stdout.put("Youentered:",NotInitialized,nl);
endDemoVars;
Inadditiontostaticvariabledeclarations,thisexampleintroducesthree
newconcepts.First,thestdout.putstatementallowsmultiple
parameters.Ifyouspecifyanintegervalue,stdout.putwillconvert
thatvaluetoitsstringrepresentationonoutput.Thesecondnewfeature
Listing1-2introducesisthestdin.getstatement.Thisstatementreads
avaluefromthestandardinputdevice(usuallythekeyboard),converts
thevaluetoaninteger,andstorestheintegervalueintothe
NotInitializedvariable.Finally,thisprogramalsointroducesthe
syntaxfor(oneformof)HLAcomments.TheHLAcompilerignoresall
textfromthe"//"sequencetotheendofthecurrentline.Thosefamiliar
withJava,C++,andDelphi/Kylixshouldrecognizethesecomments.
[3]Adiscussionofbitsandbyteswillappearinthenextchapterifyouare
unfamiliarwiththeseterms.
1.5BooleanValues
HLAandtheHLAStandardLibraryprovideslimitedsupportforboolean
objects.Youcandeclarebooleanvariables,usebooleanliteralconstants,
usebooleanvariablesinbooleanexpressions,andprintthevaluesof
booleanvariables.
Booleanliteralconstantsconsistofthetwopredefinedidentifierstrueand
false.Internally,HLArepresentsthevaluetrueusingthenumericvalue
one;HLArepresentsfalseusingthevaluezero.Mostprogramstreatzero
asfalseandanythingelseastrue,soHLA'srepresentationsfortrueand
falseshouldprovesufficient.
Todeclareabooleanvariable,youusethebooleandatatype.HLAuses
asinglebyte(theleastamountofmemoryitcanallocate)torepresent
booleanvalues.Thefollowingexampledemonstratessometypical
declarations:
static
BoolVar:boolean;
HasClass:boolean:=false;
IsClear:boolean:=true;
Asthisexampledemonstrates,youcaninitializebooleanvariablesifyou
desire.
Becausebooleanvariablesarebyteobjects,youcanmanipulatethem
usinganyinstructionsthatoperatedirectlyoneight-bitvalues.
Furthermore,aslongasyouensurethatyourbooleanvariablesonly
containzeroandone(forfalseandtrue,respectively),youcanusethe
80x86and,or,xor,andnotinstructionstomanipulatethese
booleanvalues(we'lldescribetheseinstructionsalittlelaterinthistext).
Youcanprintbooleanvaluesbymakingacalltothestdout.put
routine,e.g.,
stdout.put(BoolVar)
Thisroutineprintsthetext"true"or"false"dependinguponthevalueof
thebooleanparameter(zeroisfalse;anythingelseistrue).Notethatthe
HLAStandardLibrarydoesnotallowyoutoreadbooleanvaluesvia
stdin.get.
1.6CharacterValues
HLAletsyoudeclareone-byteASCIIcharacterobjectsusingthechar
datatype.Youmayinitializecharactervariableswithaliteralcharacter
valuebysurroundingthecharacterwithapairofapostrophes.The
followingexampledemonstrateshowtodeclareandinitializecharacter
variablesinHLA:
static
c:char;
LetterA:char:='A';
Youcanprintcharactervariablesusethestdout.putroutine,andyou
canreadcharactervariablesusingthestdin.getprocedurecall.
1.7AnIntroductiontotheIntel80x86CPU
Family
Thusfar,you'veseenacoupleofHLAprogramsthatwillactuallycompile
andrun.However,allthestatementsappearinginprogramstothispoint
havebeeneitherdatadeclarationsorcallstoHLAStandardLibrary
routines.Therehasn'tbeenanyrealassemblylanguage.Beforewecan
progressanyfurtherandlearnsomerealassemblylanguage,adetouris
necessary;forunlessyouunderstandthebasicstructureoftheIntel
80x86CPUfamily,themachineinstructionswillmakelittlesense.
TheIntelCPUfamilyisgenerallyclassifiedasaVonNeumann
ArchitectureMachine.VonNeumanncomputersystemscontainthree
mainbuildingblocks:thecentralprocessingunit(CPU),memory,and
input/outputdevices(I/O).Thesethreecomponentsareconnected
togetherusingthesystembus(consistingoftheaddress,data,and
controlbusses).TheblockdiagraminFigure1-4showsthisrelationship.
Figure1-4:VonNeumannComputerSystemBlock
Diagram.
TheCPUcommunicateswithmemoryandI/Odevicesbyplacinga
numericvalueontheaddressbustoselectoneofthememorylocations
orI/Odeviceportlocations,eachofwhichhasauniquebinarynumeric
address.ThentheCPU,I/O,andmemorydevicepassdatabetween
themselvesbyplacingthedataonthedatabus.Thecontrolbuscontains
signalsthatdeterminethedirectionofthedatatransfer(to/frommemory,
andto/fromanI/Odevice).
WithintheCPUtheregistersisthemostprominentfeature.The80x86
CPUregisterscanbebrokendownintofourcategories:generalpurpose
registers,special-purposeapplicationaccessibleregisters,segment
registers,andspecialpurposekernelmoderegisters.Thistextwillnot
considerthelasttwosetsofregisters.Thesegmentregistersarenot
usedmuchinmodern32-bitoperatingsystems(e.g.,Windows,BeOS,
andLinux);becausethistextisgearedaroundprogramswrittenfor32-bit
operatingsystems,thereislittleneedtodiscussthesegmentregisters.
Thespecial-purposekernelmoderegistersareintendedforwriting
operatingsystems,debuggers,andothersystemleveltools.Such
softwareconstructioniswellbeyondthescopeofthistext,soonceagain
thereislittleneedtodiscussthespecialpurposekernelmoderegisters.
The80x86(Intelfamily)CPUsprovideseveralgeneralpurposeregisters
forapplicationuse.Theseincludeeight32-bitregistersthathavethe
following:
EAX,EBX,ECX,EDX,ESI,EDI,EBP,andESP
The"E"prefixoneachnamestandsforextended.Thisprefix
differentiatesthe32-bitregistersfromtheeight16-bitregistersthathave
thefollowingnames:
AX,BX,CX,DX,SI,DI,BP,andSP
Finally,the80x86CPUsprovideeight8-bitregistersthathavethe
followingnames:
AL,AH,BL,BH,CL,CH,DL,andDH
Unfortunately,thesearenotallseparateregisters.Thatis,the80x86
doesnotprovide24independentregisters.Instead,the80x86overlays
the32-bitregisterswiththe16-bitregisters,anditoverlaysthe16-bit
registerswiththe8-bitregisters.Figure1-5onthenextpageshowsthis
relationship.
Figure1-5:80x86(IntelCPU)GeneralPurpose
Registers.
Themostimportantthingtonoteaboutthegeneralpurposeregistersis
thattheyarenotindependent.Modifyingoneregistermaymodifyas
manyasthreeotherregisters.Forexample,modificationoftheEAX
registermayverywellmodifytheAL,AH,andAXregisters.Thisfact
cannotbeoveremphasizedhere.Averycommonmistakeinprograms
writtenbybeginningassemblylanguageprogrammersisregistervalue
corruptionbecausetheprogrammerdidnotfullyunderstandthe
ramificationsofFigure1-5.
TheEFLAGSregisterisa32-bitregisterthatencapsulatesseveral
single-bitboolean(true/false)values.MostofthebitsintheEFLAGS
registerareeitherreservedforkernelmode(operatingsystem)functions
orareoflittleinteresttotheapplicationprogrammer.Eightofthesebits
(orflags)areofinteresttoapplicationprogrammerswritingassembly
languageprograms.Thesearetheoverflow,direction,interrupt
disable[4],sign,zero,auxiliarycarry,parity,andcarryflags.Figure1-6
showsthelayoutoftheflagswithinthelower16bitsoftheEFLAGS
register.