关闭

关闭

关闭

封号提示

内容

首页 X86_Assembly.pdf

X86_Assembly.pdf

X86_Assembly.pdf

Emperor_of_the_World 2011-09-19 评分 0 浏览量 0 0 0 0 暂无简介 简介 举报

简介:本文档为《X86_Assemblypdf》,可适用于IT/计算机领域,主题内容包含XAssemblyFromWikibooks,theopencontenttextbookscollectionContents•Introduct符等。

XAssemblyFromWikibooks,theopencontenttextbookscollectionContents•Introduction•WhyLearnAssembly•WhoisThisBookFor•HowisThisBookOrganized•BasicFAQ•HowDoestheComputerReadUnderstandAssembly•IsittheSameOnWindowsDOSLinux•WhichAssemblerisBest•DoINeedtoKnowAssembly•HowShouldIFormatmyCode•XFamily•IntelxMicroprocessors•AMDxCompatibleMicroprocessors•XArchitecture•xArchitecture•GeneralPurposeRegisters(GPR)•SegmentRegisters•EFLAGSRegister•InstructionPointer•Memory•Two'scomplementrepresentation•Addressingmodes•Stack•CPUOperationModes•RealMode•ProtectedMode•FlatMemoryModel•MultiSegmentedMemoryModel•Comments•Comments•HLAComments•andBits•TheRegisters•Example•TheAGateSaga•BitAddressing•XInstructions•Conventions•DataTransfer•Datatransferinstructions•Move•DataSwap•MoveandExtend•MovebyDataSizeTheWikibookofxAssemblyLanguageIntroductionxAssemblyWhyLearnAssemblyAssemblyisthemostprimitivetoolintheprogrammerstoolboxEntiresoftwareprojectscanbewrittenwithouteveroncelookingatasinglelineofassemblycodeSothequestionarises:whylearnassemblyAssemblylanguageistheclosestformofcommunicationthathumanscanengageinwithacomputerUsingassembly,theprogrammercanpreciselytracktheflowofdataandexecutioninaprogramAlso,anotherbenefittolearningassembly,isthatonceaprogramhasbeencompiled,itisdifficultifnotimpossibletodecompilethecodeThatmeansthatifyouwanttoexamineaprogramthatisalreadycompiled,youwillneedtoexamineitinassemblylanguageDebuggersalsowillfrequentlyonlyshowtheprogramcodeinassemblylanguageIfnothingelse,itcanbebeneficialtolearntoreadassemblylanguage,ifnotwriteitAssemblylanguageisalsothepreferredtool,ifnottheonlytoolavailableforimplementingsomelowleveltasks,suchasbootloaders,andlowlevelkernelcomponentsCodewritteninassemblyhaslessoverheadthancodewritteninhighlevellanguages,soassemblycodefrequentlywillrunmuchfasterthanprogramswritteninotherlanguagesCodethatiswritteninahighlevellanguagecanbecompiledintoassembly,and"handoptimized"tosqueezeeverylastbitofspeedoutofasectionofcodeAshardwaremanufacturerssuchasIntelandAMDaddnewfeaturesandnewinstructionstotheirprocessors,oftentimestheonlywaytoaccessthosefeaturesistouseassemblyroutinesThatis,atleastuntilthemajorcompilervendorsaddsupportforthosefeaturesDevelopingaprograminassemblycanbeaverytimeconsumingprocess,howeverWhileitmightnotbeagoodideatowritenewprojectsinassemblylanguage,itiscertainlyvaluabletoknowalittlebitaboutassemblylanguageanywayWhoisThisBookForThisbookwillserveasanintroductiontoassemblylanguage,butitwillalsoserveasagoodresourceforpeoplewhoalreadyknowthetopic,butneedsomemoreinformationonxsystemarchitecture,andadvancedusesofxassemblylanguageAllreadersareencouragedtoread(andcontributeto)thisbook,althoughapriorknowledgeofprogrammingfundamentalswouldbeadefinitebenefitHowisThisBookOrganizedThefirstsectionwilltalkaboutthexfamilyofchips,andwillintroducethebasicinstructionsetThesecondsectionwilltalkaboutthedifferencesbetweenthesyntaxofdifferentassemblersThethirdsectionwilltalkaboutsomeoftheadditionalinstructionsetsavailable,includingtheFloatingPointoperations,theMMXoperations,andtheSSEoperationsThefourthsectionwilltalkaboutsomeadvancedtopicsinxassembly,includingsomelowlevelprogrammingtaskssuchaswritingbootloadersTherearemanytasksthatcannotbeeasilyimplementedinahigherlevellanguagesuchasCorCForexample,taskssuchasenablinganddisablinginterrupts,enablingprotectedmode,accessingtheControlRegisters,creatingaGlobalDescriptorTable,etcallneedtobehandledinassemblyThefourthsectionwillalsotalkabouthowtointerfaceassemblylanguagewithCandotherhighlevellanguagesOnceafunctioniswritteninAssembly(afunctiontoenableprotectedmode,forinstance),wecaninterfacethatfunctiontoalarger,Cbased(orevenCbased)kernelTheFifthsectionwilldealwiththestandardxchipset,willtalkaboutthebasicxcomputerarchitecture,andwillgenerallydealwiththehardwaresideofthingsThecurrentlayoutofthebookisdesignedtogivereadersasmuchinformationastheyneed,withoutgoingoverboardReaderswhowanttolearnassemblylanguageonagivenassembleronlyneedtoreadthefirstsectionandthechapterinthesecondsectionthatdirectlyrelatestotheirassemblerProgrammerslookingtoimplementtheMMXorSSEinstructionsfordifferentalgorithmsonlyreallyneedtoreadsectionProgrammerslookingtoimplementbootloadersandkernels,orotherlowleveltasks,canreadsectionPeoplewhoreallywanttogettothenittygrittyofthexhardwaredesigncancontinuereadingonthroughsectionBasicFAQxAssemblyThispageisgoingtoserveasabasicFAQforpeoplewhoarenewtoassemblylanguageprogrammingHowDoestheComputerReadUnderstandAssemblyThecomputerdoesn'treally"read"or"understand"anythingperse,butthat'sbesidethepointThefactisthatthecomputercannotreadtheassemblylanguagethatyouwriteYourassemblerwillconverttheassemblylanguageintoaformofbinaryinformationcalled"machinecode"thatyourcomputerusestoperformitsoperationsIfyoudon'tassemblethecode,it'scompletegibberishtothecomputerThatsaid,assemblyisnotedbecauseeachassemblyinstructionusuallyrelatestojustasinglemachinecode,anditispossiblefor"meremortals"todothistaskdirectlywithnothingbutablanksheetofpaper,apencil,andanassemblyinstructionreferencebookIndeedintheearlydaysofcomputersthiswasacommontaskandevenrequiredinsomeinstancesto"handassemble"machineinstructionsforsomebasiccomputerprogramsAclassicalexampleofthiswasdonebySteveWozniak,whenhehandassembledtheentireIntegerBASICinterpreterintothemachinecodeforuseonhisinitialAppleIcomputerItshouldbenoted,however,thatsuchtasksforcommerciallydistributedsoftwarearesuchraritiesthattheydeservespecialmentionfromthatfactaloneVery,veryfewprogrammershaveactuallydonethisformorethanafewinstructions,andeventhenjustforaclassroomassignmentIsittheSameOnWindowsDOSLinuxTheanswerstothisquestionareyesandnoThebasicxmachinecodeisdependentonlyontheprocessorThexversionsofWindowsandLinuxareobviouslybuiltonthexmachinecodeThereareafewdifferencesbetweenLinuxandWindowsprogramminginxAssembly:OnaLinuxcomputer,themostpopularassembleristheGASassembler,whichusestheATTsyntaxforwritingcode,orNetwideAssemblerwhichisalsoknownasNASMwhichusesasyntaxsimilartoMASMOnaWindowscomputer,themostpopularassemblerisMASM,whichusestheIntelsyntaxThelistofavailablesoftwareinterrupts,andtheirfunctions,isdifferentonWindowsandLinuxThelistofavailablecodelibrariesisdifferentonWindowsandLinuxUsingthesameassembler,thebasicassemblycodewrittenoneachOperatingSystemisbasicallythesame,exceptyouinteractwithWindowsdifferentlythanyouinteractwithLinux,etcWhichAssemblerisBestTheshortansweristhatnoneoftheassemblersarebetterthantheothers,it'samatterofpersonalpreferenceThelongansweristhatdifferentassemblershavedifferentcapabilities,drawbacks,etcIfyouonlyknowGASsyntax,thenyouwillprobablywanttouseGASIfyouknowIntelsyntaxandareworkingonawindowsmachine,youmightwanttouseMASMIfyoudon'tlikesomeofthequirksorcomplexitiesofMASMandGAS,youmightwanttotryFASMandNASMWewillcoverthedifferencesbetweenthedifferentassemblersinsectionDoINeedtoKnowAssemblyYoudon'tneedtoknowassemblyformostcomputertasks,butitcertainlyisniceLearningassemblyisnotaboutlearninganewprogramminglanguageIfyouaregoingtostartanewprogrammingproject(unlessthatprojectisabootloaderoradevicedriverorakernel),thenyouwillprobablywanttoavoidassemblyliketheplagueAnexceptiontothiscouldbeifyouabsolutelyneedtosqueezethelastbitsofperformanceoutofacongestedinnerloopandyourcompilerisproducingsuboptimalcodeKeepinmind,though,thatprematureoptimizationistherootofallevil,althoughsomecomputingintenserealtimetaskscanonlyeasilybeoptimizedsufficientlyifoptimizationtechniquesareunderstoodandplannedforfromthestartHowever,learningassemblygivesaparticularinsightintohowyourcomputerworksontheinsideWhenyouprograminahigherlevellanguagelikeC,orAda,orevenJavaandPerl,allyourcodewilleventuallyneedtobeconvertedintotermsofmachinecodeinstructions,soyourcomputercanexecutethemUnderstandingthelimitsofexactlywhattheprocessorcando,atthemostbasiclevel,willalsohelpwhenprogrammingahigherlevellanguageHowShouldIFormatmyCodeMostassemblersrequirethatassemblycodeinstructionseachappearontheirownline,andareseparatedbyacarriagereturnMostassemblersalsoallowforwhitespacetoappearbetweeninstructions,operands,etcExactlyhowyouformatcodeisuptoyou,althoughtherearesomecommonways:Onewaykeepseverythinglinedup:Label:movax,bxaddax,bxjmpLabelLabel:movax,cxAnotherwaykeepsallthelabelsinonecolumn,andalltheinstructionsinanothercolumn:Label:movax,bxaddax,bxjmpLabelLabel:movax,cxAnotherwayputslabelsontheirownlines,andindentsinstructionsslightly:Label:movax,bxaddax,bxjmpLabelLabel:movax,cxYetanotherwaywillseparatelabelsandinstructionsintoseparatecolumns,ANDkeeplabelsontheirownlines:Label:movax,bxaddax,bxjmpLabelLabel:movax,cxSothereareamilliondifferentwaystodoit,buttherearesomegeneralrulesthatassemblyprogrammersgenerallyfollow:makeyourlabelsobvious,sootherprogrammerscanseewheretheyaremorestructure(indents)willmakeyourcodeeasiertoreadusecomments,toexplainwhatyouaredoingXFamilyxAssemblyThexfamilyofmicroprocessorsisaverylargefamilyofchipswithalonghistoryThispagewilltalkaboutthespecificsofeachdifferentprocessorinthisfamilyxmicroprocessorsarealsocalled“IA”processorsIntelxMicroprocessorsWikipediahasrelatedinformationatListofIntelmicroprocessors()ThewastheoriginalIntelMicroprocessor,withtheasitsfloatingpointcoprocessorThewasIntel'sfirstbitmicroprocessor()Afterthedevelopmentofthe,IntelalsocreatedthelowercostThewassimilartothe,butwithanbitdatabusinsteadofabitbus()ThewasthesecondIntelchipinthefamilythewasitsfloatingpointcoprocessorExceptfortheadditionofsomenewinstructions,optimizationofsomeoldones,andanincreaseintheclockspeed,thisprocessorwasidenticaltothe()ThewasthethirdmodelinthefamilythewasitsfloatingpointcoprocessorTheintroducedthe“ProtectedMode”modeofoperation,asopposedtothe“RealMode”thattheearliermodelsusedAllxchipscanbemadetoruninrealmodeorinprotectedmode()ThewasthefourthmodelinthefamilyItwasthefirstIntelmicroprocessorwithabitwordTheDXmodelwastheoriginalchip,andtheSXmodelwasaneconomymodelthatusedthesameinstructionset,butwhichonlyhadabitbusTheEXmodelisstillusedtodayinembeddedsystems()ThewasthefifthmodelinthefamilyIthadanintegratedfloatingpointunitforthefirsttimeinxhistoryEarlymodelDXchipsfoundtohavedefectiveFPU'swerephysicallymodifiedtodisconnecttheFPUportionofthechipandsoldastheSX(SX,SX,andSX)A"mathcoprocessor"wasavailabletoSXusersandwasessentiallyaDXwithaworkingFPUandanextrapinaddedThearrivaloftheDXprocessorsawthewidespreadintroductionoffanlessheatsinksbeingusedtokeeptheprocessorsfromoverheatingPentium()Intelcalleditthe“Pentium”becausetheycouldn'ttrademarkthecodenumber“”TheoriginalPentiumwasafasterchipthanthewithafewotherenhancementslatermodelsalsointegratedtheMMXinstructionsetPentiumPro()ThePentiumProwasthesixthgenerationarchitecturemicroprocessor,originallyintendedtoreplacetheoriginalPentiuminafullrangeofapplications,butlaterreducedtoamorenarrowroleasaserverandhighenddesktopchipPentiumII()ThePentiumIIwasbasedonamodifedversionofthePcorefirstusedforthePentiumPro,butwithimprovedbitperformanceandtheadditionoftheMMXSIMDinstructionset,whichhadalreadybeenintroducedonthePentiumMMXPentiumIII()InitialversionsofthePentiumIIIwereverysimilartotheearlierPentiumII,themostnotabledifferencebeingtheadditionofSSEinstructionsPentium()ThePentiumhadanewthgeneration"NetBurst"architectureItiscurrentlythefastestxchiponthemarketwithrespecttoclockspeed,capableofuptoGHzPentiumchipsalsointroducedthenotions“HyperThreading”,and“MultiCore”chipsCore()ThearchitectureoftheCoreprocessorswasactuallyanevenmoreadvancedversionofthethgenerationarchitecturedatingbacktothePentiumProThelimitationsoftheNetBurstarchitecture,especiallyinmobileapplications,weretoogreattojustifycreationofmoreNetBurstprocessorsTheCoreprocessorsweredesignedtooperatemoreefficientlywithalowerclockspeedAllCorebrandedprocessorshadtwoprocessingcorestheCoreSoloshadonecoredisabled,whiletheCoreDuosusedbothprocessorsCore()Anupgraded,bitversionoftheCorearchitectureAlldesktopversionsaremulticoreCeleron(firstmodel)TheCeleronchipisactuallyalargenumberofdifferentchipdesigns,dependingonpriceCeleronchipsaretheeconomylineofchips,andarefrequentlycheaperthanthePentiumchipseveniftheCeleronmodelinquestionisbasedoffaPentiumarchitectureXeon(firstmodel)TheXeonprocessorsaremodernIntelprocessorsmadeforservers,whichhaveamuchlargercache(measuredinmegabytesincomparisontootherchipskilobytesizecache)thanthePentiummicroprocessorsAMDxCompatibleMicroprocessorsWikipediahasrelatedinformationatListofAMDmicroprocessorsAthlonAthlonisthebrandnameappliedtoaseriesofdifferentxprocessorsdesignedandmanufacturedbyAMDTheoriginalAthlon,orAthlonClassic,wasthefirstseventhgenerationxprocessorand,inafirst,retainedtheinitialperformanceleadithadoverIntel'scompetingprocessorsforasignificantperiodoftimeTurionTurionisthebrandnameAMDappliestoitsbitlowpower(mobile)processorsTurionprocessors(butnotTurionXprocessors)arecompatiblewithAMD'sSocketandareequippedwithorKiBofLcache,abitsinglechannelondiememorycontroller,andanMHzHyperTransportbusDuronTheAMDDuronwasanxcompatiblecomputerprocessormanufacturedbyAMDItwasreleasedasalowcostalternativetoAMD'sownAthlonprocessorandthePentiumIIIandCeleronprocessorlinesfromrivalIntelSempronSempronis,asof,AMD'sentryleveldesktopCPU,replacingtheDuronprocessorandcompetingagainstIntel'sCeleronDprocessorOpteronTheAMDOpteronisthefirsteighthgenerationxprocessor(Kcore),andthefirstofAMD'sAMD(x)processorsItisintendedtocompeteintheservermarket,particularlyinthesamesegmentastheIntelXeonprocessorXArchitecturexAssemblyxArchitectureThexarchitecturehasGeneralPurposeRegisters(GPR),SegmentRegisters,FlagsRegisterandanInstructionPointerWikipediahasrelatedinformationatProcessorregisterGeneralPurposeRegisters(GPR)TheGPRsare:EAX:AccumulatorregisterUsedinarithmeticoperationsECX:CounterregisterUsedinshiftrotateinstructionsEDX:DataregisterUsedinarithmeticoperationsandIOoperationsEBX:BaseregisterUsedasapointertodata(locatedinDSinsegmentedmode)ESP:StackPointerregisterPointertothetopofthestackEBP:StackBasePointerregisterUsedtopointtothebaseofthestackESI:SourceregisterUsedasapointertoasourceinstreamoperationsEDI:DestinationregisterUsedasapointertoadestinationinstreamoperationsEachoftheGPRarebitswideandaresaidtobeExtendedRegisters(thustheirExxname)TheirLeastSignificantBits(LSBs)canbeaccessedusingtheirunextendedparts,namelyAX,CX,DX,BX,SP,BP,SI,andDITheextendedregisterscanbeseparatedinto"high"(theMostSignificantBits)and"low"(theLeastSignificantBits)portionsThusanextendedregisterhastheform:HHHHHHHHHHHHHHHHLLLLLLLLLLLLLLLL(Here,anHoranLdenotesasinglebit)whichcanalsobeexpressedas:HW|LWWhereHWandLWdenote"HighWord"and"LowWord"respectivelyForthefirstregisters(AX,CX,DX,BX),theMostSignificantBits(MSBs)andtheLSBsoftheirlowwordcanalsobeaccessedviaAH,CH,DH,BHandAL,CL,DL,BLrespectivelyAHisanabbreviationfor"AXHigh"ThistermoriginatesfromthefactthatthelowwordoftheregistercanbedecomposedintoitshighandlowbytesTheCH,DH,andBHmnemonicsaretobeinterpretedinasimilarfashionLikewise,ALisanabbreviationfor"AXLow"CL,DL,andBLaresimiliarilynamedSegmentRegistersTheSegmentRegistersare:•SS:StackSegmentPointertothestack•CS:CodeSegmentPointertothecode•DS:DataSegmentPointertothedata•ES:ExtraSegmentPointertoextradata('E'standsfor"Extra")•FS:FSegmentPointertomoreextradata('F'comesafter'E')•GS:GSegmentPointertostillmoreextradata('G'comesafter'F')Mostapplicationsonmostmodernoperatingsystems(likeLinuxorMicrosoftWindows)useamemorymodelthatpointsnearlyallsegmentregisterstothesameplace(andusespaginginstead),effectivelydisablingtheiruseTypicallyFSorGSisanexceptiontothisrule,tobeusedtopointatthreadspe

用户评论(0)

0/200

精彩专题

上传我的资料

每篇奖励 +1积分

资料评分:

/24
仅支持在线阅读

意见
反馈

立即扫码关注

爱问共享资料微信公众号

返回
顶部

举报
资料