




版權說明:本文檔由用戶提供并上傳,收益歸屬內容提供方,若內容存在侵權,請進行舉報或認領
文檔簡介
1從程序到可執行代碼
匯編(2)
5次課2ProcedureCall3BasicConceptTerminologyCallerCalleef()g()call-1h()call-2call-1Caller:fCallee:gcall-2Caller:gCallee:h4Procedure/FunctionImplementationInvokecalleeReturntocallerPassingdataRegistersLocalvariable5Procedure/FunctionImplementationInvokecallee:call(newinstructions)ReturntocallerPassingdataRegistersLocalvariable6InvokeCalleeInstructioncalllabel(direct)call*operand
(indirect)Behaviordescription(byhardware)SavereturnaddressinthestackJumptotheentry
ofcallee call=push+jmppushretaddrjmp
callee7Procedure/FunctionImplementation
Invokecallee:call(newinstructions)Returntocaller:ret(newinstructions)PassingdataRegistersLocalvariable8ReturntoCallerInstructionretBehaviordescription(byhardware)PopreturnaddressfromstackJumptoreturnaddress
incaller
ret=pop+jmppopretaddrjmp
retaddr9Procedure/FunctionImplementation
Invokecallee:call(newinstructions)
Returntocaller:ret(newinstructions)Passingdata:stack,registerRegistersLocalvariable10StackFrameStructureTheportionofstackallocatedforaprocedureAstackframeisdelimitedbyTheframepointer%ebpThestackpointer%espThestackpointercanmovewhentheprocedureisexecuting(dynamic)TheframepointerisstaticFrame%ebp%esp11StackFrameStructurecall:savereturnaddressinthestackret:popreturnaddressfromstackTheendofcaller’sstackframeCallee
Frame%ebp%espretaddrCaller
Frame12FrameChainPointers(%ebp/%esp)onlydelimittopmost
frameFramesarechained%ebp%esp1.callcallee13FrameChainPointers(%ebp/%esp)onlydelimittopmost
frameFramesarechainedretaddr%ebp%esp
1.callcalleecallee:2.push%ebp3.mov%esp,%ebpretaddr%ebp14FrameChainPointers(%ebp/%esp)onlydelimittopmost
frameFramesarechained%ebp%esp
1.callcalleecallee:
2.push%ebp3.mov%esp,%ebpretaddrold%ebp15FrameChainPointers(%ebp/%esp)onlydelimittopmost
frameFramesarechained%ebp%esp
1.callcalleecallee:
2.push%ebp3.mov%esp,%ebpretaddrold%ebp16FrameChainPointers(%ebp/%esp)onlydelimittopmost
frameFramesarechained%ebp%esp
1.callcalleecallee:2.push%ebp3.mov%esp,%ebp ...n-2.mov%ebp,%espn-1.pop%ebpn.retretaddrold%ebp17FrameChainPointers(%ebp/%esp)onlydelimittopmost
frameFramesarechained%ebp%esp
1.callcalleecallee:
2.push%ebp3.mov%esp,%ebp ...n-2.mov%ebp,%espn-1.pop%ebpn.retretaddrold%ebp18FrameChainPointers(%ebp/%esp)onlydelimittopmost
frameFramesarechained%ebp%esp
1.callcalleecallee:
2.push%ebp3.mov%esp,%ebp ...n-2.mov%ebp,%espn-1.pop%ebpn.retretaddrold%ebp19FrameChainPointers(%ebp/%esp)onlydelimittopmost
frameFramesarechained%ebp%esp
1.callcalleecallee:
2.push%ebp3.mov%esp,%ebp ...n-2.mov%ebp,%espn-1.pop%ebp
n.ret20FrameChainPointers(%ebp/%esp)onlydelimittopmost
frameFramesarechainedold%ebpold%ebpold%ebp%ebp%esp21MemoryLayoutUserstack
argumentN22PassingData:ArgumentspushargumentN%ebp%espCaller
Frameargument1......argumentN23PassingData:ArgumentspushargumentN...pushargument1%ebp%espCaller
Frameargument1......argumentN24PassingData:ArgumentspushargumentN...pushargument1callcallee%ebp%espretaddrCaller
FramepushargumentN...pushargument1callcalleepush%ebp%ebpargument1......argumentN25PassingData:Arguments%ebp%espretaddrCaller
FrameCallee
Frameold%ebpargument1......argumentN26PassingData:ArgumentspushargumentN...pushargument1callcalleepush%ebpmov%esp,%ebp...%ebp%esp/retaddrCaller
FrameCallee
Frameargument1......argumentN27PassingData:ArgumentsPushedbyCallerSavedincallerframeJustuponofreturnaddressFromNthto1st(fromrighttoleft)UsedbyCalleeRelativeto%ebpOffset:4+4*i+%ebpCallee
Frame%ebp%espretaddrCaller
Frame28PassingData:ReturnValueSpecificregistertokeepthereturnvalue%eaxisusedtopasstheresultofcalleetocaller29Procedure/FunctionImplementation
Invokecallee:call(newinstructions)
Returntocaller:ret(newinstructions)
Passingdata:stack,registerRegisters:callingconventionLocalvariable30CallingConventionRegistersactasasingleresourcesharedbyalloftheproceduresOnly1procedurecanbeactivePartitionregistersbetweencallerandcalleeSaller-saveregisterCallee-saveregisterOnlyconsidertheregistersusedbytheprocedure31CallingConventionCaller-saveregisters%eax,%edx,%ecxSavedbycallerCalleecanusetheseregistersfreelyThecontentsintheseregistersmaybechangedafterreturnCallermustrestorethemifittriestousethemaftercallingSaved%eaxargument1......argumentN32Caller-saveRegisterspush%eaxpushargumentN...pushargument1callcallee%ebp%espretaddrCaller
Frame33CallingConventionCallee-saveregisters%ebx,%esi,%ediSavedbycalleeCallercanusetheseregistersfreelyCalleemustsavethembeforeusingCalleemustrestorethembeforereturn34Callee-saveRegisterscallcalleepush%ebpmov%esp,%ebppush%ebx...Old%ebpSaved%ebxCallee
Frame%ebp%espretaddr35Procedure/FunctionImplementation
Invokecallee:call(newinstructions)
Returntocaller:ret(newinstructions)
Passingdata:stack,register
Registers:callingconventionLocalvariable:stack36LocalVariableWhynotstorelocalvariablesinregisters?NoenoughregistersArrayandstructures(e.g.,a[2])Needaddress(e.g.,&a)Old%ebpLocalvariableSavedregs37LocalVariableAllocationBelowsavedregsorold%ebpmove/sub%esp,(e.g.,subl$4,%esp)De-allocationmove/add%esp,(e.g.,addl$4,%esp)UsageRelativeto%esp/%ebp,(e.g.,movl%eax,8(%esp))Callee
Frame%ebp%espretaddr38PutitTogetherCaller
Frame%ebp%espcaller-saveregisters39PutitTogether1.Savecaller-saveregisters
(%eax,%edx,%ecx)Caller
Frame%ebp%esparguments(n~1)caller-saveregisters40PutitTogether1.Savecaller-saveregisters
(%eax,%edx,%ecx)2.Pushactualarguments
fromrighttoleftCaller
Frame%ebp%esparguments(n~1)caller-saveregisters41PutitTogether1.Savecaller-saveregisters
(%eax,%edx,%ecx)2.Pushactualarguments
fromrighttoleft3.CallinstructionSavereturnaddressTransfercontroltocalleeretaddrCaller
Frame%ebp%esparguments(n~1)42PutitTogether4.Savecaller%ebpcaller-saveregisters%ebpretaddrCaller
Frame%ebp%esparguments(n~1)43PutitTogether4.Savecaller%ebp5.Setcallee%ebpcaller-saveregistersold%ebpretaddrCaller
Frame%esp/%ebparguments(n~1)44PutitTogether4.Savecaller%ebp5.Setcallee%ebp6.Savecallee-saveregisters
(%ebx,%edi,%esi)caller-saveregistersold%ebpretaddrCaller
Framecallee-saveregisters%ebp%esparguments(n~1)45PutitTogether4.Savecaller%ebp5.Setcallee%ebp6.Savecallee-saveregisters
(%ebx,%edi,%esi)7.Allocatespaceforlocal
variablecaller-saveregistersold%ebpretaddrCaller
Framecallee-saveregisterslocalvariables%ebp%esp46PutitTogether...n-4.savereturnvaluein%eaxarguments(n~1)caller-saveregistersold%ebpretaddrCaller
Framecallee-saveregisterslocalvariables%ebp%esp47PutitTogether...n-4.savereturnvaluein%eaxn-3.de-allocatelocalvariablearguments(n~1)caller-saveregistersold%ebpretaddrCaller
Framecallee-saveregisterslocalvariables%ebp%esp48PutitTogether...n-4.savereturnvaluein%eaxn-3.de-allocatelocalvariablen-2.Restorecallee-saveregistersarguments(n~1)caller-saveregistersold%ebpretaddrCaller
Framecallee-saveregisterslocalvariables%ebp%esp/49PutitTogether...n-4.savereturnvaluein%eaxn-3.de-allocatelocalvariablen-2.Restorecallee-saveregistersn-1.Restorecaller%ebparguments(n~1)caller-saveregistersold%ebpretaddrCaller
Framecallee-saveregisterslocalvariables%ebp%esp50PutitTogether...n-4.savereturnvaluein%eaxn-3.de-allocatelocalvariablen-2.Restorecallee-saveregistersn-1.Restorecaller%ebpn.RetinstructionpopreturnaddressTransfercontroltocallerarguments(n~1)caller-saveregistersold%ebpretaddrCaller
Framecallee-saveregisterslocalvariables%ebp%esp51Example1intswap_add(int*xp,int*yp)2{3 intx=*xp;4 inty=*yp;56 *xp=y;7 *yp=x;8 returnx+y;9}1052Example11intcaller()12{13 intarg1=534;14 intarg2=1057;15 intsum=swap_add(&arg1,&arg2);16 intdiff=arg1-arg2;1718 returnsum*diff;19}53Finishingcodeinswap_add0Saved%ebp-4arg2(534)-8arg1(1057)-12yp(&arg2)-16xp(&arg1)-20ReturnAddrSaved%ebpSaved%ebxStackframeforcaller12popl%ebxRestore%ebx13movl%ebp,%esp
Restore%esp14popl%ebpRestore%ebp15ret
ReturntocallerCallbyvalue%ebpxp(=&arg1=%ebp+16)%edxyp(=&arg2=%ebp+20)%ecxoriginalvalue%ebx1591%eax%esp54Array55AccessingArrayTA[N];AllocateacontiguousregioninmemoryThesizeoftheregionissizeof(T)
*
NbytesThestartingaddressofanarrayAisdenotedasXAArrayelementscanbeaccessedUsinganintegerindexrangingbetween0andN-1ArrayelementiisstoredataddressXA+sizeof(T)*i56Array012345678910110481216chara[12];xaxa+4xa+8char*b[5];xbxb+4xb+8xb+12xb+1657Array0481216doublec[2];xcxc+8double*d[5];xdxd+4xd+8xd+12xd+1658PointerArithmeticAdditionandsubtractionp+i,p-i(resultisapointer)p-q(resultisanint)Referencing&dereferencing*p,&ESubscriptionA[i],*(A+i)59MemoryreferencinginstructionEisanarrayofint’sAddressofEisstoredinregister%edxIndexiisstoredinregister%ecxThearrayelementE[i]istranslatedintomovl (%edx,%ecx,4),%eax60PointerArithmeticExpressionTypeValueAssemblycodeEint*xEmovl%edx,%eaxE[0]intM[xE]movl(%edx),%eaxE[i]
intM[xE+4i]movl(%edx,%ecx,4),%eax&E[2]
int*xE+8leal8(%edx,)%eaxE+i-1int*xE+4i-4lea-4(%edx,%ecx,4),%eax*(&E[i]+i)
intM[xE+4i+4i]movl(%edx,%ecx,8),%eax&E[i]-E
intimovl%ecx,%eax61NestedArrayintA[4][3];ArrayAisatwo-dimensionalarraywithfourrowsandthreecolumnsItisreferencedasA[0][0]throughA[3][2]RowElementAddressA[0]A[0][0]xAA[0][1]xA+4A[0][2]xA+8A[1]A[1][0]xA+12A[1][1]xA+16A[1][2]xA+20A[2]A[2][0]xA+24A[2][1]xA+28A[2][2]xA+32A[3]A[3][0]xA+36A[3][1]xA+40A[3][2]xA+4462NestedArrayintA[4][3];Arrayofarraytypedefintrow3_t[3];
row3_tA[4];ArrayAcontains4elements,
eachrequiring12bytesto
store3integersThewholesizeofarrayAis48bytesRowmajororderedinmemory63NestedArrayTD[R][C];D[i][j]isatmemoryaddressxD+L*(C*i+j)Lissizeof(T)64AccessA[i,j]ItisinmemoryM[xA+j*4+i*12]%eaxcontainsxA%edxholdsi,%ecxholdsjsall$2,%ecx #j*4leal(%edx,%edx,2),%edx#i*3leal(%ecx,%edx,4),%ecx#j*4+i*12movl(%eax,%ecx),%eax
65Fixed-sizeArrays#defineN16typedefintfix_matrix[N][N];/*Computei,koffixedmatrixproduct*/intfix_prod_ele(fix_matrixA,fix_matrixB,
inti,intk){
intj;
intresult=0;
for(j=0;j<N;j++)
result+=A[i][j]*B[j][k];
returnresult;}66Fixed-sizeArrays/*Computei,koffixedmatrixproduct*/intfix_prod_ele_opt(fix_matrixA,fix_matrixB,
inti,intk){
int*Arow=&A[i][0],*Bptr=&B[0][k];
intj,result=0;
for(j=0;j<16;j++){
result+=Arow[j]*(*Bptr);
Bptr+=N;
}
returnresult;}67Fixed-sizeArraysAptrin%esi,Bptrin%ecxresultin%ebx,jin%edx.L6: #loop:movl(%ecx),%eax #Get*Bptrimull(%esi,%edx,4),%eax #MultiplybyArow[j]addl%eax,%ebx #Addtoresultaddl$1,%edx #j++addl$64,%ecx #Add16*4toBptrcmpl$16,%edx #comparej:16jne.L6 #if!=,gotoloop68Variable-SizeArraysintvar_ele(intn,intA[n][n],inti,intj){
returnA[i][j];}DeclareanarrayintA[exp1][exp2]eitherasalocalvariableorasanargumenttoafunctionThedimensionsofthearrayaredeterminedbyevaluatingtheexpressionsatthetimethedeclarationisencounterd69AssemblyCodenat%ebp+8,Aat%ebp+12iat%ebp+16,jat%ebp+20movl8(%ebp),%eax #Getnsall$2,%eax #Compute4*nmovl%eax,%edx #Copy4*nimull16(%ebp),%edx #Compute4*n*imovl20(%ebp),%eax #Getjsall$2,%eax #Compute4*jaddl12(%ebp),%eax #ComputexA+4?jmovl(%eax,%edx),%eax#ReadfromxA+4?(n?i+j)70HeterogeneousDataStructures&Alignment71OutlineStructUnionAlignmentPointers72StructuresGroupobjectsintoasingleobjectstructrect{ intllx;/*Xcoordinateoflower-leftcorner*/ intlly;/*Ycoordinateoflower-leftcorner*/ intcolor;/*Codingofcolor*/ intwidth;/*Width(inpixels)*/ intheight;/*Height(inpixels)*/};73StructuresMemorylayoutAllthecomponentsarestoredinacontiguousregionofmemoryApointertoastructureistheaddressofitsfirstbyte74Structurestructrec{ inti; intj; inta[3]; int*p;}*r;ija[0]a[1]a[2]pContentsOffset0482075StructureReferencestostructureelementsUsingoffsetsasdisplacementsr->j=r->i(Copyelementr->itoelementr->j)risinregister%edx.1 movl (%edx),%eax Getr->i2 movl %eax,4(%edx) Storeinr->jija[0]a[1]a[2]pContentsOffset0482076Structure&(r->a[i])rin%eax,iin%edx:1leal8(%eax,%edx,4),%ecx Generate&r->a[i]ija[0]a[1]a[2]pContentsOffset0482077Structurer->p=&r->a[r->i+r->j];rinregister%edx:1 movl4(%edx),%eax Getr->j2 addl(%edx),%eax Addr->i3 leal8(%edx,%eax,4),%eax Compute&r->a[r->i+r->j]4 movl%eax,20(%edx) Storeinr->pija[0]a[1]a[2]pContentsOffset0482078UnionsAsingleobjectcanbereferencedbyusingdifferentdatatypesThesyntaxofauniondeclarationisidenticaltothatforstructures,butitssemanticsareverydifferentRatherthanhavingthedifferentfieldsreferencedifferentblocksofmemory,theyallreferencethesameblock79UnionsstructS3{ charc; inti[2]; doublev;};unionU3{ charc; inti[2]; doublev;};TypecivsizeS3041220U30008Theoffsetsofthefields,aswellasthetotalsizeofdatatypesS3andU3,are:80UnionsstructNODE{ intis_leaf; union{ struct{ structNODE*left; structNODE*right; }internal; doubledata; }info;};81Unions1
unsignedfloat2bit(floatf)2
{3
union{4
floatf;5
unsignedu;6
}temp;7
temp.f=f;8
returntemp.u;9
}1
movl 8(%ebp),%eax82AlignmentAlignmentrestrictionsTheaddressforsometypeofobjectmustbeamultipleofsomevaluek
(typically2,4,or8)SimplifythehardwaredesignoftheinterfacebetweentheprocessorandthememorysystemInIA32hardwarewillworkcorrectlyregardlessofthealignmentofdataAligneddatacanimprovememorysystemperformance83AlignmentLinuxalignmentrestriction1-bytedatatypesareabletohaveanyaddress2-bytedatatypesmusthaveanaddressthatismultipleof2Anylargerdatatypesmusthaveanaddressthatismultipleof484SimpleExamplestructxxx{ inti; charc; doubled;};structxxxx[2];0x000x040x080x0C0x100x14&x[0].i&x[0].c&x[0].d&x[1].iComplexExamplestructxxx{shorts;charc0;inti;longl;charc1;chara[2];doubled;charc2;};structxxxx[2];850x000x040x080x0C0x100x140x180x1C&x[0].s&x[0].c0&x[0].i&x[0].l&x[0].c1&x[0].a[0]&x[0].a[1]&x[0].d&x[0].c2&x[1].s86Arraystructccc{charc1;chara[3];charc2;};structcccc[2];0x000x040x080x0C0x100x14&c[0].c1&c[0].a[0]&c[0].c2&c[1].c1&c[1].a[0]&c[1].c287Arraystructccc{charc1;shorta[3];charc2;};structssss[2];0x000x040x080x0C0x100x14&s[0].c1&s[0].c2&s[0].a[0]&s[1].c1&s[1].c2&s[1].a[0]88Arraystructiii{charc1;inta[3];charc2;};structiiii[2];0x000x040x080x0C0x100x14&s[0].c1&s[0].c2&x[0].i&s[1].c189PointersEverypointerhasatypeIftheobjecthastypeTApointertothisobjecthastypeT*Specialvoid*typeRepresentsagenericpointermallocreturnsagenericpointerEverypointerhasavalue90PointersPointersarecreatedwiththe&operatorAppliedtolvalueexpressionLvalueexpressioncanappearontheleftsideofassignmentPointersaredereferencedwiththeoperator*TheresultisavaluehavingthetypeassociatedwiththepointerArraysandpointersareclosedrelatedThenameofarraycanbeviewedasapointerconstantip[0]isequivalentto*ip91PointerArithmeticAdditionandsubtractionp+i,p-i(resultisapointer)p-q(resultisaint)Referencing&dereferencing*p,&ESubscriptionA[i],*(A+i)92Pointerscanpointtofunctionsvoid(*f)(int*)fisapointertofunctionThefunctiontakenint*asargumentThereturntypeofthefunctionisvoidAssignmentmakesfpointtofuncf=funcNoticetheprecedenceoftheoperatorsvoid*f(int*)declaresfisafunction(void*)f(int*)93PointerDeclarationchar **argv;int (*daytab)[13]int (*comp)()char (*(*x())[])()Functionreturningpointertoarray[]ofpointertofunctionreturningcharchar (*(*x[3])())[5]Array[3]ofpointertofunctionreturningpointertoarray[5]ofchar94CoperatorsOperators Associativity()[]->.++-- lefttoright!~++--+-*&(type)sizeof righttoleft*/% lefttoright+- lefttoright<<>> lefttoright<<=>>= lefttoright==!= lefttoright& lefttoright^ lefttoright| lefttoright&& lefttoright|| lefttoright?: righttoleft=+=-=*=/=%=&=^=!=<<=>>= righttoleft, lefttorightNote:Unary+,-,and*havehigherprecedencethanbinaryforms95ParameterPassingCallbyvaluef(xp)Callbyreferencef(&xp)96BufferOverflow97Out-of-BoundsMemoryReferences1/*Implementationoflibraryfunctiongets()*/2char*gets(char*s)3{4 intc;5 char*dest=s;6 intgot_char=0;/Hasatleastonecharacterbeenread?*/7 while((c=getchar())!=’\n’&&c!=EOF){8 *dest++=c;/*Noboundschecking*/9 gotchar=1;10 }11 *dest++=’\0’; /*TerminateString*/12 if(c==EOF&&!gotchar)13 returnNULL;/*Endoffileorerror*/14 returns;15}98Out-of-BoundsMemoryReferences14/*Readinputlineandwriteitback*/15voidecho()16{17 charbuf[8]; /*Waytoosmall!*/18 gets(buf);19 puts(buf);20}99Out-of-BoundsMemoryReferencesReturnaddressSaved%ebpSaved%ebx[7][6][5][4][3][2][1][0]%ebpbufStackframeforcallerStackframeforecho100Out-of-BoundsMemoryReferencesReturnaddressSaved%ebp[11][10][9][8][7][6][5][4][3][2][1][0]%ebpbufStackframeforcallerStackframeforecho101Out-of-BoundsMemoryReferencesReturnaddress[15]1[4][13][12][11][10][9][8][7][6][5][4][3][2][1][0]%ebpbufStackframeforcallerStackframeforecho102Out-of-BoundsMemoryReferences[19][18][17][16][15]1[4][13][12][11][10][9][8][7][6][5][4][3][2][1][0]%ebpbufStackframeforcallerStackframeforecho103MaliciousUseofBufferOverflowvoidbar(){charbuf[64];gets(buf);...}voidfoo(){bar();...}returnaddressAStackaftercalltogets()BfoostackframebarstackframeBexploitcodepaddatawrittenbygets()104TheFamousInternetWormofNovember1988TogainaccesstomanyofthecomputersacrosstheInternet4differentwaysOnewasabufferoverflowattackonthefingerdHundredsofmachineswereeffectivelyparalyzedTheauthorofthewormwascaughtandprosecuted.Hewassentencedto3yearsprobation400hoursofcommunityserviceanda$10,500fine105MorrisWormRobertTappanMorrisbornNovember8,1965aprofessoratMITHeisthesonofRobertMorristheformerchiefscientistattheNationalComputerSecurityCenteradivisionoftheNationalSecurityAgency(NSA)106ThwartingBufferOverflowAttacksStackRandomizationStackCorruptionDetectionLimitingExecutableCodeRegions107Machine-LevelRepresentation
ofPrograms(x86-64)108SizeofDataTypeDataTypesinCLanguageDataTypeIA32(Linux)x86-64(Linux)char11short22int44longint48longlong88float44double88longdouble1216pointer(e.g.char*)48IntegerRegisterExtendexistregistersto64bits%rbp%rsp%rdi%rsi%rdx%rcx%rbx%rax%eax%edx%ecx%ebx%esi%edi%esp%ebp%al%ah%dl%dh%cl%ch%bl%bhIntegerRegisterAdd8new64bitsregisters%rbp%rsp%rdi%rsi%rdx%rcx%rbx%rax%eax%ebx%ecx%edx%esi%edi%esp%ebp%al%ah%dl%dh%cl%ch%bl%bh%r15%r14%r13%r12%r11%r10%r9%r8%r8d%r9d%r10d%r11d%r12d%r13d%r14d%r15d111InstructionsLongwordl(4Bytes)?Quadwordq(8Bytes)NewInstructionsmovl→movqaddl→addqsall→salqetc.32-bitinstructionsgenerate32-bitresultsSethigherorderbitsofdestinationregisterto0Example:addlIA32/LinuxStackFrameCallerStackFrameArgumentsforthiscallReturnAddress(pushedby“call”)CalleeStackFrameOld%ebp(savedby“push%ebp”)SavedregistersLocalvariablesArgumentsfornextcall112Procedures-StackRetAddrArgumentsOld%ebpSavedregistersLocalvariablesArguments%ebp%espframepointerstackpointerIA32/LinuxRegisterUsage%eax,%edx,%ecxCallersavespriorthecall
ifvaluesareusedbylater%eaxReturnintegervalue%ebx,%esi,%ediCalleesavesifwantto
usedthem%esp,%ebpspecial113Procedures-Register%eax%edx%ecx%ebx%esi%edi%esp%ebpCaller-SaveCallee-SaveSpecial%rbp%rsp%rdi%rsi%rdx%rcx%rbx%rax%r15%r14%r13%r12%r11%r10%r9%r8X86-64/LinuxRegisterUsageCaller-Save%rax%rcx%rdx
%rsi%rdi%r8%r9Callee-Save%rbx%rbp%r10%r12%r13%r14%r15Special%rsp,%r11114Procedures-Register%rbp%rsp%rdi%rsi%rdx%rcx%rbx%rax%r15%r14%r13%r12%r11%r10%r9%r8X86-64/LinuxRegisterUsageArgumentspassedviaregs%rcx%rdx%rsi%rdi
%r8%r9Ifmorethan6integer
parameters,thenpass
restonstackReturnvalueby%raxNoframepointerSpecial%rspstackpointer%r11usedforlinking115Procedures-Register%rbp%rsp%rdi%rsi%rdx%rcx%rbx%rax%r15%r14%r13%r12%r11%r10%r9%r8%rdiarg#1%rsiarg#2%rdxarg#3%rcxarg#4%r9arg#6%r8arg#5%raxret%rspstack%r11linkx86-64/LinuxStackFrameCallerStackFrameArgumentspassedviaregistersReturnAddress(pushedby“call”)CalleeStackFrameSavedregistersLocalvariables116Procedures-StackRetAddrSavedregistersLocalvariables%rspstackpointer117X86-64SwapOperandspassedinregistersFirst(xp)in%rdi,second(yp)in%rsiNostackoperationsrequired(exceptret)AvoidstackCanholdalllocalinformationinregistersvoidswap(long*xp,long*yp){longt0=*xp;longt1=*yp;*xp=t1;*yp=t0;}swap:movq(%rdi),%rdxmovq(%rsi),%raxmovq%rax,(%rdi)movq%rdx,(%rsi)ret118AlignmentBytesIA32x86-64TypeAlignmentTypeAlignment1charNocharNo2short02short024int,float,pointer002int,
float0028double0002(Win)002(Lin)double,pointer000212/16longdouble002longdouble00002ExampleIA32LinuxK=4;doubletreatedlikea4-bytedatatypeX86-64orIA32Windows:K=8;duetodoubleelementstructs1{charc;inti[2];doubled;}*p;C3bytesi[0]i[1]4bytesdp+0p+4p+8p+16p+24C3bytesi[0]i[1]dp+0p+4p+8p+12p+20119120從程序到可執行代碼
指令編碼和匯編器
1次課Y86ProcessorStateProgramRegistersSame8aswithIA32.Each32bitsConditionCodesSingle-bitflagssetbyarithmeticorlogicalinstructionsOF:OverflowZF:ZeroSF:NegativeProgramCounterIndicatesaddressofinstructionMemoryByte-addressablestoragearrayWordsstoredinlittle-endianbyteorder%eax%ecx%edx%ebx%esi%edi%esp%ebpProgramregistersConditioncodesPCMemoryOFZFSFY86InstructionsFormat1--6bytesofinformationreadfrommemoryCandetermineinstructionlengthfromfirstbyteNotasmanyinstructiontypes,andsimplerencodingthanwithIA32Eachaccessesandmodifiessomepart(s)oftheprogramstateY86InstructionsFormat(P259)1--6bytesofinformationreadfrommemoryCandetermineinstructionlengthfromfirstbyteNotasmanyinstructiontypes,andsimplerencodingthanwithIA32Eachaccessesandmodifiessomepart(s)oftheprogramstateErrata:JXXandcallare5byteslong.Format(P259)1--6bytesofinformationreadfrommemoryCandetermineinstructionlengthfromfirstbyteNotasmanyinstructiontypes,andsimplerencodingthanwithIA32Eachaccessesandmodifiessomepart(s)oftheprogramstateErrata:JXXandcallare5byteslong.EncodingRegistersEachregisterhas4-bitIDSameencodingasinIA32,butIA32usingonly3-bitIDRegisterIDFindicates“noregister”Willusethisinourhardwaredesigninmultipleplaces%eax%ecx%edx%ebx%esi%edi%esp%ebp012367451InstructionExampleAdditionInstructione.g.,addl%eax,%esi
Encoding:
6006Two-byteencodingFirstindicatesinstructiontypeSecondgivessourceanddestinationregistersEncodedRepresentationGe
溫馨提示
- 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯系上傳者。文件的所有權益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網頁內容里面會有圖紙預覽,若沒有圖紙預覽就沒有圖紙。
- 4. 未經權益所有人同意不得將文件中的內容挪作商業或盈利用途。
- 5. 人人文庫網僅提供信息存儲空間,僅對用戶上傳內容的表現方式做保護處理,對用戶上傳分享的文檔內容本身不做任何修改或編輯,并不能對任何下載內容負責。
- 6. 下載文件中如有侵權或不適當內容,請與我們聯系,我們立即糾正。
- 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 診所引流現場管理制度
- 診療技術授權管理制度
- 調解中心監督管理制度
- 財政特設專戶管理制度
- 貨代公司各類管理制度
- 貨物裝卸安全管理制度
- 貨船安全生產管理制度
- 2025年中國感應式皂液器行業市場全景分析及前景機遇研判報告
- 2025年中國動作感應手柄行業市場全景分析及前景機遇研判報告
- 液壓工具質保協議書范本
- 2025至2030中國材料疲勞試驗機行業項目調研及市場前景預測評估報告
- 2025年陜西、山西、寧夏、青海四省(陜晉寧青)高考 生物真題試卷 附答案
- 2024年西昌市教育和體育局考核聘用公立幼兒園教師真題
- 2025設備租賃合同版本范文
- 2025年浙江杭州錢塘區和達能源有限公司招聘筆試沖刺題(帶答案解析)
- 2025年衣物清潔多元化發展趨勢白皮書-天貓家清第一財經商業數據中心
- 冷鏈物流園建設項目投融資與財務方案
- 保險業務員分級考試試題及答案
- 2024統編版七年級道德與法治下冊期末測試卷(含答案)
- 酒店經銷商合同協議書
- 轉讓釣場合同協議書
評論
0/150
提交評論