爱问 爱问共享资料 爱问分类
首页 > > > professional assembly language.pdf

professional assembly language.pdf

professional assembly language.…

上传者: 我是谁是我
47次下载 0人收藏 暂无简介 简介 2012-05-14 举报

简介:关于汇编语言的书

ProfessionalAssemblyLanguageRichardBlum01_579010ffirs.qxd1/7/0510:19AMPageiii01_579010ffirs.qxd1/7/0510:19AMPageiiProfessionalAssemblyLanguage01_579010ffirs.qxd1/7/0510:19AMPagei01_579010ffirs.qxd1/7/0510:19AMPageiiProfessionalAssemblyLanguageRichardBlum01_579010ffirs.qxd1/7/0510:19AMPageiiiProfessionalAssemblyLanguagePublishedbyWileyPublishing,Inc.10475CrosspointBoulevardIndianapolis,IN46256www.wiley.comCopyright2005byWileyPublishing,Inc.,Indianapolis,Indiana.Allrightsreserved.PublishedsimultaneouslyinCanadaISBN:0-7645-7901-0ManufacturedintheUnitedStatesofAmerica109876543211MA/SW/QR/QV/INNopartofthispublicationmaybereproduced,storedinaretrievalsystemortransmittedinanyformorbyanymeans,electronic,mechanical,photocopying,recording,scanningorotherwise,exceptaspermittedunderSections107or108ofthe1976UnitedStatesCopyrightAct,withouteitherthepriorwrittenpermis-sionofthePublisher,orauthorizationthroughpaymentoftheappropriateper-copyfeetotheCopyrightClearanceCenter,222RosewoodDrive,Danvers,MA01923,(978)750-8400,fax(978)646-8600.RequeststothePublisherforpermissionshouldbeaddressedtotheLegalDepartment,WileyPublishing,Inc.,10475CrosspointBlvd.,Indianapolis,IN46256,(317)572-3447,fax(317)572-4355,e-mail:brandreview@wiley.com.LIMITOFLIABILITY/DISCLAIMEROFWARRANTY:THEPUBLISHERANDTHEAUTHORMAKENOREPRESENTATIONSORWARRANTIESWITHRESPECTTOTHEACCURACYORCOMPLETENESSOFTHECONTENTSOFTHISWORKANDSPECIFICALLYDISCLAIMALLWARRANTIES,INCLUDINGWITHOUTLIMITATIONWARRANTIESOFFITNESSFORAPARTICULARPURPOSE.NOWARRANTYMAYBECREATEDOREXTENDEDBYSALESORPROMOTIONALMATERIALS.THEADVICEANDSTRATEGIESCONTAINEDHEREINMAYNOTBESUITABLEFOREVERYSITUATION.THISWORKISSOLDWITHTHEUNDERSTANDINGTHATTHEPUBLISHERISNOTENGAGEDINRENDERINGLEGAL,ACCOUNTING,OROTHERPROFESSIONALSERVICES.IFPROFESSIONALASSISTANCEISREQUIRED,THESERVICESOFACOMPETENTPROFESSIONALPERSONSHOULDBESOUGHT.NEITHERTHEPUBLISHERNORTHEAUTHORSHALLBELIABLEFORDAMAGESARISINGHERE-FROM.THEFACTTHATANORGANIZATIONORWEBSITEISREFERREDTOINTHISWORKASACITATIONAND/ORAPOTENTIALSOURCEOFFURTHERINFORMATIONDOESNOTMEANTHATTHEAUTHORORTHEPUBLISHERENDORSESTHEINFORMATIONTHEORGANIZATIONORWEBSITEMAYPROVIDEORRECOMMENDATIONSITMAYMAKE.FURTHER,READERSSHOULDBEAWARETHATINTERNETWEBSITESLISTEDINTHISWORKMAYHAVECHANGEDORDISAP-PEAREDBETWEENWHENTHISWORKWASWRITTENANDWHENITISREAD.Forgeneralinformationonourotherproductsandservicesortoobtaintechnicalsupport,pleasecontactourCustomerCareDepartmentwithintheU.S.at(800)762-2974,outsidetheU.S.at(317)572-3993orfax(317)572-4002.Wileyalsopublishesitsbooksinavarietyofelectronicformats.Somecontentthatappearsinprintmaynotbeavailableinelectronicbooks.Blum,Richard.1962-Professionalassemblylanguage/RichardBlum.p.cm.Includesindex.ISBN0-7645-7901-0(paper/website)1.Assemblylanguage(Computerprogramlanguage)1.Title.QA76.73.A8B582005005.13'6—dc222004029116Trademarks:Wiley,theWileyPublishinglogo,Wrox,theWroxlogo,ProgrammertoProgrammerandrelatedtradedressaretrademarksorregisteredtrademarksofJohnWiley&Sons,Inc.and/oritsaffiliates,intheUnitedStatesandothercountries,andmaynotbeusedwithoutwrittenpermission.Allothertrademarksarethepropertyoftheirrespectiveowners.WileyPublishing,Inc.,isnotassociatedwithanyproductorvendormentionedinthisbook.01_579010ffirs.qxd1/7/0510:19AMPageivAbouttheAuthorRichardBlumhasworkedforalargeU.S.governmentorganizationformorethan15years.Duringthattime,hehashadtheopportunitytoprogramutilitiesinvariousprogramminglanguages:C,C++,Java,andMicrosoftVB.NETandC#.Withthisexperience,Richhasoftenfoundthebenefitofreviewingassemblylanguagecodegeneratedbycompilersandutilizingassemblylanguageroutinestospeeduphigher-levellanguageprograms.RichhasabachelorofsciencedegreeinelectricalengineeringfromPurdueUniversity,whereheworkedonmanyassemblylanguageprojects.(Ofcourse,thiswasbackintheeight-bitprocessordays.)HealsohasamasterofsciencedegreeinmanagementfromPurdueUniversity,specializinginManagementInformationSystems.WhenRichisnotbeingacomputernerd,heiseitherplayingelectricbassforthechurchworshipbandorspendingtimewithhiswife,Barbara,andtwodaughters,KatieJaneandJessica.01_579010ffirs.qxd1/7/0510:19AMPagev01_579010ffirs.qxd1/7/0510:19AMPageviCreditsExecutiveEditorChrisWebbDevelopmentEditorAdaobiObiTultonProductionEditorWilliamA.BartonTechnicalEditorPaulCarterCopyEditorLuannRouffEditorialManagerKathrynMalmBourgoineVicePresident&ExecutiveGroupPublisherRichardSwadleyVicePresidentandPublisherJosephB.WikertProjectCoordinatorErinSmithGraphicsandProductionSpecialistsJonelleBurnsAmandaCarterCarrieA.FosterLaurenGoddardDennyHagerJoyceHaugheyQualityControlTechniciansDavidFaustSusanMoritzCarlWilliamPierceMediaDevelopmentSpecialistAngieDennyProofreadingTECHBOOKSProductionServicesIndexingRichardT.Evans01_579010ffirs.qxd1/7/0510:19AMPagevii01_579010ffirs.qxd1/7/0510:19AMPageviiiThisbookisdedicatedtomywife,Barbara,andmydaughters,KatieJaneandJessica.“TrustintheLordwithallyourheartandleannotonyourownunderstanding;inallwaysacknowledgehim,andhewillmakeyourpathsstraight.”Pr3:5-6(NIV)01_579010ffirs.qxd1/7/0510:19AMPageix01_579010ffirs.qxd1/7/0510:19AMPagexAcknowledgmentsFirst,allhonor,glory,andpraisegotoGod,whothroughHisSonmakesallthingspossibleandgivesusthegiftofeternallife.ManythanksgotothegreatteamofpeopleatJohnWiley&SonsPublishing.ThankstoChrisWebb,theacquisitionseditor,forofferingmetheopportunitytowritethisbook.IamforeverindebtedtoAdaobiObiTulton,thedevelopmenteditor,forherworkinmakingthisbookpresentableandheroverallguid-ancethroughthebookwritingprocess.Also,manythanksgotoPaulCarter,thetechnicaleditorofthebook.Paul’scommentsthroughoutthebookwereinvaluableinpresentingthetopicinthebestwayandforpointingoutmygoofsandblunders.IwouldalsoliketothankCaroleMcClendonatWatersideProductions,Inc.,forarrangingthisopportunityforme,andforhelpingoutinmywritingcareer.Finally,Iwouldliketothankmyparents,MikeandJoyceBlum,fortheirdedicationandsupportwhileraisingme,andtomywife,Barbara,anddaughters,KatieJaneandJessica,fortheirlove,patience,andunderstanding,especiallywhileIwaswritingthisbook.01_579010ffirs.qxd1/7/0510:19AMPagexi01_579010ffirs.qxd1/7/0510:19AMPagexiiContentsAcknowledgmentsxiContentsxiiiIntroductionxxiiiChapter1:WhatIsAssemblyLanguage?1ProcessorInstructions1Instructioncodehandling2Instructioncodeformat3High-LevelLanguages6Typesofhigh-levellanguages7High-levellanguagefeatures9AssemblyLanguage10Opcodemnemonics11Definingdata12Directives14Summary15Chapter2:TheIA-32Platform17CorePartsofanIA-32Processor17Controlunit19Executionunit24Registers25Flags29AdvancedIA-32Features32Thex87floating-pointunit32Multimediaextensions(MMX)33StreamingSIMDextensions(SSE)33Hyperthreading34TheIA-32ProcessorFamily34Intelprocessors35Non-Intelprocessors36Summary3702_579010ftoc.qxd1/7/0510:37AMPagexiiixivContentsChapter3:TheToolsoftheTrade39TheDevelopmentTools39TheAssembler40TheLinker42TheDebugger43TheCompiler44Theobjectcodedisassembler44TheProfiler44TheGNUAssembler45Installingtheassembler45Usingtheassembler47Awordaboutopcodesyntax49TheGNULinker50TheGNUCompiler53Downloadingandinstallinggcc53Usinggcc54TheGNUDebuggerProgram56Downloadingandinstallinggdb56Usinggdb57TheKDEDebugger60Downloadingandinstallingkdbg60Usingkdbg60TheGNUObjdumpProgram62Usingobjdump63Anobjdumpexample64TheGNUProfilerProgram65Usingtheprofiler65Aprofileexample68ACompleteAssemblyDevelopmentSystem69ThebasicsofLinux69DownloadingandrunningMEPIS70Yournewdevelopmentsystem71Summary72Chapter4:ASampleAssemblyLanguageProgram73ThePartsofaProgram73Definingsections74Definingthestartingpoint74CreatingaSimpleProgram75TheCPUIDinstruction76Thesampleprogram7702_579010ftoc.qxd1/7/0510:37AMPagexivxvContentsBuildingtheexecutable80Runningtheexecutable80Assemblingusingacompiler80DebuggingtheProgram81Usinggdb81UsingCLibraryFunctionsinAssembly86Usingprintf87LinkingwithClibraryfunctions88Summary90Chapter5:MovingData91DefiningDataElements91Thedatasection91Definingstaticsymbols94Thebsssection95MovingDataElements97TheMOVinstructionformats97Movingimmediatedatatoregistersandmemory98Movingdatabetweenregisters99Movingdatabetweenmemoryandregisters99ConditionalMoveInstructions106TheCMOVinstructions107UsingCMOVinstructions109ExchangingData110Thedataexchangeinstructions111Usingthedataexchangeinstruction116TheStack119Howthestackworks119PUSHingandPOPingdata120PUSHingandPOPingalltheregisters123ManuallyusingtheESPandEBPregisters123OptimizingMemoryAccess123Summary124Chapter6:ControllingExecutionFlow127TheInstructionPointer127UnconditionalBranches129Jumps129Calls132Interrupts13502_579010ftoc.qxd1/7/0510:37AMPagexvxviContentsConditionalBranches136Conditionaljumpinstructions136Thecompareinstruction138Examplesofusingtheflagbits140Loops144Theloopinstructions144Aloopexample145PreventingLOOPcatastrophes145DuplicatingHigh-LevelConditionalBranches146ifstatements147forloops150OptimizingBranchInstructions153Branchprediction153Optimizingtips155Summary158Chapter7:UsingNumbers161NumericDataTypes161Integers162Standardintegersizes162Unsignedintegers164Signedintegers166Usingsignedintegers168Extendingintegers169DefiningintegersinGAS172SIMDIntegers173MMXintegers173MovingMMXintegers174SSEintegers176MovingSSEintegers177BinaryCodedDecimal178WhatisBCD?178FPUBCDvalues179MovingBCDvalues180Floating-PointNumbers182Whatarefloating-pointnumbers?182Standardfloating-pointdatatypes184IA-32floating-pointvalues186Definingfloating-pointvaluesinGAS187Movingfloating-pointvalues187Usingpresetfloating-pointvalues18902_579010ftoc.qxd1/7/0510:37AMPagexvixviiContentsSSEfloating-pointdatatypes190MovingSSEfloating-pointvalues191Conversions196Conversioninstructions196Aconversionexample198Summary199Chapter8:BasicMathFunctions201IntegerArithmetic201Addition201Subtraction210Incrementinganddecrementing215Multiplication216Division221ShiftInstructions223Multiplybyshifting224Dividingbyshifting225Rotatingbits226DecimalArithmetic227UnpackedBCDarithmetic227PackedBCDarithmetic229LogicalOperations231Booleanlogic231Bittesting232Summary233Chapter9:AdvancedMathFunctions235TheFPUEnvironment235TheFPUregisterstack236TheFPUstatus,control,andtagregisters237UsingtheFPUstack242BasicFloating-PointMath245AdvancedFloating-PointMath249Floating-pointfunctions249Partialremainders252Trigonometricfunctions254Logarithmicfunctions257Floating-PointConditionalBranches259TheFCOMinstructionfamily260TheFCOMIinstructionfamily262TheFCMOVinstructionfamily26302_579010ftoc.qxd1/7/0510:37AMPagexviixviiiContentsSavingandRestoringtheFPUState265SavingandrestoringtheFPUenvironment265SavingandrestoringtheFPUstate266WaitingversusNonwaitingInstructions269OptimizingFloating-PointCalculations270Summary270Chapter10:WorkingwithStrings273MovingStrings273TheMOVSinstruction274TheREPprefix278OtherREPinstructions283StoringandLoadingStrings283TheLODSinstruction283TheSTOSinstruction284Buildingyourownstringfunctions285ComparingStrings286TheCMPSinstruction286UsingREPwithCMPS288Stringinequality289ScanningStrings291TheSCASinstruction292Scanningformultiplecharacters293Findingastringlength295Summary296Chapter11:UsingFunctions297DefiningFunctions297AssemblyFunctions299Writingfunctions299Accessingfunctions302Functionplacement304Usingregisters304Usingglobaldata304PassingDataValuesinCStyle306Revisitingthestack306Passingfunctionparametersonthestack306Functionprologueandepilogue308Defininglocalfunctiondata30902_579010ftoc.qxd1/7/0510:37AMPagexviiixixContentsCleaningoutthestack312Anexample312Watchingthestackinaction314UsingSeparateFunctionFiles317Creatingaseparatefunctionfile317Creatingtheexecutablefile318Debuggingseparatefunctionfiles319UsingCommand-LineParameters320Theanatomyofaprogram320Analyzingthestack321Viewingcommand-lineparameters323Viewingenvironmentvariables325Anexampleusingcommand-lineparameters326Summary328Chapter12:UsingLinuxSystemCalls329TheLinuxKernel329Partsofthekernel330Linuxkernelversion336SystemCalls337Findingsystemcalls337Findingsystemcalldefinitions338Commonsystemcalls339UsingSystemCalls341Thesystemcallformat341AdvancedSystemCallReturnValues346Thesysinfosystemcall346Usingthereturnstructure347Viewingtheresults348TracingSystemCalls349Thestraceprogram349Advancedstraceparameters350Watchingprogramsystemcalls351Attachingtoarunningprogram353SystemCallsversusCLibraries355TheClibraries356TracingCfunctions357ComparingsystemcallsandClibraries358Summary35902_579010ftoc.qxd1/7/0510:37AMPagexixxxContentsChapter13:UsingInlineAssembly361WhatIsInlineAssembly?361BasicInlineAssemblyCode365Theasmformat365UsingglobalCvariables367Usingthevolatilemodifier369Usinganalternatekeyword369ExtendedASM370ExtendedASMformat370Specifyinginputandoutputvalues370Usingregisters372Usingplaceholders373Referencingplaceholders376Alternativeplaceholders377Changedregisterslist377Usingmemorylocations379Usingfloating-pointvalues380Handlingjumps382UsingInlineAssemblyCode384Whataremacros?384Cmacrofunctions384Creatinginlineassemblymacrofunctions386Summary387Chapter14:CallingAssemblyLibraries389CreatingAssemblyFunctions389CompilingtheCandAssemblyPrograms391Compilingassemblysourcecodefiles392Usingassemblyobjectcodefiles392Theexecutablefile393UsingAssemblyFunctionsinCPrograms395Usingintegerreturnvalues396Usingstringreturnvalues397Usingfloating-pointreturnvalues400Usingmultipleinputvalues401Usingmixeddatatypeinputvalues403UsingAssemblyFunctionsinC++Programs407CreatingStaticLibraries408Whatisastaticlibrary?408Thearcommand40902_579010ftoc.qxd1/7/0510:37AMPagexxxxiContentsCreatingastaticlibraryfile410Compilingwithstaticlibraries412UsingSharedLibraries412Whataresharedlibraries?412Creatingasharedlibrary414Compilingwithasharedlibrary414Runningprogramsthatusesharedlibraries415DebuggingAssemblyFunctions417DebuggingCprograms417Debuggingassemblyfunctions418Summary420Chapter15:OptimizingRoutines421OptimizedCompilerCode421Compileroptimizationlevel1422Compileroptimizationlevel2423Compileroptimizationlevel3425CreatingOptimizedCode425Generatingtheassemblylanguagecode425Viewingoptimizedcode429Recompilingtheoptimizedcode429OptimizationTricks430Optimizingcalculations430Optimizingvariables433Optimizingloops437Optimizingconditionalbranches442Commonsubexpressionelimination447Summary450Chapter16:UsingFiles453TheFile-HandlingSequence453OpeningandClosingFiles454Accesstypes455UNIXpermissions456Openfilecode458Openerrorreturncodes459Closingfiles460WritingtoFiles460Asimplewriteexample460Changingfileaccessmodes462Handlingfileerrors46202_579010ftoc.qxd1/7/0510:37AMPagexxixxiiContentsReadingFiles463Asimplereadexample464Amorecomplicatedreadexample465Reading,Processing,andWritingData467Memory-MappedFiles470Whatarememory-mappedfiles?470Themmapsystemcall471mmapassemblylanguageformat473Anmmapexample475Summary479Chapter17:UsingAdvancedIA-32Features481ABriefReviewofSIMD481MMX482SSE483SSE2483DetectingSupportedSIMDOperations483Detectingsupport484SIMDfeatureprogram485UsingMMXInstructions487Loadingandretrievingpackedintegervalues487PerformingMMXoperations488UsingSSEInstructions497Movingdata498Processingdata499UsingSSE2Instructions504Movingdata505Processingdata505SSE3Instructions508Summary508Index51102_579010ftoc.qxd1/7/0510:37AMPagexxiiIntroductionAssemblylanguageisoneofthemostmisunderstoodprogramminglanguagesinuse.Whenthetermassemblylanguageisused,itofteninvokestheideaoflow-levelbitshufflingandporingoverthousand-pageinstructionmanualslookingfortheproperinstructionformat.Withtheproliferationoffancyhigh-levellanguagedevelopmenttools,itisnotuncommontoseethephrase“assemblylanguageprogrammingisdead”popupamongvariousprogrammingnewsgroups.However,assemblylanguageprogrammingisfarfromdead.Everyhigh-levellanguageprogrammustbecompiledintoassemblylanguagebeforeitcanbelinkedintoanexecutableprogram.Forthehigh-levellanguageprogrammer,understandinghowthecompilergeneratestheassemblylanguagecodecanbeagreatbenefit,bothfordirectlywritingroutinesinassemblylanguageandforunderstandinghowthehigh-levellanguageroutinesareconvertedtoassemblylanguagebythecompiler.WhoThisBookIsForTheprimarypurposeofthisbookistoteachhigh-levellanguageprogrammershowtheirprogramsareconvertedtoassemblylanguage,andhowthegeneratedassemblylanguagecodecanbetweaked.Thatsaid,themainaudienceforthisbookisprogrammersalreadyfamiliarwithahigh-levellanguage,suchasC,C++,orevenJava.Thisbookdoesnotspendmuchtimeteachingbasicprogrammingprinciples.Itassumesthatyouarealreadyfamiliarwiththebasicsofcomputerprogramming,andareinterestedinlearningassemblylanguagetounderstandwhatishappeningunderneaththehood.However,ifyouarenewtoprogrammingandarelookingatassemblylanguageprogrammingasaplacetostart,thisbookdoesnottotallyignoreyou.Itispossibletofollowalonginthechaptersfromthestarttothefinishandobtainabasicknowledgeofhowassemblylanguageprogramming(andprogrammingingeneral)works.Eachofthetopicspresentedincludesexamplecodethatdemonstrateshowtheassem-blylanguageinstructionswork.Ifyouarecompletelynewtoprogramming,Ire

professional assembly language.pdf

professional assembly language.…

上传者: 我是谁是我
47次下载 0人收藏 暂无简介 简介 2012-05-14 举报

简介:关于汇编语言的书

ProfessionalAssemblyLanguageRichardBlum01_579010ffirs.qxd1/7/0510:19AMPageiii01_579010ffirs.qxd1/7/0510:19AMPageiiProfessionalAssemblyLanguage01_579010ffirs.qxd1/7/0510:19AMPagei01_579010ffirs.qxd1/7/0510:19AMPageiiProfessionalAssemblyLanguageRichardBlum01_579010ffirs.qxd1/7/0510:19AMPageiiiProfessionalAssemblyLanguagePublishedbyWileyPublishing,Inc.10475CrosspointBoulevardIndianapolis,IN46256www.wiley.comCopyright2005byWileyPublishing,Inc.,Indianapolis,Indiana.Allrightsreserved.PublishedsimultaneouslyinCanadaISBN:0-7645-7901-0ManufacturedintheUnitedStatesofAmerica109876543211MA/SW/QR/QV/INNopartofthispublicationmaybereproduced,storedinaretrievalsystemortransmittedinanyformorbyanymeans,electronic,mechanical,photocopying,recording,scanningorotherwise,exceptaspermittedunderSections107or108ofthe1976UnitedStatesCopyrightAct,withouteitherthepriorwrittenpermis-sionofthePublisher,orauthorizationthroughpaymentoftheappropriateper-copyfeetotheCopyrightClearanceCenter,222RosewoodDrive,Danvers,MA01923,(978)750-8400,fax(978)646-8600.RequeststothePublisherforpermissionshouldbeaddressedtotheLegalDepartment,WileyPublishing,Inc.,10475CrosspointBlvd.,Indianapolis,IN46256,(317)572-3447,fax(317)572-4355,e-mail:brandreview@wiley.com.LIMITOFLIABILITY/DISCLAIMEROFWARRANTY:THEPUBLISHERANDTHEAUTHORMAKENOREPRESENTATIONSORWARRANTIESWITHRESPECTTOTHEACCURACYORCOMPLETENESSOFTHECONTENTSOFTHISWORKANDSPECIFICALLYDISCLAIMALLWARRANTIES,INCLUDINGWITHOUTLIMITATIONWARRANTIESOFFITNESSFORAPARTICULARPURPOSE.NOWARRANTYMAYBECREATEDOREXTENDEDBYSALESORPROMOTIONALMATERIALS.THEADVICEANDSTRATEGIESCONTAINEDHEREINMAYNOTBESUITABLEFOREVERYSITUATION.THISWORKISSOLDWITHTHEUNDERSTANDINGTHATTHEPUBLISHERISNOTENGAGEDINRENDERINGLEGAL,ACCOUNTING,OROTHERPROFESSIONALSERVICES.IFPROFESSIONALASSISTANCEISREQUIRED,THESERVICESOFACOMPETENTPROFESSIONALPERSONSHOULDBESOUGHT.NEITHERTHEPUBLISHERNORTHEAUTHORSHALLBELIABLEFORDAMAGESARISINGHERE-FROM.THEFACTTHATANORGANIZATIONORWEBSITEISREFERREDTOINTHISWORKASACITATIONAND/ORAPOTENTIALSOURCEOFFURTHERINFORMATIONDOESNOTMEANTHATTHEAUTHORORTHEPUBLISHERENDORSESTHEINFORMATIONTHEORGANIZATIONORWEBSITEMAYPROVIDEORRECOMMENDATIONSITMAYMAKE.FURTHER,READERSSHOULDBEAWARETHATINTERNETWEBSITESLISTEDINTHISWORKMAYHAVECHANGEDORDISAP-PEAREDBETWEENWHENTHISWORKWASWRITTENANDWHENITISREAD.Forgeneralinformationonourotherproductsandservicesortoobtaintechnicalsupport,pleasecontactourCustomerCareDepartmentwithintheU.S.at(800)762-2974,outsidetheU.S.at(317)572-3993orfax(317)572-4002.Wileyalsopublishesitsbooksinavarietyofelectronicformats.Somecontentthatappearsinprintmaynotbeavailableinelectronicbooks.Blum,Richard.1962-Professionalassemblylanguage/RichardBlum.p.cm.Includesindex.ISBN0-7645-7901-0(paper/website)1.Assemblylanguage(Computerprogramlanguage)1.Title.QA76.73.A8B582005005.13'6—dc222004029116Trademarks:Wiley,theWileyPublishinglogo,Wrox,theWroxlogo,ProgrammertoProgrammerandrelatedtradedressaretrademarksorregisteredtrademarksofJohnWiley&Sons,Inc.and/oritsaffiliates,intheUnitedStatesandothercountries,andmaynotbeusedwithoutwrittenpermission.Allothertrademarksarethepropertyoftheirrespectiveowners.WileyPublishing,Inc.,isnotassociatedwithanyproductorvendormentionedinthisbook.01_579010ffirs.qxd1/7/0510:19AMPageivAbouttheAuthorRichardBlumhasworkedforalargeU.S.governmentorganizationformorethan15years.Duringthattime,hehashadtheopportunitytoprogramutilitiesinvariousprogramminglanguages:C,C++,Java,andMicrosoftVB.NETandC#.Withthisexperience,Richhasoftenfoundthebenefitofreviewingassemblylanguagecodegeneratedbycompilersandutilizingassemblylanguageroutinestospeeduphigher-levellanguageprograms.RichhasabachelorofsciencedegreeinelectricalengineeringfromPurdueUniversity,whereheworkedonmanyassemblylanguageprojects.(Ofcourse,thiswasbackintheeight-bitprocessordays.)HealsohasamasterofsciencedegreeinmanagementfromPurdueUniversity,specializinginManagementInformationSystems.WhenRichisnotbeingacomputernerd,heiseitherplayingelectricbassforthechurchworshipbandorspendingtimewithhiswife,Barbara,andtwodaughters,KatieJaneandJessica.01_579010ffirs.qxd1/7/0510:19AMPagev01_579010ffirs.qxd1/7/0510:19AMPageviCreditsExecutiveEditorChrisWebbDevelopmentEditorAdaobiObiTultonProductionEditorWilliamA.BartonTechnicalEditorPaulCarterCopyEditorLuannRouffEditorialManagerKathrynMalmBourgoineVicePresident&ExecutiveGroupPublisherRichardSwadleyVicePresidentandPublisherJosephB.WikertProjectCoordinatorErinSmithGraphicsandProductionSpecialistsJonelleBurnsAmandaCarterCarrieA.FosterLaurenGoddardDennyHagerJoyceHaugheyQualityControlTechniciansDavidFaustSusanMoritzCarlWilliamPierceMediaDevelopmentSpecialistAngieDennyProofreadingTECHBOOKSProductionServicesIndexingRichardT.Evans01_579010ffirs.qxd1/7/0510:19AMPagevii01_579010ffirs.qxd1/7/0510:19AMPageviiiThisbookisdedicatedtomywife,Barbara,andmydaughters,KatieJaneandJessica.“TrustintheLordwithallyourheartandleannotonyourownunderstanding;inallwaysacknowledgehim,andhewillmakeyourpathsstraight.”Pr3:5-6(NIV)01_579010ffirs.qxd1/7/0510:19AMPageix01_579010ffirs.qxd1/7/0510:19AMPagexAcknowledgmentsFirst,allhonor,glory,andpraisegotoGod,whothroughHisSonmakesallthingspossibleandgivesusthegiftofeternallife.ManythanksgotothegreatteamofpeopleatJohnWiley&SonsPublishing.ThankstoChrisWebb,theacquisitionseditor,forofferingmetheopportunitytowritethisbook.IamforeverindebtedtoAdaobiObiTulton,thedevelopmenteditor,forherworkinmakingthisbookpresentableandheroverallguid-ancethroughthebookwritingprocess.Also,manythanksgotoPaulCarter,thetechnicaleditorofthebook.Paul’scommentsthroughoutthebookwereinvaluableinpresentingthetopicinthebestwayandforpointingoutmygoofsandblunders.IwouldalsoliketothankCaroleMcClendonatWatersideProductions,Inc.,forarrangingthisopportunityforme,andforhelpingoutinmywritingcareer.Finally,Iwouldliketothankmyparents,MikeandJoyceBlum,fortheirdedicationandsupportwhileraisingme,andtomywife,Barbara,anddaughters,KatieJaneandJessica,fortheirlove,patience,andunderstanding,especiallywhileIwaswritingthisbook.01_579010ffirs.qxd1/7/0510:19AMPagexi01_579010ffirs.qxd1/7/0510:19AMPagexiiContentsAcknowledgmentsxiContentsxiiiIntroductionxxiiiChapter1:WhatIsAssemblyLanguage?1ProcessorInstructions1Instructioncodehandling2Instructioncodeformat3High-LevelLanguages6Typesofhigh-levellanguages7High-levellanguagefeatures9AssemblyLanguage10Opcodemnemonics11Definingdata12Directives14Summary15Chapter2:TheIA-32Platform17CorePartsofanIA-32Processor17Controlunit19Executionunit24Registers25Flags29AdvancedIA-32Features32Thex87floating-pointunit32Multimediaextensions(MMX)33StreamingSIMDextensions(SSE)33Hyperthreading34TheIA-32ProcessorFamily34Intelprocessors35Non-Intelprocessors36Summary3702_579010ftoc.qxd1/7/0510:37AMPagexiiixivContentsChapter3:TheToolsoftheTrade39TheDevelopmentTools39TheAssembler40TheLinker42TheDebugger43TheCompiler44Theobjectcodedisassembler44TheProfiler44TheGNUAssembler45Installingtheassembler45Usingtheassembler47Awordaboutopcodesyntax49TheGNULinker50TheGNUCompiler53Downloadingandinstallinggcc53Usinggcc54TheGNUDebuggerProgram56Downloadingandinstallinggdb56Usinggdb57TheKDEDebugger60Downloadingandinstallingkdbg60Usingkdbg60TheGNUObjdumpProgram62Usingobjdump63Anobjdumpexample64TheGNUProfilerProgram65Usingtheprofiler65Aprofileexample68ACompleteAssemblyDevelopmentSystem69ThebasicsofLinux69DownloadingandrunningMEPIS70Yournewdevelopmentsystem71Summary72Chapter4:ASampleAssemblyLanguageProgram73ThePartsofaProgram73Definingsections74Definingthestartingpoint74CreatingaSimpleProgram75TheCPUIDinstruction76Thesampleprogram7702_579010ftoc.qxd1/7/0510:37AMPagexivxvContentsBuildingtheexecutable80Runningtheexecutable80Assemblingusingacompiler80DebuggingtheProgram81Usinggdb81UsingCLibraryFunctionsinAssembly86Usingprintf87LinkingwithClibraryfunctions88Summary90Chapter5:MovingData91DefiningDataElements91Thedatasection91Definingstaticsymbols94Thebsssection95MovingDataElements97TheMOVinstructionformats97Movingimmediatedatatoregistersandmemory98Movingdatabetweenregisters99Movingdatabetweenmemoryandregisters99ConditionalMoveInstructions106TheCMOVinstructions107UsingCMOVinstructions109ExchangingData110Thedataexchangeinstructions111Usingthedataexchangeinstruction116TheStack119Howthestackworks119PUSHingandPOPingdata120PUSHingandPOPingalltheregisters123ManuallyusingtheESPandEBPregisters123OptimizingMemoryAccess123Summary124Chapter6:ControllingExecutionFlow127TheInstructionPointer127UnconditionalBranches129Jumps129Calls132Interrupts13502_579010ftoc.qxd1/7/0510:37AMPagexvxviContentsConditionalBranches136Conditionaljumpinstructions136Thecompareinstruction138Examplesofusingtheflagbits140Loops144Theloopinstructions144Aloopexample145PreventingLOOPcatastrophes145DuplicatingHigh-LevelConditionalBranches146ifstatements147forloops150OptimizingBranchInstructions153Branchprediction153Optimizingtips155Summary158Chapter7:UsingNumbers161NumericDataTypes161Integers162Standardintegersizes162Unsignedintegers164Signedintegers166Usingsignedintegers168Extendingintegers169DefiningintegersinGAS172SIMDIntegers173MMXintegers173MovingMMXintegers174SSEintegers176MovingSSEintegers177BinaryCodedDecimal178WhatisBCD?178FPUBCDvalues179MovingBCDvalues180Floating-PointNumbers182Whatarefloating-pointnumbers?182Standardfloating-pointdatatypes184IA-32floating-pointvalues186Definingfloating-pointvaluesinGAS187Movingfloating-pointvalues187Usingpresetfloating-pointvalues18902_579010ftoc.qxd1/7/0510:37AMPagexvixviiContentsSSEfloating-pointdatatypes190MovingSSEfloating-pointvalues191Conversions196Conversioninstructions196Aconversionexample198Summary199Chapter8:BasicMathFunctions201IntegerArithmetic201Addition201Subtraction210Incrementinganddecrementing215Multiplication216Division221ShiftInstructions223Multiplybyshifting224Dividingbyshifting225Rotatingbits226DecimalArithmetic227UnpackedBCDarithmetic227PackedBCDarithmetic229LogicalOperations231Booleanlogic231Bittesting232Summary233Chapter9:AdvancedMathFunctions235TheFPUEnvironment235TheFPUregisterstack236TheFPUstatus,control,andtagregisters237UsingtheFPUstack242BasicFloating-PointMath245AdvancedFloating-PointMath249Floating-pointfunctions249Partialremainders252Trigonometricfunctions254Logarithmicfunctions257Floating-PointConditionalBranches259TheFCOMinstructionfamily260TheFCOMIinstructionfamily262TheFCMOVinstructionfamily26302_579010ftoc.qxd1/7/0510:37AMPagexviixviiiContentsSavingandRestoringtheFPUState265SavingandrestoringtheFPUenvironment265SavingandrestoringtheFPUstate266WaitingversusNonwaitingInstructions269OptimizingFloating-PointCalculations270Summary270Chapter10:WorkingwithStrings273MovingStrings273TheMOVSinstruction274TheREPprefix278OtherREPinstructions283StoringandLoadingStrings283TheLODSinstruction283TheSTOSinstruction284Buildingyourownstringfunctions285ComparingStrings286TheCMPSinstruction286UsingREPwithCMPS288Stringinequality289ScanningStrings291TheSCASinstruction292Scanningformultiplecharacters293Findingastringlength295Summary296Chapter11:UsingFunctions297DefiningFunctions297AssemblyFunctions299Writingfunctions299Accessingfunctions302Functionplacement304Usingregisters304Usingglobaldata304PassingDataValuesinCStyle306Revisitingthestack306Passingfunctionparametersonthestack306Functionprologueandepilogue308Defininglocalfunctiondata30902_579010ftoc.qxd1/7/0510:37AMPagexviiixixContentsCleaningoutthestack312Anexample312Watchingthestackinaction314UsingSeparateFunctionFiles317Creatingaseparatefunctionfile317Creatingtheexecutablefile318Debuggingseparatefunctionfiles319UsingCommand-LineParameters320Theanatomyofaprogram320Analyzingthestack321Viewingcommand-lineparameters323Viewingenvironmentvariables325Anexampleusingcommand-lineparameters326Summary328Chapter12:UsingLinuxSystemCalls329TheLinuxKernel329Partsofthekernel330Linuxkernelversion336SystemCalls337Findingsystemcalls337Findingsystemcalldefinitions338Commonsystemcalls339UsingSystemCalls341Thesystemcallformat341AdvancedSystemCallReturnValues346Thesysinfosystemcall346Usingthereturnstructure347Viewingtheresults348TracingSystemCalls349Thestraceprogram349Advancedstraceparameters350Watchingprogramsystemcalls351Attachingtoarunningprogram353SystemCallsversusCLibraries355TheClibraries356TracingCfunctions357ComparingsystemcallsandClibraries358Summary35902_579010ftoc.qxd1/7/0510:37AMPagexixxxContentsChapter13:UsingInlineAssembly361WhatIsInlineAssembly?361BasicInlineAssemblyCode365Theasmformat365UsingglobalCvariables367Usingthevolatilemodifier369Usinganalternatekeyword369ExtendedASM370ExtendedASMformat370Specifyinginputandoutputvalues370Usingregisters372Usingplaceholders373Referencingplaceholders376Alternativeplaceholders377Changedregisterslist377Usingmemorylocations379Usingfloating-pointvalues380Handlingjumps382UsingInlineAssemblyCode384Whataremacros?384Cmacrofunctions384Creatinginlineassemblymacrofunctions386Summary387Chapter14:CallingAssemblyLibraries389CreatingAssemblyFunctions389CompilingtheCandAssemblyPrograms391Compilingassemblysourcecodefiles392Usingassemblyobjectcodefiles392Theexecutablefile393UsingAssemblyFunctionsinCPrograms395Usingintegerreturnvalues396Usingstringreturnvalues397Usingfloating-pointreturnvalues400Usingmultipleinputvalues401Usingmixeddatatypeinputvalues403UsingAssemblyFunctionsinC++Programs407CreatingStaticLibraries408Whatisastaticlibrary?408Thearcommand40902_579010ftoc.qxd1/7/0510:37AMPagexxxxiContentsCreatingastaticlibraryfile410Compilingwithstaticlibraries412UsingSharedLibraries412Whataresharedlibraries?412Creatingasharedlibrary414Compilingwithasharedlibrary414Runningprogramsthatusesharedlibraries415DebuggingAssemblyFunctions417DebuggingCprograms417Debuggingassemblyfunctions418Summary420Chapter15:OptimizingRoutines421OptimizedCompilerCode421Compileroptimizationlevel1422Compileroptimizationlevel2423Compileroptimizationlevel3425CreatingOptimizedCode425Generatingtheassemblylanguagecode425Viewingoptimizedcode429Recompilingtheoptimizedcode429OptimizationTricks430Optimizingcalculations430Optimizingvariables433Optimizingloops437Optimizingconditionalbranches442Commonsubexpressionelimination447Summary450Chapter16:UsingFiles453TheFile-HandlingSequence453OpeningandClosingFiles454Accesstypes455UNIXpermissions456Openfilecode458Openerrorreturncodes459Closingfiles460WritingtoFiles460Asimplewriteexample460Changingfileaccessmodes462Handlingfileerrors46202_579010ftoc.qxd1/7/0510:37AMPagexxixxiiContentsReadingFiles463Asimplereadexample464Amorecomplicatedreadexample465Reading,Processing,andWritingData467Memory-MappedFiles470Whatarememory-mappedfiles?470Themmapsystemcall471mmapassemblylanguageformat473Anmmapexample475Summary479Chapter17:UsingAdvancedIA-32Features481ABriefReviewofSIMD481MMX482SSE483SSE2483DetectingSupportedSIMDOperations483Detectingsupport484SIMDfeatureprogram485UsingMMXInstructions487Loadingandretrievingpackedintegervalues487PerformingMMXoperations488UsingSSEInstructions497Movingdata498Processingdata499UsingSSE2Instructions504Movingdata505Processingdata505SSE3Instructions508Summary508Index51102_579010ftoc.qxd1/7/0510:37AMPagexxiiIntroductionAssemblylanguageisoneofthemostmisunderstoodprogramminglanguagesinuse.Whenthetermassemblylanguageisused,itofteninvokestheideaoflow-levelbitshufflingandporingoverthousand-pageinstructionmanualslookingfortheproperinstructionformat.Withtheproliferationoffancyhigh-levellanguagedevelopmenttools,itisnotuncommontoseethephrase“assemblylanguageprogrammingisdead”popupamongvariousprogrammingnewsgroups.However,assemblylanguageprogrammingisfarfromdead.Everyhigh-levellanguageprogrammustbecompiledintoassemblylanguagebeforeitcanbelinkedintoanexecutableprogram.Forthehigh-levellanguageprogrammer,understandinghowthecompilergeneratestheassemblylanguagecodecanbeagreatbenefit,bothfordirectlywritingroutinesinassemblylanguageandforunderstandinghowthehigh-levellanguageroutinesareconvertedtoassemblylanguagebythecompiler.WhoThisBookIsForTheprimarypurposeofthisbookistoteachhigh-levellanguageprogrammershowtheirprogramsareconvertedtoassemblylanguage,andhowthegeneratedassemblylanguagecodecanbetweaked.Thatsaid,themainaudienceforthisbookisprogrammersalreadyfamiliarwithahigh-levellanguage,suchasC,C++,orevenJava.Thisbookdoesnotspendmuchtimeteachingbasicprogrammingprinciples.Itassumesthatyouarealreadyfamiliarwiththebasicsofcomputerprogramming,andareinterestedinlearningassemblylanguagetounderstandwhatishappeningunderneaththehood.However,ifyouarenewtoprogrammingandarelookingatassemblylanguageprogrammingasaplacetostart,thisbookdoesnottotallyignoreyou.Itispossibletofollowalonginthechaptersfromthestarttothefinishandobtainabasicknowledgeofhowassemblylanguageprogramming(andprogrammingingeneral)works.Eachofthetopicspresentedincludesexamplecodethatdemonstrateshowtheassem-blylanguageinstructionswork.Ifyouarecompletelynewtoprogramming,Ire
  • 相关资料
  • 该用户的其他资料
  • 名称/格式
  • 下载次数
  • 资料大小
  • 名称/格式
  • 下载次数
  • 资料大小

用户评论

0/200
暂无评论
上传我的资料

资料阅读排行

关闭

请选择举报的类型

关闭

提示

提交成功!

感谢您对爱问共享资料的支持,我们将尽快核实并处理您的举报信息。

关闭

提示

提交失败!

您的举报信息提交失败,请重试!

关闭

提示

重复举报!

亲爱的用户!感觉您对爱问共享资料的支持,请勿重复举报噢!

全屏 缩小 放大
收藏
资料评价:

/ 577
所需积分:1 立即下载
返回
顶部
举报
资料
关闭

温馨提示

感谢您对爱问共享资料的支持,精彩活动将尽快为您呈现,敬请期待!