Tải bản đầy đủ (.pdf) (838 trang)

Assembly language step by step programming with DOS and linux

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (4.28 MB, 838 trang )

AssemblyLanguageStepby-Step:Programming
withDOSandLinux,
SecondEdition
ISBN:0471375233
byJeff
Duntemann
JohnWiley&Sons©2000(613
pages)

A“LostWorld”journeyinto
16-bitassembler
programmingconceptsand
techniques.

TableofContents
AssemblyLanguageStep-by-Step—
ProgrammingwithDOSandLinux,
SecondEdition
Foreword
"WhyWouldYouWantto
Introduction DoThat?"
AnotherPleasantValley
SaturdayUnderstanding
Chapter1 WhatComputersReally
Do
AlienBasesGettingYour
Chapter2 - ArmsaroundBinaryand
Hexadecimal
LiftingtheHood



Chapter3

- DiscoveringWhat
ComputersActuallyAre
TheRighttoAssemble
TheProcessofMaking
Chapter4 AssemblyLanguage
Programs
NASM-IDE:APlaceto
StandGivemealever
Chapter5 - longenough,anda
placetostand,andIwill
movetheEarth.
AnUneasyAllianceThe
x86CPUandIts
Chapter6 SegmentedMemory
System
FollowingYour
InstructionsMeeting
Chapter7 MachineInstructionsup
CloseandPersonal
OurObjectAllSublime
Chapter8 - CreatingProgramsthat
Work
DividingandConquering
UsingProceduresand
Chapter9 MacrostoBattle
Complexity
Bits,Flags,Branches,
andTablesEasinginto

Chapter10 MainstreamAssembly
Programming
StringingThemUp
Chapter11 - ThoseAmazingString


Chapter12

Chapter13

Conclusion
AppendixA

AppendixB
AppendixC
AppendixD

Instructions
TheProgrammer'sView
ofLinuxToolsandSkills
- toHelpYouWrite
AssemblyCodeundera
True32-BitOS
CodingforLinux
ApplyingWhatYou've
- LearnedtoaTrue
ProtectedMode
OperatingSystem
NottheEnd,ButOnly
theBeginning

Partial8086/8088
- InstructionSet
Reference
SegmentRegister
- AssumptionsforReal
ModeSegmentedModel
WebURLsforAssembly
Programmers
SegmentRegister
Assumptions
- What'sontheCD-ROM?

AppendixE
Index
ListofFigures
ListofTables


BackCover
Thebestsellingguidetoassemblylanguage--now
updatedandexpandedtoincludecoverageofLinux.
Thisneweditionofthebestsellingguidetoassembly
programmingnowcoversDOSandLinux!TheSecond
Editionbeginswithahighlyaccessibleoverviewofthe
internaloperationsoftheIntel-basedPCand
systematicallycoversallthestepsinvolvedinwriting,
testing,anddebuggingassemblyprograms.
ExpertauthorJeffDuntemannthenpresentsworking
exampleprogramsforboththeDOSandLinux
operatingsystemsusingthepopularfreeassembler

NASM.Healsoinlcudesvaluableinfomationonhowto
useproceduresandmacros,plusrareexplanationsof
assembly-levelcodingforLinux,allofwhichcombine
toofferacomprehensivelookatthecomplexititesof
assemblyprogrammingforIntelprocessors.
Providingyouwiththefoundationtocreateexecutable
assemblylanguageprograms,thisbook:
ExplainshowtouseNASM-IDE,asimpleprogram
editorandassembly-orienteddevelopment
environment
Detailsthemostusedelementsofthe86-family
instructionset
TeachesaboutDEBUG,thesinglemostusefultool
youhaveasanassemblylanguageprogrammer
Examinestheoperationsthatmachineinstructions


forcetheCPUtoperform
Discussestheprocessofmemoryaddressing
CoverscodingforLinux
AbouttheAuthor
JeffDuntemannistheEditor-in-ChiefofVisual
Developermagazine,formereditorofTurboTechnix
andPCTechniques,the"StructuredProgramming"
columnistforDr.Dobb’sJournal,andhaswrittenand
editedmorethantwentyprogrammingbooks.


AssemblyLanguageStep-by-Step—
ProgrammingwithDOSandLinux,Second

Edition
JeffDuntemann

WileyComputerPublishing
JohnWiley&Sons,Inc.
NEWYORK•CHICHESTER•WEINHEIM•BRISBANE•SINGAPORE•
TORONTO
Publisher:RobertIpsen
Editor:CarySullivan
ManagingEditor:MichelineFrederick
TextDesign&Composition:NorthMarketStreetGraphics
Designationsusedbycompaniestodistinguishtheirproductsareoften
claimedastrademarks.InallinstanceswhereJohnWiley&Sons,Inc.,is
awareofaclaim,theproductnamesappearininitialcapitalorALL
CAPITALLETTERS.Readers,however,shouldcontacttheappropriate
companiesformorecompleteinformationregardingtrademarksand
registration.
Copyright©2000byJeffDuntemann.
Allrightsreserved.
PublishedbyJohnWiley&Sons,Inc.
PublishedsimultaneouslyinCanada.
Nopartofthispublicationmaybereproduced,storedinaretrieval
systemortransmittedinanyformorbyanymeans,electronic,


mechanical,photocopying,recording,scanningorotherwise,exceptas
permittedunderSections107or108ofthe1976UnitedStatesCopyright
Act,withouteitherthepriorwrittenpermissionofthePublisher,or
authorizationthroughpaymentoftheappropriateper-copyfeetothe
CopyrightClearanceCenter,222RosewoodDrive,Danvers,MA01923,

(978)750-8400,fax(978)750-4744.RequeststothePublisherfor
permissionshouldbeaddressedtothePermissionsDepartment,John
Wiley&Sons,Inc.,605ThirdAvenue,NewYork,NY10158-0012,(212)
850-6011,fax(212)850-6008,E-Mail:<PERMREQ@WILEY.COM>.
Thispublicationisdesignedtoprovideaccurateandauthoritative
informationinregardtothesubjectmattercovered.Itissoldwiththe
understandingthatthepublisherisnotengagedinprofessionalservices.
Ifprofessionaladviceorotherexpertassistanceisrequired,theservices
ofacompetentprofessionalpersonshouldbesought.
LibraryofCongressCataloging-in-PublicationData:
Duntemann,Jeff.
Assemblylanguagestep-by-step:programmingwithDOSandLinux/
JeffDuntemann.—2nded.
p.cm.
Rev.ed.of:Assemblylanguage,©1992.
ISBN0-471-37523-3(paper/CD-ROM:alk.paper)
1.Assemblerlanguage(Computerprogramlanguage)I.Duntemann,Jeff.
Assemblylanguage.II.Title.
QA76.73.A8D882000
005.265—dc2100-020611
10987654321
TotheeternalmemoryofKathleenM.Duntemann,Godmother
1920–1999whogavemebookswhenallIcoulddowasputteeth
marksonthem.TherearenowordsforhowmuchIoweyou!
Acknowledgments
Firstofall,totheauthorsofthesoftwarethatIamhonoredtoprovideby


theirpermissiononthisbook'sCD-ROM:
RobertAnderton,authorofNASM-IDE:

www.inglenook.co.uk/nasmide/
AnthonyWilliams,authorofALINK: />And,ofcourse,theNASMteam:Julian"Jules"Hall,Simon
Tatham,H.PeterAnvin,JohnFine,KendallBennet,GaryClark,
andAndrewCrabtree:www.web-sites.co.uk/nasm/
Becauseoftheirgenerosity,thereis"nothingelsetobuy."Everythingyou
needtoprograminassemblyisrighthereontheCD-ROMforthisbook.
AbundantthanksalsogotoBillSchindler,forteachingmethewaysof
theClibrary,andMichaelAbrash,whohasalwayshasbeentherock
uponwhommyknowledgeofassemblylanguageitselfhasbeen
anchored.
Finally,toCarol,asalways,forthesacramentalfriendshipthathas
challengedme,shapedme,andredeemedmeeverydayofour30years
togetherand23yearsasspouses.


Foreword
Timepasses.Itwasexactly10yearsagothissummer,backinJuly1989,
whenIturnedinthemanuscriptofabookcalledAssemblyLanguage
fromSquareOne.Thebookwaswellreceived,butitspublisherwent
belly-uponlyafewmonthsafteritsintroduction.Thatmayhavebeena
blessing,becausethebookwastooshort,hadafewmoreerrorsinit
thanitshouldhavehad,andwasprintedonhorriblecheappaperthat
rippedwithalmostnoprovocationandisnowturningsicklyyellow.
So,Ileaptonthechancetodothebookoverandpublishitwithareal
publisher,themostvenerableJohnWiley&Sons,who(astheirT-shirts
say)hasbeentotallyawesomesince1809.Itwasthoroughlyrewritten
andbecameanewbookwithanewtitle,andwentontheshelvesin
Septemberof1992.Timepasses,butinaworldwherethelifeofa
computerbookmaywellbeeightmonthsorless,Wileykeptthefirst
editionofAssemblyLanguageStep-by-Stepinprintforeightyears,from

1992to2000.
Inthattimeithasprobablysoldmorecopiesthananyothersingle
assemblylanguagebook,andI'vereceivedhundredsoflettersofadvice,
corrections,suggestions,andsimple,"Hey,thisiscool!"compliments.
Thankstoyouallfortakingthetimetowrite.Itmeansalottome.It's
unclearhowlongthissecondeditionwillremaininprint,butaslongas
peoplekeepbuyingit(andtellingmeit'sbeenusefultothem),Isuspect
thateitherthiseditionoronetofollowwillremainavailable.
Timepasses.Andbeforewegetintothebookproper,there'ssomething
elseIwantedtorelate.OnJuly8,1999,mysisterGretchenDuntemann
RoperfoundthatKathleenDuntemannhaddiedpeacefullyinhersleepin
Chicago,almost10yearstothedaysinceIhadcompletedAssembly
LanguagefromSquareOne,whichwasalsodedicatedtoher.Shekept
bothbooksonhercoffeetableandwouldshowthemtoanyonewho
cametovisit,eventhoughsheneverhadacomputerandprobablynever
understoodwhatassemblylanguagewas.Shewasmyauntand
godmother,myfather'ssolesibling,whosangmyABCstomeand
demandedthatIbeadmittedtoAdlerPlanetariuminChicagowhenIwas


six,eventhoughtherulesatthattimedemandedthatchildrenbeseven
toattendtheskyshow."Nametheplanetsfortheniceman,"shetoldme,
andIdid,andwhenIhadgonethroughalltheplanetsIstartedinonthe
constellations.Igotin,becauseshebelievedinme.Andshewasthere
througheveryothermajormilestoneinmylife:FirstCommunion,
Confirmation,wedding,myfather'sillnessanddeath,yearsandyearsof
ChristmasesandThanksgivingsandbirthdays,alwayswithtreatsforthe
dogandstoriestotell,withaquickIrishwitandagenerousheart-and
trulyIcannotandwillnoteverforgether.
IsaythisonlybecausesomanyofyouareconsiderablyyoungerthanI,

andmayforgetinthefeverofyounglife:Timepasses,andsodothe
peoplewhobelieveinus,andurgeusthroughthewallsaswehitthem
sothatwemayarriveatmidlifewithsomethingtoshowforit.Fathers
andmothers,grandparents,auntsandunclescanaddimmeasurablyto
ourlives,andoftendo,evenwhenwe'retoobusytonotice.Cherishthem
whileyouhavethem,becausecherishingthemafterthey'regoneisa
lonelybusinessindeed.
Inthemeantime,havingbeentalkingaboutassemblylanguageinone
bookoranotherfor10years,I'vedecidedtomakeit20.Aslongasthere
willbePCs,therewillbeassemblylanguage.Staytuned.Theyear2009
willbeherebeforeyouknowit.


Introduction:"WhyWouldYouWanttoDo
That?"
Itwas1985,andIwasinacharteredbusinNewYorkCity,headingfora
pressreceptionwithabunchofotherrestlessmediaegomaniacs.Iwas
onlybeginningmymediacareer(astechnicaleditorforPCTechJournal)
andmyfirstbookwasstillmonthsinthefuture.Ihappenedtobesitting
nexttoanestablishedprogrammingwriter/guru,withwhomIwas
impressedandtowhomIwasbabblingaboutonethingoranother.I
won'tnamehim,ashe'sdonealotforthefield,andwilldoalotmore
beforehe'sthroughifhedoesn'tkillhimselfsmokingfirst.
ButIhappenedtoletslipthatIwasaTurboPascalfanatic,andwhatI
reallywantedtodowaslearnhowtowriteTurboPascalprogramsthat
madeuseofthebrandnewMicrosoftWindowsuserinterface.He
wrinkledhisnoseandgrimacedwryly,beforespeakingtheInfamous
Question:
"Whywouldyouwanttodothat?"
Ihadneverheardthequestionbefore(thoughIwouldhearitmanytimes

thereafter),andittookmeaback.Why?Because,well,because…I
wantedtoknowhowitworked.
"Heh.That'swhatC'sfor."
FurtherdiscussiongotmenowhereinaPascaldirection.Butsome
probingledmetounderstandthatyoucouldn'twriteWindowsappsin
TurboPascal.Itwasimpossible.Or...theprogrammingwriter/gurudidn't
knowhow.Maybeboth.Ineverlearnedthetruth.ButIdidlearnthe
meaningoftheInfamousQuestion.
Notewell:Whensomebodyasksyou,"Whywouldyouwanttodothat?"
whatitreallymeansisthis:"You'veaskedmehowtodosomethingthat
iseitherimpossibleusingtoolsthatIfavororcompletelyoutsidemy
experience,butIdon'twanttolosefacebyadmittingit.So,...how'bout
thoseBlackhawks?"


Ihearditagainandagainovertheyears:
Q:HowcanIsetupaCstringsothatIcanreaditslengthwithout
scanningit?
A:Whywouldyouwanttodothat?
Q:HowcanIwriteanassemblylanguagesubroutinecallablefromTurbo
Pascal?
A:Whywouldyouwanttodothat?
Q:HowcanIwriteWindowsappsinassemblylanguage?
A:Whywouldyouwanttodothat?
Yougettheidea.TheanswertotheInfamousQuestionisalwaysthe
same,andiftheweaselseveraskitofyou,snapbackasquicklyas
possible:BecauseIwanttoknowhowitworks.
Thatisacompletelysufficientanswer.It'stheanswerI'veusedevery
singletime,exceptforoneoccasionaconsiderablenumberofyearsago,
whenIputforththatIwantedtowriteabookthattaughtpeoplehowto

programinassemblylanguageastheirfirstexperienceinprogramming.
Q:Goodgrief,whywouldyouwanttodothat?
A:Becauseit'sthebestwaythereistobuildtheskillsrequiredto
understandhowalltherestoftheprogramminguniverseworks.
Beingaprogrammerisonethingaboveallelse:Itisunderstandinghow
thingswork.Learningtobeaprogrammer,furthermore,isalmostentirely
aprocessoflearninghowthingswork.Thiscanbedoneatvarious
levels,dependingonthetoolsyou'reworkingwith.Ifyou'reprogramming
inVisualBasic,youhavetounderstandhowcertainthingswork,but
thosethingsarebyandlargeconfinedtoVisualBasicitself.Agreatdeal
ofmachineryishiddenbythelayerthatVisualBasicplacesbetweenthe
programmerandthecomputer.(ThesameistrueofDelphi,Java,Perl,
andmanyotherveryhigh-levelprogrammingenvironments.)Ifyou're
usingaCcompiler,you'realotclosertothemachine,andyouseealot


moreofthatmachinery-andmust,therefore,understandhowitworksto
beabletouseit.However,quiteabitremainshidden,evenfromthe
hardenedCprogrammer.(ManyCprogrammersfoolthemselvesinto
thinkingtheyknowwaymorethantheyactuallydo-andhavethebad
karmatobeprettydamnedarrogantaboutit.)
If,ontheotherhand,you'reworkinginassemblylanguage,you'reas
closetothemachineasyoucanget.Assemblylanguagehidesnothing,
andwithholdsnopower.Theflipside,ofcourse,isthatnomagicallayer
betweenyouandthemachinewillabsolveanyignoranceandtakecare
ofthingsforyou.Ifyoudon'tunderstandhowsomethingworks,you're
deadinthewater-unlessyouknowenoughtobeabletofigureitouton
yourown.
That'sakeypoint:Mygoalincreatingthisbookisnotentirelytoteach
youassemblylanguageperse.Ifthisbookhasaprimedirectiveatall,it

istoimpartacertaindisciplinedcuriosityaboutthemachine,alongwith
somebasiccontextfromwhichyoucanbegintoexplorethemachineat
itslowestlevels.That,andtheconfidencetogiveityourbestshot.Thisis
difficultstuff,butit'snothingyoucan'tmastergivensomeconcentration,
patience,andthetimeitrequires-which,Icaution,maybeconsiderable.
Intruth,whatI'mreallyteachingyouishowtolearn.


TheMasterPlan
YouneedanIntel-basedcomputer.ForalotofwhatI'llbeexplaining,
literallyanyIntel-basedmachinewilldo-rightbacktotheprimordial8088basedIBMPCfrom1981.However,tobeabletotryalltheexamples,
you'llneedatleasta386.Mostofthebookrelatesto16-bitDOS,which
comeswithWindows95and98,and(inaslightlylimitedform)is
emulatedbyWindowsNT.Towardtheendofthebook,Iexplainhowto
workwithassemblyunderLinux,andforthatyouwilldefinitelyneeda
386ormore-advancedIntelmachine.
Althoughmostpeoplethinkofmasteringassemblylanguageasthe
processoflearningacollectionofmachineinstructions,that'sactuallythe
easypart.Therealchallengeinassemblyislearningthemachine's
memorymodels-sothat'sactuallywhatI'llbeemphasizing.
TherearethreegeneralmemorymodelsfortheIntelprocessorfamily:
16-bitflatmodel(sometimescalledtheTinymodel,orjustthe"COMfile
model"),16-bitsegmentedmodel,and32-bitflatmodel.I'mspendinga
fairamountoftimeon16-bitflatmodel,becauseit'sverymuchlikethe
32-bitflatmodelinminiature.Thesegmentedmodelruledforagood
manyyears(includingthetimewhenIwrotethefirsteditionofthisbook),
butit'sactuallyacompromisethatlivedfarlongerthanitdeservedto.
WhateverfutureIntelcomputingmayhave,itwillhappeninaflatmemory
model.Youneedtoknowaboutsegments-butIhopeyou'llneveractually
havetousethem.

TheCD-ROMforthisbookcontainsanassembler:NASM,theNet-Wide
Assembler.It'sfree,it'seasytolearn,andfullsourcecodeisavailable,
freeofcharge,fromtheInternet.That'stheassemblerI'llbeteaching.If
youcanunderstandNASM,youcanpickupMicrosoft'sMASMwithout
trouble.NASMcangenerateprogramsforboth16-bitDOSand32-bit
Linux,soit'stheidealassemblerformetoteachinthisbook.Although
NASMisincludedontheCD-ROM,youmightchecktheNASMWebsite
toseeifanewerversionisavailable.(Thefirsteditionofthisbook
remainedinprintforeightyears.Youcouldbereadingthesewordsinthe


year2005orlater-bywhichtimemostofthesoftwareIspeakofwillbein
amuchmorehighlyevolvedstate.)TheWeblocationsofallthesoftware
mentionedorusedinthisbookaregiveninAppendixC.
InthefirsteditionofthisbookIpresentedasimpleeditor/environment
calledJED.JEDishistory,gonewithsomeBorlandcodelibrariesthat
werepulledfromthemarket.InitsplaceIpresentNASM-IDE,a
conceptuallysimilarutilitycreatedforNASMbyRobertAndertonofthe
UnitedKingdom.NASM-IDEoperatesonlyunderDOS.Itwon'thelpyou
withLinux.ButinLinuxthereareamultitudeofeditorsavailable,andin
theprocessoflearningLinuxyoucertainlylearnedoneofthem.
Whateveritis,useit.(Iuse,andwillrecommend,EMACS.)IfI'velearned
nothingelseaboutLinux,it'sthatpeoplegetveryattachedtotheirtext
editors.Iwon'taskyoutolearnanotherone.
Thewaytogetthemostfromthisbookistostartatthebeginningand
readitthrough,onechapteratatime,inorder.Evenifyourollyoureyes
andsayyoualreadyknowwhathexadecimalis,readitanyway.It'sa
goodreview-andyouwon'tmissanyofmyjokesandfunnystories.Load
andrunalltheexampleprograms.Tryyourbesttounderstandwhat
everysinglelineineveryprogramdoes.

Thatis,ultimately,whatI'mafter:toshowyouthewaytounderstand
whateveryhowever-distantcornerofyourmachineisdoing,andhowall
itsmanypiecesworktogether.Thisdoesn'tmeanI'llexplaineverycorner
ofitmyself-noonewilllivelongenoughtodothat;computingisn'tsimple
anymore-butifyoudevelopthedisciplineofpatientresearchand
experimentation,youcanprobablyworkitoutforyourself.Ultimately,
that'stheonlywaytolearnit:byyourself.Theguidanceyoufind-in
friends,ontheNet,inbookslikethis-isonlyguidance,andgreaseonthe
axles.Youhavetodecidewho'stobethemaster,youorthemachine,
andmakeitso.Assemblyprogrammersaretheonlyprogrammerswho
cantrulyclaimtobethemasters,andthat'satruthworthmeditatingon.
Ifitmeansanythingatall(optimistandthoroughgoingPelagianthatI
am),Ibelieveinyou.Goforit.
-JeffDuntemann


Scottsdale,Arizona
May2000


Chapter1:AnotherPleasantValleySaturday
UnderstandingWhatComputersReallyDo


It'sAllinthePlan
"Quick,getthekidsup,it'spast7.Nicky'sgotLittleLeagueat9and
Dione'sgotballetat10.Mike,giveMaxhisheartwormpill!(We'reoutof
them,Ma,remember?)Yourfatherpickedagreatweekendtogo
fishing…Here,letmegiveyou10bucksandgogetmorepillsatthe
vet's…MyGod,that'sright,Hankneededgasmoneyandleftmebroke.

There'satellermachineoverbyKmart,andifIgothereIcantakethat
stupidtoiletseatbackandgettherightone.
"IguessI'dbettermakealist…"
It'sanotherPleasantValleySaturday,andthirty-oddmillionsuburban
homemakerssitdownwithapencilandpadatthekitchentabletotryand
makesenseofamorningthatwouldkillandpickleanylesserbeing.In
hermindshethinksofthedependenciesandtracestheroute:
DropNickyatRandPark,gobacktoDempsterandit'sabout10minutes
toGolfMillMall.DoIhavegas?I'dbettercheckfirst-ifnot,stopatDel's
ShellorIwon'tmakeittoMilwaukeeAvenue.Milkthetellermachineat
GolfMill,thencrosstheparkinglottoKmarttoreturnthetoiletseatthat
Hankboughtlastweekendwithoutcheckingwhatshapeitwas.Gotta
remembertothrowthetoiletseatinbackofthevan-writethatatthetop
ofthelist.
Bythenit'llbehalfpast,maybelater.Balletisallthewaydown
GreenwoodinParkRidge.NoleftturnfromMilwaukee-butthere'sthe
sneakpatharoundbehindtheMall.Ihavetoremembernottoturnright
ontoMilwaukeelikeIalwaysdo-jotthatdown.WhileI'minParkRidgeI
cancheckandseeifHank'snewglassesarein-shouldcallbuttheywon't
evenbeopenuntil9:30.Oh,andgroceries-candothatwhileDione
dances.OnthewaybackIcancutovertoOaktonandgetthedog'spills.
Inabout90secondsflatthelistiscomplete:
Throwtoiletseatinvan.


Checkgas-ifempty,stopatDel'sShell.
DropNickyatRandPark.
StopatGolfMilltellermachine.
ReturntoiletseatatKmart.
DropDioneatballet(rememberbackpathtoGreenwood).

SeeifHank'sglassesareatPearleVision-iftheyare,make
doublesuretheyrememberedtheextrascratchcoating.
GetgroceriesatJewel.
PickupDione.
Stopatvet'sforheartwormpills.
Dropoffgroceriesathome.
Ifit'stime,pickupNicky.Ifnot,collapseforafewminutes,then
pickupNicky.
Collapse!
Inwhatweoftencalla"laundrylist"(whetheritinvolveslaundryornot)is
theperfectmetaphorforacomputerprogram.Withoutrealizingit,our
intrepidhomemakerhaswrittenherselfacomputerprogramandthenset
out(actingasthecomputer)toexecuteitandbedonebeforenoon.
Computerprogrammingisnothingmorethanthis:Youtheprogrammer
writealistofstepsandtests.Thecomputerthenperformseachstepand
testinsequence.Whenthelistofstepshasbeenexecuted,thecomputer
stops.
Acomputerprogramisalistofstepsandtests,nothingmore.

StepsandTests
ThinkforamomentaboutwhatIcalla"test"intheprecedinglaundrylist.


Atestisthesortofeither/ordecisionwemakedozensorhundredsof
timesoneventhemostplacidofdays,sometimesnearlywithoutthinking
aboutit.
Ourhomemakerperformedatestwhenshejumpedintothevantoget
startedonheradventure.Shelookedatthegasgauge.Thegasgauge
wouldtellheroneoftwothings:(1)Shehasenoughgas,or(2)no,she
doesn't.Ifshehasenoughgas,shetakesarightandheadsforRand

Park.Ifshedoesn'thaveenoughgas,shetakesaleftdowntothecorner
andfillsthetankatDel'sShell.(Deltakescreditcards.)Then,withafull
tank,shecontinuestheprogrambytakingaU-turnandheadingforRand
Park.
Intheabstract,atestconsistsofthosetwoparts:
First,youtakealookatsomethingthatcangooneoftwoways.
Thenyoudooneoftwothings,dependingonwhatyousawwhen
youtookalook.
Towardtheendoftheprogram,ourhomemakergothome,tookthe
groceriesoutofthevan,andtookalookattheclock.Ifitisn'ttimetoget
NickybackfromLittleLeague,shehasamomenttocollapseonthe
couchinanearlyemptyhouse.IfitistimetogetNicky,there'snorestfor
theragged:ShesprintsforthevanandheadsbacktoRandPark.
(Anyguessesastowhethershereallygetstocollapsewhentheprogram
iscomplete?)

MorethanTwoWays?
Youmightobject,sayingthatmanyormosttestsinvolvemorethantwo
alternatives.Ha-hah,sorry,you'redeadwrong-ineverycase.
Furthermore,you'rewrongwhetheryouthinkyouareornot.
Exceptfortotallyimpulsiveorpsychoticbehavior,everyhuman
decisioncomesdowntothechoicebetweentwoalternatives.
Whatyouhavetodoislookalittlemorecloselyatwhatgoesthrough


yourmindwhenyoumakedecisions.Thenexttimeyoubuzzdownto
MooFooGooforfastChinese,observeyourselfwhileyou'reporingover
themenu.Thechoicemightseem,atfirst,tobeofoneitemoutof26
Cantonesemaincourses.Notso-thechoice,infact,isbetweenchoosing
oneitemandnotchoosingthatoneitem.YoureyesrestonChickenwith

Cashews.Naw,toobland.Thatwasatest.Youslidedowntothenext
item.ChickenwithBlackMushrooms.Hmmm,no,hadthatlastweek.
Thatwasanothertest.Nextitem:KungPaoChicken.Yeah,that'sit!That
wasathirdtest.
Thechoicewasnotamongchickenwithcashews,chickenwithblack
mushrooms,orchickenwithkungpao.Eachdishhaditsmoment,poised
beforethecriticaleyeofyourmind,andyouturnedthumbsuporthumbs
downonit,individually.Eventually,onedishwon,butitwoninthatsame
gameof"toeatornottoeat."
Letmegiveyouanotherexample.Manyoflife'smostcomplicated
decisionscomeaboutduetothefactthat99.99867percentofusarenot
nudists.You'vebeenthere:You'restandingintheclothesclosetinyour
underwear,flippingthroughyourrackofpants.Thetestscomethickand
fast.Thisone?No.Thisone?No.Thisone?No.Thisone?Yeah.You
pickapairofbluepants,say.(It'saMonday,afterall,andbluewould
seemanappropriatecolor.)Thenyoustumbleovertoyoursockdrawer
andtakealook.Whoops,nobluesocks.Thatwasatest.Soyoustumble
backtotheclothescloset,hangyourbluepantsbackonthepantsrack,
andstartover.Thisone?No.Thisone?No.Thisone?Yeah.Thistime
it'sbrownpants,andyoutossthemoveryourarmandheadbacktothe
sockdrawertotakeanotherlook.Nertz,outofbrownsocks,too.Soit's
backtotheclothescloset…
Whatyoumightconsiderasingledecision,orperhapstwodecisions
inextricablytangled(likepickingpantsandsocksofthesamecolor,given
stockonhand),isactuallyaseriesofsmalldecisions,alwaysbinaryin
nature:Pick'emordon'tpick'em.Find'emordon'tfind'em.TheMonday
morningepisodeintheclothesclosetisagoodanalogyofa
programmingstructurecalledaloop:Youkeepdoingaseriesofthings
untilyougetitright,andthenyoustop.(Assumingyou'renotthekindof
nerdwhowearsbluesockswithbrownpants.)Butwhetheryouget



everythingrightalwayscomesdowntoasequenceofsimpleeither/or
decisions.

ComputersThinkLikeUs
Icanalmosthearwhatyou'rethinking:"Sure,it'sacomputerbook,and
he'stryingtogetmetothinklikeacomputer."Notatall.Computersthink
likeus.Wedesignedthem;howelsecouldtheythink?No,whatI'mtrying
todoisgetyoutotakealong,hardlookathowyouthink.Werunon
automaticforsomuchofourlivesthatweliterallydomostofourthinking
withoutreallythinkingaboutit.
Theverybestmodelforthelogicofacomputerprogramistheverysame
logicweusetoplanandmanageourdailyaffairs.Nomatterwhatwedo,
itcomesdowntoamatterofconfrontingtwoalternativesandpicking
one.Whatwemightthinkofasasinglelargeandcomplicateddecisionis
nothingmorethanamessytangleofmanysmallerdecisions.Theskillof
lookingatacomplexdecisionandseeingallthelittledecisionsinits
tummywillserveyouwellinlearninghowtoprogram.Observeyourself
thenexttimeyouhavetodecidesomething.Countupthelittledecisions
thatmakeupthebigone.You'llbesurprised.
And,surprise!You'llbeaprogrammer.


HadThisBeentheRealThing…
Donotbealarmed.Whatyouhavejustexperiencedwasametaphor.It
wasnottherealthing.(Therealthingcomeslater.)
Iusemetaphorsalotinthisbook.Ametaphorisaloosecomparison
drawnbetweensomethingfamiliar(suchasaSaturdaymorninglaundry
list)andsomethingunfamiliar(suchasacomputerprogram).Theideais

toanchortheunfamiliarinthetermsofthefamiliar,sothatwhenIbegin
tossingfactsatyou,you'llhavesomeplacecomfortabletolaythem
down.
Themostimportantthingforyoutodorightnowiskeepanopenmind.If
youknowalittlebitaboutcomputersorprogramming,don'tpicknits.
Yes,thereareimportantdifferencesbetweenahomemakerfollowinga
scribbledlaundrylistandacomputerexecutingaprogram.I'llmention
thosedifferencesallingoodtime.
Fornow,it'sstillChapter1.Taketheseinitialmetaphorsontheirown
terms.Lateron,they'llhelpalot.


DoNotPassGO
"There'sareasonboredandboardarehomonyms,"saidmybestfriend
Artoneevening,aswesat(twosuper-sophisticatedtwelve-year-olds)
playingsomegameinhisbasement.(Hemayhavebeenunhappy
becausehewaslosing.)WasitMilleBornes?OrStratego?Or
Monopoly?Orsomethingelseentirely?Iconfess,Idon'tremember.I
simplyrecallhoppingsomelittlepieceofplasticshapedlikeapregnant
bowlingpinupanddownaseriesofcoloredsquaresthattoldmetodo
dumbthingslikegobacktwospacesorput$100inthepotornukeOuter
Mongolia.
OuterMongolianotwithstanding,therearestrongparallelstobedrawn
betweenthatpeculiarAmericanobsession,theboardgame,and
assembly-languageprogramming.Firstofall,everythingwesaidbefore
stillholds:Boardgames,byandlarge,consistofaprogressionofsteps
andtests.Insomegames,suchasTrivialPursuit,everysteponthe
boardisatest:toseeifyoucananswer,ornotanswer,aquestionona
card.Inotherboardgames,eachlittlesquareontheboardcontains
somesortofinstruction:LoseOneTurn;GoBackTwoSquares;Takea

CardfromCommunityChest;and,ofcourse,GotoJail.
CertainboardgamesmadeforsomelivelyargumentsbetweenArtand
myself(itwasthatorbebored,asitwere)concerningwhatitmeantto
GoForwardorBackwardFiveSteps.Itseemedtomethatyoushould
countthesquareyouwerealreadyon,andArt,traditionalistalways,
thoughtyoushouldstartcountingwiththefirststepinthedirectionyou
hadtogo.Thismadeadifferenceinthegame,ofcourse.(Iconveniently
forgottopressmypointwhendoingsowouldlandmeonsomethinglike
ParkPlacewith15ofArt'shotelsonit…)

TheGameofBigBux
Toavoidgettinginserioustrouble,Ihaveinventedmyownboardgame
tocontinuedowntheroadwiththisparticularmetaphor.Inthesensethat
artmirrorslife,theGameofBigBuxmirrorslifeinSiliconValley,where


moneyseemstobespontaneouslycreated(generallyinsomebodyelse's
pocket)andthethreebigMoneyBlackHolesarefastcars,Californiareal
estate,andmessydivorces.
AportionoftheBigBuxGameBoardisshowninFigure1.1.Thelineof
rectanglesontheleftsideofthepagecontinuesallthewayaroundthe
board.Inthemiddleoftheboardarecubbyholestostoreyourplay
moneyandgamepieces;stacksofcardstobereadoccasionally;and
shortdetourswithsuchnamesasMessyDivorceandStartaBusiness,
whicharebriefsequencesofthesamesortofactionrectanglesasthose
formingthepatharoundtheedgeoftheboard.


Figure1.1:TheGameofBigBux.
Unlikemanyboardgames,youdon'tthrowdicetodeterminehowmany

stepsaroundtheboardyoutake.BigBuxrequiresthatyoumoveone
stepforwardoneachturn,unlessthesquareyoulandoninstructsyouto


×