ebook img

Introduction to Assembly Language Programming: For Pentium and RISC Processors PDF

702 Pages·2004·3.111 MB·
Save to my drive
Quick download
Download
Most books are stored in the elastic cloud where traffic is expensive. For this reason, we have a limit on daily download.

Preview Introduction to Assembly Language Programming: For Pentium and RISC Processors

TEXTS IN COMPUTER SCIENCE Editors David Gries Fred B. Schneider Sivarama P. Dandamudi Introduction to Assembly Language Programming For Pentium and RISC Processors With 75 Illustrations SivaramaP.Dandamudi SchoolofComputerScience CarletonUniversity 1125ColonelByDrive Ottawa,K1S5B6 Canada [email protected] SeriesEditors: DavidGries FredB.Schneider DepartmentofComputerScience CornellUniversity UpsonHall Ithaca,NY14853-7501 USA LibraryofCongressCataloging-in-PublicationData Dandamudi,SivaramaP.,1955– IntroductiontoAssemblylanguageprogramming:PentiumandRISCprocessors/ SivaramaP.Dandamudi.—2nded. p.cm.—(Textsincomputerscience) Includesbibliographicalreferencesandindex. ISBN0-387-20636-1(alk.paper) 1. Assemblerlanguage(Computerprogramlanguage) 2. Microprocessors—Programming. I.Title. II. Series. QA76.73.A87D36 2004 005.13′6—dc22 2004049182 ISBN0-387-20636-1 Printedonacid-freepaper. PentiumisaregisteredtrademarkofIntelCorporation. 2005,1998SpringerScience+BusinessMedia,Inc. Allrightsreserved.Thisworkmaynotbetranslatedorcopiedinwholeorinpartwithoutthewrittenpermissionofthe publisher (Springer Science+Business Media, Inc., 233 Spring Street, New York, NY 10013, USA), except for brief excerptsinconnectionwithreviewsorscholarlyanalysis.Use inconnectionwithanyformofinformationstorageand retrieval, electronic adaptation, computer software, or by similar or dissimilar methodology now known or hereafter developedisforbidden. Theuseinthispublicationoftradenames,trademarks,servicemarks,andsimilarterms,eveniftheyarenotidentified assuch,isnottobetakenasanexpressionofopinionastowhetherornottheyaresubjecttoproprietaryrights. PrintedintheUnitedStatesofAmerica. (HAM) 9 8 7 6 5 4 3 2 1 SPIN10949580 springeronline.com To myparents,Subba Rao and PrameelaRani, mywife,Sobha, and mydaughter,Veda Preface The objectiveof this bookis to introduceassembly languageprogramming. Assembly lan- guage is very closely linked to the underlying processor architecture and design. Popular processordesignscanbebroadlydividedintotwocategories:ComplexInstructionSetCom- puters (CISC) and Reduced Instruction Set Computers (RISC). The dominant processor in thePCmarket,Pentium,belongstotheCISCcategory.However,therecentdesigntrendisto usetheRISCdesigns. SomeexampleRISCprocessorsincludetheMIPS,SPARC,PowerPC, and ARM. Even Intel’s 64-bit processor Itanium is a RISC processor. Thus, both types of processorsareimportantcandidatesforourstudy. This book coversassembly language programmingof both CISC and RISC processors. We use the Intel Pentium processor as the representative of the CISC category. We have selectedthePentiumprocessorbecauseofitsmarketdominance. ToexploreRISCassembly language, we selected the MIPS processor. The MIPS processor is appealing as it closely adherestotheRISCprinciples.Furthermore,theavailabilityoftheSPIMsimulatorallowsus touseaPentium-basedPCtolearnMIPSassemblylanguage. New in the Second Edition Thesecondeditionhasbeensubstantiallyrevisedtoreflectthechangesthathavetakenplace sincethepublicationofthefirstedition.Themajorchangesarelistedbelow: • We introduced RISC assembly language programming so that the reader can benefit fromlearningbothCISCandRISCassemblylanguages.Asmentionedbefore,Pentium andMIPSprocessorsareusedtocoverCISCandRISCprocessors. vii viii Preface • The first edition used MASM/TASM assemblers. In this edition, we use the NASM assembler. The syntax of NASM is slightly differentfrom that of MASM/TASM as- semblers.TheadvantageisthatNASMisfree!Anotheradvantageisthatitworkswith bothMicrosoftWindowsandLinuxoperatingsystems. • ConsistentwithourshifttoNASM,wemovedawayfromDOStoLinux.SinceNASM is available for Windows and Linux, most of the programs in this book can be used witheitherWindowsorLinux. However,weclearlyindicateourpreferencetoLinux. Thispreferenceisexposedinchapterslike“High-LevelLanguageInterface”thatdeal withmixed-modeprogramminginvolvingCandassemblylanguage. Forexample,in Chapter 17, we use the GNU C compiler (gcc) ratherthan the Microsoftor Borland Ccompiler. Similarly,inAppendixCweusetheGNUdebugger(gdb)toexplorethe debuggingprocess. • The“BasicComputerOrganization”chapter(Chapter2)hasbeencompletelyrewritten togiveageneralbackgroundoncomputerorganization.ThePentiumprocessordetails aremovedtoanewchapter(Chapter4). • AcompletelynewchapterhasbeenaddedtodiscussPentium’sprotectedmodeinter- ruptprocessing. • Wehaveaddedanewchapteronrecursion. Thischapterdiscusseshowwecanimple- mentrecursiveproceduresinthePentiumandMIPSassemblylanguages. • We have augmented the Pentium assembly language programming by describing its floating-pointinstructions.Thisentirechapterisnewinthisedition. Inadditiontothesemajorchanges,allchaptershavegonethroughextensiverevision. Some chaptershavebeenreorganizedtoeliminatetheduplicationpresentinthefirstedition. Intended Use Assemblylanguageprogrammingispartofseveralundergraduatecurriculaincomputersci- ence,computerengineering,andelectricalengineeringdepartments. Thisbookcanbeused asatextforthosecoursesthatteachassemblylanguage. It can also be used as a companiontext in a computer organizationcourse for teaching theassemblylanguage.BecausewecoverbothCISCandRISCprocessors,theinstructorcan selecttheassemblylanguagethatbestfitsherorhiscourse. Inaddition,itcanbeusedasatextinvocationaltrainingcoursesofferedbycommunity colleges. Becauseoftheteach-by-examplestyleusedinthebook,itisalsosuitableforself- studybycomputerprofessionalsandengineers. Instructional Support Thebook’sWebsite(www.scs.carleton.ca/˜sivarama/asm_book)hascomplete chapter-by-chapterPowerPointslidesforinstructors. Instructorscanusetheseslidesdirectly Preface ix in their classes or can modify them to suit their needs. In addition, instructors can obtain thesolutionsmanualbycontactingthepublisher. Formoreup-to-datedetails,pleaseseethe book’sWebsite. Prerequisites Thestudentisassumedtohavehadsomeexperienceinastructured,high-levellanguagesuch asC.However,thebookdoesnotassumeextensiveknowledgeofanyhigh-levellanguage— only the basics are needed. Furthermore, it is assumed that the student has a rudimentary backgroundinthesoftwaredevelopmentcycle,asisobtainedinatypicalhigh-levelprogram- mingcourse. Features Hereisasummaryofthespecialfeaturesthatsetsthisbookapart: • Thisis probablythe only bookto coverthe assembly languageprogrammingof both CISCandRISCprocessors. • ThisbookusesNASMandLinuxasopposedtoscoresofotherbooksthatuseMASM andWindows. • Thebookisself-containedanddoesnotassumeabackgroundincomputerorganization. Allnecessarybackgroundmaterialoncomputerorganizationispresentedinthebook. • Thisbookcontainsamethodicalorganizationofchaptersforastep-by-stepintroduction totheassemblylanguage. • Extensive examples are used in each chapter to illustrate the points discussed in the chapter.Ourobjectiveisnotjusttoexplainhowaninstructionworksbutalsotoprovide therationaleastowhytheinstructionhasbeendesignedthewayitis. • Proceduresareintroducedearlyontoencouragemodularprogrammingindeveloping assemblylanguageprograms. • Asetofinputandoutputroutinesisprovidedsothatthestudentcanfocusondeveloping assemblylanguageprogramsratherthanspendingtimeinunderstandinghowtheinput andoutputaredoneusingthebasicI/Ofunctionsprovidedbytheoperatingsystem. • Thisbookdoesnotusefragmentsofcodeinexamples. Allexamplesarecompletein the sense that they can be assembled and run, giving a better feeling as to how these programswork. • Allexamplesandotherrequiredsoftwareareavailablefromthebook’sWebsite(www. scs.carleton.ca/˜sivarama/asm_book)to give opportunities for students toperformhands-onassemblyprogramming. • Most chapters are written in such a way that each chapter can be covered in two or three 60-minute lectures by giving proper reading assignments. Typically, important x Preface conceptsare emphasizedin the lectures while leaving the other materialas a reading assignment.Ouremphasisonextensiveexamplesfacilitatesthispedagogicalapproach. • Interchapterdependenciesare kept to a minimum to offer maximum flexibility to in- structorsin organizingthe material. Eachchapterclearly indicatesthe objectivesand providesanoverviewatthebeginningandasummaryattheend. • Eachchaptercontainstwotypesofexercises—reviewandprogramming—toreinforce theconceptsdiscussedinthechapter. • The appendicesprovidespecial referencematerial that contains a thoroughtreatment ofvarioustopics. Overview and Organization The18chaptersinthebookaredividedinto6parts(seethefigureonthenextpageforchap- ter dependencies). Part I presents introductorytopicsand consists of the first two chapters. Chapter1providesintroductiontotheassemblylanguageandgivesreasonsforprogramming intheassemblylanguage.Chapter2presentsthebasicsofcomputerorganizationwithafocus onthreesystemcomponents:processor,memory,andI/O. Part II is dedicated to Pentium assembly language programming. It consists of nine chapters—Chapters 3 through 11. This part begins with a description of the Pentium pro- cessororganization(Chapter3). Inparticular,thischaptergivessufficientdetailsonthe16- and 32-bitIntel processorsso that the student can effectivelyprogramin the assembly lan- guage. Chapter 4 gives an overview of the assembly language. After covering these two chapters,onecanwritesimplestandaloneassemblylanguageprograms. Toemphasizetheimportanceofmodularprogramming,proceduresareintroducedearly on(inChapter5). TheotherchaptersinthispartexpandontheoverviewgiveninChapter4. Chapter 6 presents the addressing modes supported by the Intel 16- and 32-bit processors. This chapteralso containsa detailed discussionon the motivationfor providingthe various addressingmodes. Addressingmodesare one of the differentiatingcharacteristicsof CISC processors. Chapter 7 discusses the arithmeticinstructionsand the use of the flagsregister. Chapters 8 and 9 present conditional and bit manipulation instructions. A feature of these twochaptersisthattheyrelatehowhigh-levellanguagestatementscanbeimplementedusing the instructionsdiscussed in these two chapters. Chapter 10 discussesthe string processing instructionsindetail. ASCIIandBCDarithmeticinstructionsarepresentedinChapter11. Thefirstfourchaptersofthispart—Chapters3to6—shouldbecoveredinsomedetailfor propergroundinginassemblylanguageprogramming. However,theremainingfivechapters can be studied in any order. In addition, the depth at which these five chaptersare covered canbe variedwithoutsacrificingthe effectiveness,dependingonthe time availableandim- portancetothecourseobjective. PartIIIisdedicatedtotheMIPSassemblylanguageprogramming. Chapter12describes theRISCdesignprinciples;italsocoversMIPSprocessordetails. TheMIPSassemblylan- guageispresentedinChapter13. ThischapteralsogivesdetailsontheSPIMsimulator. All Preface xi Chapter 1 Chapter 2 Chapter 3 Chapter 12 Chapter 4 Chapter 13 Chapter 5 Chapter 6 Chapter 16 Chapter 7 Chapter 9 Chapter 11 Chapter 14 Chapter 17 Chapter 8 Chapter 10 Chapter 15 Chapter 18 theprogrammingexamplesgiveninthischaptercanberunonaPentium-basedPCusingthe SPIMsimulator.TheSPIMsimulatordetailsaregiveninAppendixD. PartIVfocusesonPentium’sinterruptprocessingmechanism. Wecoverbothprotected- modeandreal-modeinterruptprocessing. Chapter14givesdetailsonprotected-modeinter- ruptprocessing. ThischapterusesLinuxsystemcallstofacilitateourdiscussionofsoftware interrupts. The next chapter discusses the real-mode interrupt processing. This is the only chapterthatusesDOStoexplorehowprogrammedI/Oandinterrupt-drivenI/Oaredone. Theremaining3ofthe18chaptersconstitutePartV.Thesechaptersdealwithadvanced topics. Chapter 16 focuses on how recursive procedures are implemented in Pentium and MIPS assembly languages. The next chapter deals with the high-level language interface, whichallowsmixed-modeprogramming.WeuseCandassemblylanguagetocovertheprin- ciplesinvolvedinmixed-modeprogramming. ThelastchapterdiscussesPentium’sfloating- pointinstructions. Tofollowtheprogrammingexamplesofthischapter,youneedtounder- standthehigh-levellanguageinterfacedetailspresentedinChapter17. The seven appendices provide a wealth of reference material the student needs. Ap- pendix A primarily discusses the number systems and their internal representation. Ap- pendix B gives information on the use of I/O routines provided with this book and the as-

See more

The list of books you might like

Most books are stored in the elastic cloud where traffic is expensive. For this reason, we have a limit on daily download.