Assembly Language For X86 Processors 7th Edition Pdf Download

  • Unformatted text preview: Assembly Language for x86 Processors 7th Edition Kip R. Irvine Chapter 5: Procedures Chapter Overview • • • • • Stack Operations Defining and Using Procedures Linking to an External Library The Irvine32 Library 64-­Bit Assembly Programming Irvine, K ip R. Assembly L anguage for x86 P rocessors 7 /e, 2 015. 2 Stack Operations.
  • Answers to End of Chapter Reviews and Exercises for Assembly Language for x86 Processors, 7th Edition. A more correct term is 'assembly language'.

Presentation on theme: 'Assembly Language for x86 Processors 7th Edition'— Presentation transcript:

1 Assembly Language for x86 Processors 7th Edition
Kip R. IrvineChapter 8: Advanced ProceduresSlides prepared by the author.Revised by Zuoliu Ding at Fullerton College, 08/2014(c) Pearson Education, All rights reserved. You may modify and copy this slide show for your personal use, or for use in the classroom, as long as this copyright statement, the author's name, and the title are not changed.

2 Chapter Overview Stack Frames Recursion INVOKE, ADDR, PROC, and PROTO
Creating Multimodule ProgramsAdvanced Use of Parameters (optional)Java Bytecodes (optional)Irvine, Kip R. Assembly Language for x86 Processors 7/e, 2015.

3 Stack Frames Stack Parameters Local Variables
ENTER and LEAVE InstructionsLOCAL DirectiveWriteStackFrame ProcedureIrvine, Kip R. Assembly Language for x86 Processors 7/e, 2015.

4 Stack Frame Also known as an activation record
Area of the stack set aside for a procedure's return address, passed parameters, saved registers, and local variablesCreated by the following steps:Calling program pushes arguments on the stack and calls the procedure.The called procedure pushes EBP on the stack, and sets EBP to ESP.If local variables are needed, a constant is subtracted from ESP to make room on the stack.Irvine, Kip R. Assembly Language for x86 Processors 7/e, 2015.

The Art of Assembly Language Page iii The Art of Assembly Language (Full Contents) Forward Why Would Anyone Learn This Stuff? 1 1 What’s Wrong With Assembly Language. 1 2 What’s Right With Assembly Language?

5 Stack Parameters More convenient than register parameters
Two possible ways of calling DumpMem. Which is easier?Why need Stack Parameters?Anatomy of C codepushadmov esi,OFFSET arraymov ecx,LENGTHOF arraymov ebx,TYPE arraycall DumpMempopadpush TYPE arraypush LENGTHOF arraypush OFFSET arraycall DumpMemint AddTwo(int i, int j){return i+j;}int f(int &i, bool b)int n, m; // do...return m; int x = AddTwo(5, 6);int y = f(x, true);Irvine, Kip R. Assembly Language for x86 Processors 6/e, 2010.

6 Passing Arguments by Value
Push argument values on stack(Use only 32-bit values in protected mode to keep the stack aligned)Call the called-procedureAccept a return value in EAX, if anyRemove arguments from the stack if the called- procedure did not remove themIrvine, Kip R. Assembly Language for x86 Processors 7/e, 2015.

7 Example (val2) 6 (val1) 5 ESP Stack prior to CALL .data val1 DWORD 5
.codepush val2push val1(val2)(val1) ESPStack prior to CALLIrvine, Kip R. Assembly Language for x86 Processors 7/e, 2015.

8 Passing Arguments by Value: AddTwo
.datasum DWORD ?.codepush 6 ; second argumentpush 5 ; first argumentcall AddTwo ; EAX = summov sum,eax ; save the sumint n = AddTwo( 5, 6 );AddTwo PROCpush ebpmov ebp,esp.Irvine, Kip R. Assembly Language for Intel-Based Computers 5/e, 2007.

9 Passing by Reference Push the offsets of arguments on the stack
Call the procedureAccept a return value in EAX, if anyRemove arguments from the stack if the called procedure did not remove themIrvine, Kip R. Assembly Language for x86 Processors 7/e, 2015.

10 Example (offset val2) 00000004 (offset val1) 00000000 ESP
.dataval1 DWORD 5val2 DWORD 6.codepush OFFSET val2push OFFSET val1(offset val2)(offset val1) ESPStack prior to CALLIrvine, Kip R. Assembly Language for x86 Processors 7/e, 2015.

11 Stack after the CALL value or addr of val2 value or addr of val1
[EBP+12][EBP+8][EBP+4]ESP, EBPvalue or addr of val2value or addr of val1return addressEBPIrvine, Kip R. Assembly Language for x86 Processors 7/e, 2015.

12 Passing Arguments by Reference: Swap
An argument passed by reference consists of the address (offset) of an object:push offset val2push offset val1call SwapIn C/C++,Swap(&val1, &val2);Irvine, Kip R. Assembly Language for Intel-Based Computers 5/e, 2007.

13 Accessing Stack Parameters (C/C++)
C and C++ functions access stack parameters using constant offsets from EBP1.Example: [ebp + 8]EBP is called the base pointer or frame pointer because it holds the base address of the stack frame.EBP does not change value during the function.EBP must be restored to its original value when a function returns.1 BP in Real-address modeIrvine, Kip R. Assembly Language for x86 Processors 7/e, 2015.

14 RET Instruction Return from subroutine
Pops stack into the instruction pointer (EIP or IP). Control transfers to the target address.Syntax:RETRET nOptional operand n causes n bytes to be added to the stack pointer after EIP (or IP) is assigned a value.Irvine, Kip R. Assembly Language for x86 Processors 7/e, 2015.

15 Who removes parameters from the stack?
Caller (C) or Called-procedure (STDCALL):AddTwo PROCpush val push ebppush val mov ebp,espcall AddTwo mov eax,[ebp+12]add esp, add eax,[ebp+8]pop ebpret( Covered later: The MODEL directive specifies calling conventions )Irvine, Kip R. Assembly Language for x86 Processors 7/e, 2015.

16 C Call : Caller releases stack RET does not clean up the stack.
AddTwo_C PROCpush ebpmov ebp,espmov eax,[ebp + 12] ; second parameteradd eax,[ebp + 8] ; first parameterpop ebpret ; caller cleans up the stackAddTwo_C ENDP_Example1 PROCpush 6push 5call AddTwo_Cadd esp,8 ; clean up the stackcall DumpRegs ; sum is in EAXret_Example1 ENDPIrvine, Kip R. Assembly Language for Intel-Based Computers 5/e, 2007.

17 STDCall : Procedure releases stack The RET n instruction cleans up the stack.
AddTwo PROCpush ebpmov ebp,espmov eax,[ebp + 12] ; second parameteradd eax,[ebp + 8] ; first parameterpop ebpret 8 ; clean up the stackAddTwo ENDP_Example2 PROCpush 6push 5call AddTwocall DumpRegs ; sum is in EAXret_Example2 ENDPIrvine, Kip R. Assembly Language for Intel-Based Computers 5/e, 2007.

18 Passing an Array by Reference (1 of 2)
The ArrayFill procedure fills an array with 16-bit random integersThe calling program passes the address of the array, along with a count of the number of array elements:.datacount = 100array WORD count DUP(?).codepush OFFSET arraypush COUNTcall ArrayFillIrvine, Kip R. Assembly Language for x86 Processors 7/e, 2015.

19 Passing an Array by Reference (2 of 2)
ArrayFill can reference an array without knowing the array's name:ArrayFill PROCpush ebpmov ebp,esppushadmov esi,[ebp+12]mov ecx,[ebp+8].ESI points to the beginning of the array, so it's easy to use a loop to access each array element. View the complete program.Irvine, Kip R. Assembly Language for x86 Processors 7/e, 2015.

20 ArrayFill Procedure ArrayFill PROC push ebp mov ebp,esp
pushad ; save registersmov esi,[ebp+12] ; offset of array, beginningmov ecx,[ebp+8] ; array sizecmp ecx,0 ; ECX 0?je L2 ; yes: skip over loopL1: mov eax,10000h ; get random 0 - FFFFhcall RandomRange ; from the link librarymov [esi],axadd esi,TYPE WORDloop L1L2: popad ; restore registerspop ebpret 8 ; clean up the stackArrayFill ENDPIrvine, Kip R. Assembly Language for Intel-Based Computers 5/e, 2007.

21 Your turn . . .Create a procedure named Difference that subtracts the first argument from the second one. Following is a sample call: (30 – 14 = 16)push ; second argument, subtrahendpush ; first argument, minuend call Difference ; EAX = 16int diff =Difference(30, 14);Difference PROCpush ebpmov ebp,espmov eax,[ebp + 8] ; first argument (30)sub eax,[ebp + 12] ; second argument (14)pop ebpret 8Difference ENDPIrvine, Kip R. Assembly Language for x86 Processors 6/e, 2010.

22 Local VariablesOnly statements within subroutine can view or modify local variablesStorage used by local variables is released when subroutine endslocal variable name can have the same name as a local variable in another function without creating a name clashEssential when writing recursive procedures, as well as procedures executed by multiple execution threadsIrvine, Kip R. Assembly Language for x86 Processors 7/e, 2015.

23 Local VariablesTo explicitly create local variables, subtract total size from ESP.void MySub(){int X=10;int Y=20;}MySub PROCpush ebpmov ebp,espsub esp, ; create variablesmov DWORD PTR [ebp-4],10 ; Xmov DWORD PTR [ebp-8],20 ; Y; ... Do somethingmov esp,ebp ; remove locals from stackpop ebpretMySub ENDP LocalVars.asmIrvine, Kip R. Assembly Language for Intel-Based Computers 5/e, 2007.

24 ENTER and LEAVEENTER instruction creates stack frame for a called procedurepushes EBP on the stack (push ebp)sets EBP to the base of the stack frame (mov ebp, esp)reserves space for local variables (sub esp, n)Syntax: ENTER numBytesReserved, nestingLevel (=0)LEAVE instruction terminates the stack frame for a called procedurerestores ESP to release local variables (mov esp, ebp)pops EBP for the caller (pop ebp)Irvine, Kip R. Assembly Language for Intel-Based Computers 5/e, 2007.

25 LEAVE Instruction Terminates the stack frame for a procedure. push ebp
Equivalent operationspush ebpmov ebp,espsub esp, ; 2 local DWORDsMySub PROCenter 8,0...leaveretMySub ENDPmov esp,ebp ; free local spacepop ebpIrvine, Kip R. Assembly Language for x86 Processors 7/e, 2015.

26 LOCAL Directive The LOCAL directive declares a list of local variables
immediately follows the PROC directiveeach variable is assigned a typeSyntax:LOCAL varlistExample:MySub PROCLOCAL var1:BYTE, var2:WORD, var3:SDWORDIrvine, Kip R. Assembly Language for x86 Processors 7/e, 2015.

27 Using LOCAL Examples: LOCAL flagVals[20]:BYTE ; array of bytes
LOCAL pArray:PTR WORD ; pointer to an arraymyProc PROC, ; procedureLOCAL t1:BYTE, ; local variablesIrvine, Kip R. Assembly Language for x86 Processors 7/e, 2015.

28 LOCAL Example MASM generates: BubbleSort PROC LOCAL temp:DWORD,
SwapFlag:BYTE. . .retBubbleSort ENDPMASM generates:BubbleSort PROCpush ebp ; enter 8, 0mov ebp,espadd esp,0FFFFFFF8h ; add -8 to ESP. . .mov esp,ebp ; leavepop ebpretBubbleSort ENDP See LocalExample.asmIrvine, Kip R. Assembly Language for Intel-Based Computers 5/e, 2007.

29 LEA Instruction LEA returns offsets of direct and indirect operands
OFFSET operator only returns constant offsetsLEA required when obtaining offsets of stack parameters & local variablesExampleCopyString PROC,count:DWORDLOCAL temp[20]:BYTEmov edi,OFFSET count ; invalid operandmov esi,OFFSET temp ; invalid operandlea edi,count ; oklea esi,temp ; okAn example of C++ equivalent assembly code, see textIrvine, Kip R. Assembly Language for x86 Processors 7/e, 2015.

30 LEA Example Suppose you have a Local variable at [ebp-8]
And you need the address of that local variable in ESIYou cannot use this:mov esi, OFFSET [ebp-8] ; errorUse this instead:lea esi,[ebp-8]Irvine, Kip R. Assembly Language for x86 Processors 7/e, 2015.

31 WriteStackFrame Procedure
Displays contents of current stack framePrototype:WriteStackFrame PROTO,numParam:DWORD, ; number of passed parametersnumLocalVal: DWORD, ; number of DWordLocal variablesnumSavedReg: DWORD ; number of saved registersIrvine, Kip R. Assembly Language for x86 Processors 7/e, 2015.

32 WriteStackFrame Example
main PROCmov eax, 0EAEAEAEAhmov ebx, 0EBEBEBEBhINVOKE aProc, 1111h, 2222hexitmain ENDPaProc PROC USES eax ebx,x: DWORD, y: DWORDLOCAL a:DWORD, b:DWORDPARAMS = 2LOCALS = 2SAVED_REGS = 2mov a,0AAAAhmov b,0BBBBhINVOKE WriteStackFrame, PARAMS, LOCALS, SAVED_REGSIrvine, Kip R. Assembly Language for x86 Processors 7/e, 2015.

33   All in Stack Frame [EBP+8] EBP ESP push EBP mov EBP,ESP
Parameter n... …Parameter 1Return AddressEBPLocal Variable 1… …Local Variable mRegister 1Register k[EBP+8]push EBPmov EBP,ESPmov ESP,EBPpop EBPEBPPrologue EpilogueESPIrvine, Kip R. Assembly Language for Intel-Based Computers 5/e, 2007.

34 Review(True/False): A subroutine’s stack frame always contains the caller’s return address and the subroutine’s local variables.(True/False): Arrays are passed by reference to avoid copying them onto the stack.(True/False): A procedure’s prologue code always pushes EBP on the stack.(True/False): Local variables are created by adding an integer to the stack pointer.(True/False): In 32-bit protected mode, the last argument to be pushed on the stack in a procedure call is stored at location ebp+8.(True/False): Passing by reference requires popping a parameter’s offset from the stack inside the called procedure.What are two common types of stack parameters?TFv, rIrvine, Kip R. Assembly Language for x86 Processors 6/e, 2010.

35 What's Next Stack Frames Recursion INVOKE, ADDR, PROC, and PROTO
Creating Multimodule ProgramsAdvanced Use of Parameters (optional)Java Bytecodes (optional)Irvine, Kip R. Assembly Language for x86 Processors 7/e, 2015.

36 Recursion What is Recursion? Recursively Calculating a Sum
Calculating a FactorialIrvine, Kip R. Assembly Language for x86 Processors 7/e, 2015.

37 What is Recursion? The process created when . . .
A procedure calls itselfProcedure A calls procedure B, which in turn calls procedure AUsing a graph in which each node is a procedure and each edge is a procedure call, recursion forms a cycle:Irvine, Kip R. Assembly Language for x86 Processors 7/e, 2015.

38 Recursively Calculating a Sum
The CalcSum procedure recursively calculates the sum of an array of integers. Receives: ECX = count. Returns: EAX = sumCalcSum PROCcmp ecx,0 ; check counter valuejz L2 ; quit if zeroadd eax,ecx ; otherwise, add to sumdec ecx ; decrement countercall CalcSum ; recursive callL2: retCalcSum ENDPStack frame:View the complete programIrvine, Kip R. Assembly Language for x86 Processors 7/e, 2015.

39 Calculating a Factorial (1 of 3)
This function calculates the factorial of integer n. A new value of n is saved in each stack frame:int factorial(int n){if(n 0)return 1;elsereturn n * factorial(n-1);}As each call instance returns, the product it returns is multiplied by the previous value of n.Irvine, Kip R. Assembly Language for x86 Processors 7/e, 2015.

40 Calculating a Factorial (2 of 3)
Factorial PROCpush ebpmov ebp,espmov eax,[ebp+8] ; get ncmp eax,0 ; n > 0?ja L1 ; yes: continuemov eax,1 ; no: return 1jmp L2L1: dec eaxpush eax ; Factorial(n-1)call Factorial; Instructions from this point on excursion when each recursive call returns.ReturnFact:mov ebx,[ebp+8] ; get nmul ebx ; eax = eax * ebxL2: pop ebp ; return EAXret 4 ; clean up stackFactorial ENDPIrvine, Kip R. Assembly Language for x86 Processors 7/e, 2015.

41 Calculating a Factorial (3 of 3)
Suppose we want to calculate 12!This diagram shows the first few stack frames created by recursive calls to FactorialEach recursive call uses 12 bytes of stack space.Irvine, Kip R. Assembly Language for x86 Processors 7/e, 2015.

42 => F: push ebp0, eax is 3 L1, eax=2, push 2
L2, pop ebp3<=[ebp3+8] is 1, 1*1L2, pop ebp2[ebp2+8] is 2, 1*2L2, pop ebp1[ebp1+8] is 3, 2*3L2, pop ebp0eax is 6RetuenMainIrvine, Kip R. Assembly Language for Intel-Based Computers 5/e, Added by Zuoliu Ding

43 Review(True/False): Given the same task to accomplish, a recursive subroutine usually uses less memory than a nonrecursive one.In the Factorial function, what condition terminates the recursion?Which instructions in the assembly language Factorial procedure execute after each recursive call has finished?What will happen to the Factorial program’s output when trying to calculate 13 factorial?Challenge: In the Factorial program, how many bytes of stack space are used by the Factorial procedure when calculating 12 factorial?Challenge: Write the pseudocode for a recursive algorithm that generates the first 20 integers of the Fibonacci series (1, 1, 2, 3, 5, 8, 13, 21, . . .).Fn=0RFUO156Irvine, Kip R. Assembly Language for x86 Processors 6/e, 2010.

44 What's Next Stack Frames Recursion INVOKE, ADDR, PROC, and PROTO
Creating Multimodule ProgramsJava BytecodesIrvine, Kip R. Assembly Language for x86 Processors 7/e, 2015.

45 INVOKE, ADDR, PROC, and PROTO
INVOKE DirectiveADDR OperatorPROC DirectivePROTO DirectiveParameter ClassificationsExample: Exchaning Two IntegersDebugging TipsIrvine, Kip R. Assembly Language for x86 Processors 7/e, 2015.

46 INVOKE DirectiveNot in 64-bit mode!In 32-bit mode, the INVOKE directive is a powerful replacement for Intel’s CALL instruction that lets you pass multiple argumentsSyntax:INVOKE procedureName [, argumentList]ArgumentList is an optional comma-delimited list of procedure argumentsArguments can be:immediate values and integer expressionsvariable namesaddress and ADDR expressionsregister namesIrvine, Kip R. Assembly Language for x86 Processors 7/e, 2015.

47 INVOKE Examples .data byteVal BYTE 10 wordVal WORD 1000h .code
; direct operands:INVOKE Sub1,byteVal,wordVal; address of variable:INVOKE Sub2,ADDR byteVal; register name, integer expression:INVOKE Sub3,eax,(10 * 20); address expression (indirect operand):INVOKE Sub4,[ebx]Irvine, Kip R. Assembly Language for x86 Processors 7/e, 2015.

48 ADDR Operator Not in 64-bit mode!
Returns a near or far pointer to a variable, depending on which memory model your program uses:Small model: returns 16-bit offsetLarge model: returns 32-bit segment/offsetFlat model: returns 32-bit offsetSimple example:.datamyWord WORD ?.codeINVOKE mySub,ADDR myWordIrvine, Kip R. Assembly Language for x86 Processors 7/e, 2015.

49 PROC Directive (1 of 2) The PROC directive declares a procedure
Not in 64-bit mode!PROC Directive (1 of 2)The PROC directive declares a procedureSyntax:label PROC [attributes] [USES regList], paramListThe USES clause must be on the same line as PROC.Attributes: distance, language type, visibilityParamList is a list of parameters separated by commas.label PROC, parameter1, parameter2, …, parameterNEach parameter has the following syntax:paramName : typetype must either be one of the standard ASM types (BYTE, SBYTE, WORD, etc.), or it can be a pointer to one of these types.Irvine, Kip R. Assembly Language for x86 Processors 7/e, 2015.

50 PROC Directive (2 of 2)Alternate format permits parameter list to be on one or more separate lines:label PROC,paramListThe parameters can be on the same line . . .param-1:type-1, param-2:type-2, . . ., param-n:type-nOr they can be on separate lines:param-1:type-1,param-2:type-2,. . .,param-n:type-ncomma requiredIrvine, Kip R. Assembly Language for x86 Processors 7/e, 2015.

51 Example: AddTwo Procedure
AddTwo receives two integers and returns their sum in EAX.See Params.asmMASM Generates:AddTwo PROC,val1:DWORD, val2:DWORDpush ebpmov ebp, espmov eax,val1add eax,val2leaveret hAddTwo ENDP___________________________sub esp, 002hpush myDatapush hcall AddTwoAddTwo PROC,val1:DWORD, val2:DWORDmov eax,val1add eax,val2retAddTwo ENDP___________________________myData WORD 1000hinvoke AddTwo, 1, myDataIrvine, Kip R. Assembly Language for Intel-Based Computers 5/e, 2007.

52 Example: FillArrayFillArray receives a pointer to an array of bytes, a single byte fill value that will be copied to each element of the array, and the size of the array.FillArray PROC,pArray:PTR BYTE, fillVal:BYTEarraySize:DWORDmov ecx,arraySizemov esi,pArraymov al,fillValL1: mov [esi],alinc esiloop L1retFillArray ENDPIrvine, Kip R. Assembly Language for x86 Processors 7/e, 2015.

53 Example: Read_File PROC
MASM Generates: See Params.asmRead_File PROCpush ebpmov ebp, espadd esp, 0FFFFFFFCh ;Localpush eaxpush ebxmov esi, dword ptr [ebp+8]mov dword ptr [ebp-4], eax; ... …pop ebxpop eaxleave ;mov esp, ebp;pop ebpret hRead_File ENDPRead_File PROC USES eax ebx,pBuffer:PTR BYTELOCAL fileHandle:DWORDmov esi, pBuffermov fileHandle, eax;retRead_File ENDPIrvine, Kip R. Assembly Language for Intel-Based Computers 5/e, 2007.

54 PROTO Directive Creates a procedure prototype Syntax:
label PROTO paramListParameter list not permitted in 64-bit modeEvery procedure called by the INVOKE directive must have a prototypeA complete procedure definition can also serve as its own prototypeIrvine, Kip R. Assembly Language for x86 Processors 7/e, 2015.

55 PROTO DirectiveStandard configuration: PROTO appears at top of the program listing, INVOKE appears in the code segment, and the procedure implementation occurs later in the program:MySub PROTO ; procedure prototype.codeINVOKE MySub ; procedure callMySub PROC ; procedure implementation.MySub ENDPIrvine, Kip R. Assembly Language for x86 Processors 7/e, 2015.

56 PROTO ExamplePrototype for the ArraySum procedure, showing its parameter list:ArraySum PROC USES esi ecx,ptrArray:PTR DWORD, ; points to the arrayszArray:DWORD ; array size...ArraySum ENDPArraySum PROTO,Parameters are not permitted in 64-bit mode.Irvine, Kip R. Assembly Language for x86 Processors 7/e, 2015.

57 Assembly Time Argument Checking
mySub1 PROTO, p1:BYTE, p2:WORD, p3:PTR BYTE invoke mySub1, byte_1, byte_1, ADDR byte_1MASM Generates the following and no error detected:A R * push OFFSET byte_1F A R * mov al, byte_1F B6 C0 * movzx eax, al* push eaxA R * mov al, byte_1D * push eaxE E * call mySub1Explain why use movzx and push eax?See 8.4.4, P for detailsIrvine, Kip R. Assembly Language for Intel-Based Computers 5/e, 2007.

58 Parameter Classifications
An input parameter is data passed by a calling program to a procedure.The called procedure is not expected to modify the corresponding parameter variable, and even if it does, the modification is confined to the procedure itself.An output parameter is created by passing a pointer to a variable when a procedure is called.The procedure does not use any existing data from the variable, but it fills in a new value before it returns.An input-output parameter is a pointer to a variable containing input that will be both used and modified by the procedure.The variable passed by the calling program is modified.Irvine, Kip R. Assembly Language for x86 Processors 7/e, 2015.

59 Example: Exchanging Two Integers
The Swap procedure exchanges the values of two 32-bit integers. pValX and pValY do not change values, but the integers they point to are modified.Swap PROC USES eax esi edi,pValX:PTR DWORD, ; pointer to first integerpValY:PTR DWORD ; pointer to second integermov esi,pValX ; get pointersmov edi,pValYmov eax,[esi] ; get first integerxchg eax,[edi] ; exchange with secondmov [esi],eax ; replace first integerretSwap ENDPDemo: Swap.asmWhat if don’t use xchg?Irvine, Kip R. Assembly Language for Intel-Based Computers 5/e, 2007.

60 Trouble-Shooting Tips
Save and restore registers when they are modified by a procedure.Except a register that returns a function resultWhen using INVOKE, be careful to pass a pointer to the correct data type.For example, MASM cannot distinguish between a DWORD argument and a PTR BYTE argument.Do not pass an immediate value to a procedure that expects a reference parameter.Dereferencing its address will likely cause a general-protection fault.Irvine, Kip R. Assembly Language for x86 Processors 7/e, 2015.

61 Using VARARG invoke addup3, 3, 5, 2, 4
addup3 PROC NEAR C, argcount:WORD, arg1:VARARGsub ax, ax ; Clear work registersub si, si.WHILE argcount > 0 ; number of argumentsadd ax, arg1[si] ; Arg1 has the first argumentdec argcount ; Point to next argumentinc si.ENDWret ; Total is in AXaddup3 ENDPMicrosoft MASM 6.1 Programmer's Guide, p149Irvine, Kip R. Assembly Language for x86 Processors 6/e, 2010.

62 What's Next Stack Frames Recursion INVOKE, ADDR, PROC, and PROTO
Creating Multimodule ProgramsAdvanced Use of Parameters (optional)Java Bytecodes (optional)Irvine, Kip R. Assembly Language for x86 Processors 7/e, 2015.

63 Multimodule ProgramsA multimodule program is a program whose source code has been divided up into separate ASM files.Each ASM file (module) is assembled into a separate OBJ file.All OBJ files belonging to the same program are linked using the link utility into a single EXE file.This process is called static linkingIrvine, Kip R. Assembly Language for x86 Processors 7/e, 2015.

64 AdvantagesLarge programs are easier to write, maintain, and debug when divided into separate source code modules.When changing a line of code, only its enclosing module needs to be assembled again. Linking assembled modules requires little time.A module can be a container for logically related code and data (think object-oriented here...)encapsulation: procedures and variables are automatically hidden in a module unless you declare them publicIrvine, Kip R. Assembly Language for x86 Processors 7/e, 2015.

65 Creating a Multimodule Program
Here are some basic steps to follow when creating a multimodule program:Create the main moduleCreate a separate source code module for each procedure or set of related proceduresCreate an include file that contains procedure prototypes for external procedures (ones that are called between modules)Use the INCLUDE directive to make your procedure prototypes available to each moduleIrvine, Kip R. Assembly Language for x86 Processors 7/e, 2015.

66 Example: ArraySum Program
Let's review the ArraySum program from Chapter 5.Each of the four white rectangles will become a module. This will be a 32-bit application.Irvine, Kip R. Assembly Language for x86 Processors 7/e, 2015.

67 Sample Program output Enter a signed integer: -25
The sum of the integers is: +53Irvine, Kip R. Assembly Language for x86 Processors 7/e, 2015.

68 Three Examples: Array Sum
Compare (p175) using Register ParametersNow 8.5.5, use Stack Parameters (ModSum32_traditional.asm)Now 8.5.6, use PROC and Invoke (ModSum32_advanced.asm)Discuss the differencesWhich one is your preferred?Irvine, Kip R. Assembly Language for Intel-Based Computers 5/e, 2007.

69 INCLUDE FileThe sum.inc file contains prototypes for external functions that are not in the Irvine32 library:INCLUDE Irvine32.incPromptForIntegers PROTO,ptrPrompt:PTR BYTE, ; prompt stringptrArray:PTR DWORD, ; points to the arrayarraySize:DWORD ; size of the arrayArraySum PROTO,count:DWORD ; size of the arrayDisplaySum PROTO,theSum:DWORD ; sum of the arrayIrvine, Kip R. Assembly Language for x86 Processors 7/e, 2015.

70 Inspect Individual Modules
MainPromptForIntegersArraySumDisplaySumFunction name mangling / name decorationIrvine, Kip R. Assembly Language for x86 Processors 7/e, 2015.

71 What's Next Stack Frames Recursion INVOKE, ADDR, PROC, and PROTO
Creating Multimodule ProgramsAdvanced Use of Parameters (optional)Java Bytecodes (optional)Irvine, Kip R. Assembly Language for x86 Processors 7/e, 2015.

72 Saving and Restoring Registers
Push registers on stack just after assigning ESP to EBPlocal registers are modified inside the procedureMySub_ PROCpush ebp mov ebp,esp push ecxpush edx mov eax,[ebp+8]; Do something...pop edx pop ecxpop ebpret 4MySub_ ENDPProcedure using explicit stack parameters should avoid the USES operator, if no LOCAL or Proc parameters.Irvine, Kip R. Assembly Language for x86 Processors 6/e, 2010.

73 Stack Affected by USES Operator
MySub1 PROC USES ecx edxpush ebpmov ebp,espmov eax,[ebp+8]; ...retMySub1 ENDPUSES operator generates:MySub1 PROCpush ecxpush edxpush ebpmov ebp,espmov eax,[ebp+8]; ...pop edxpop ecxretWhere is ebp+8 pointing to?ECXSee UsesTest.asmIrvine, Kip R. Assembly Language for x86 Processors 6/e, 2010.

74 Passing 8-bit and 16-bit Arguments
Cannot push 8-bit values on stackPushing 16-bit operand may cause page fault or ESP alignment problemincompatible with Windows API functionsExpand smaller arguments into 32-bit values, using MOVZX or MOVSX:.datacharVal BYTE 'x'.codemovzx eax,charValpush eaxcall UppercaseIrvine, Kip R. Assembly Language for x86 Processors 7/e, 2015.

75 Passing 64-bit Arguments
Push high-order values on the stack first; work backward in memoryResults in little-endian ordering of dataExample:.datalongVal QWORD ABCDEFh.codepush DWORD PTR longVal + 4 ; high doubleword;push DWORD PTR longVal ; low doublewordcall WriteHex64What’s stack memory look like?ef cd abIrvine, Kip R. Assembly Language for x86 Processors 6/e, 2010.

7th

76 Passing 64-bit Arguments, WriteHex64
When passing multiword integers to procedures using the stack, push the highorder part first, working down to the low-order part. Doing so places the integer into the stack in little endian orderWriteHex64 PROCpush ebpmov ebp,espmov eax,[ebp+12] ; high doublewordcall WriteHexmov eax,[ebp+8] ; low doublewordpop ebpret 8WriteHex64 ENDPIrvine, Kip R. Assembly Language for x86 Processors 7/e, Added by Zuoliu Ding.

77 Non-Doubleword Local Variables
Local variables can be different sizesHow created in the stack by LOCAL directive:8-bit: assigned to next available byte16-bit: assigned to next even (word) boundary32-bit: assigned to next doubleword boundaryIrvine, Kip R. Assembly Language for x86 Processors 7/e, 2015.

78 Local Byte VariableExample1 PROCLOCAL var1:BYTEmov al,var ; [EBP - 1]retExample1 ENDPAs stack offsets default to 32 bits, decrement ESP by 4Place var1 at [EBP-1] and leave three bytes below it unused (nu)Irvine, Kip R. Assembly Language for x86 Processors 6/e, 2010.

79 The Microsoft x64 Calling Convention
CALL subtracts 8 from RSPFirst four parameters are placed in RCX, RDX, R8, and R9. Additional parameters are pushed on the stack.Parameters less than 64 bits long are not zero extendedReturn value in RAX if <= 64 bitsCaller must allocate at least 32 bytes of shadow space so the subroutine can copy parameter valuesIrvine, Kip R. Assembly Language for x86 Processors 7/e, 2015.

80 The Microsoft x64 Calling Convention
Caller must align RSP to 16-byte boundaryCaller must remove all parameters from the stack after the callReturn value larger than 64 bits must be placed on the runtime stack, with RCX pointing to itRBX, RBP, RDI, RSI, R12, R14, R14, and R15 registers are preserved by the subroutine; all others are not.Overview of x64 Calling Conventions:Irvine, Kip R. Assembly Language for x86 Processors 7/e, 2015.

81 What's Next Stack Frames Recursion INVOKE, ADDR, PROC, and PROTO
Creating Multimodule ProgramsAdvanced Use of Parameters (optional)Java Bytecodes (optional)Irvine, Kip R. Assembly Language for x86 Processors 7/e, 2015.

82 Java Bytecodes Stack-oriented instruction format
operands are on the stackinstructions pop the operands, process, and push result back on stackEach operation is atomicMight be be translated into native code by a just in time compilerIrvine, Kip R. Assembly Language for x86 Processors 7/e, 2015.

83 Java Virual Machine (JVM)
Essential part of the Java PlatformExecutes compiled bytecodesmachine language of compiled Java programsIrvine, Kip R. Assembly Language for x86 Processors 7/e, 2015.

84 Java Methods Each method has its own stack frame
Areas of the stack frame:local variablesoperandsexecution environmentIrvine, Kip R. Assembly Language for x86 Processors 7/e, 2015.

85 Bytecode Instruction Format
1-byte opcodeiload, istore, imul, goto, etc.zero or more operandsDisassembling Bytecodesuse javap.exe, in the Java Development Kit (JDK)Irvine, Kip R. Assembly Language for x86 Processors 7/e, 2015.

86 Primitive Data TypesSigned integers are in twos complement format, stored in big-endian orderIrvine, Kip R. Assembly Language for x86 Processors 7/e, 2015.

87 JVM Instruction SetComparison Instructions pop two operands off the stack, compare them, and push the result of the comparison back on the stackExamples: fcmp and dcmpIrvine, Kip R. Assembly Language for x86 Processors 7/e, 2015.

88 JVM Instruction Set Conditional Branching Unconditional Branching
jump to label if st(0) <= 0ifle labelUnconditional Branchingcall subroutinejsr labelIrvine, Kip R. Assembly Language for x86 Processors 7/e, 2015.

89 Java Disassembly Examples
Adding Two Integersint A = 3;int B = 2;int sum = 0;sum = A + B;Irvine, Kip R. Assembly Language for x86 Processors 7/e, 2015.

90 Java Disassembly Examples
Adding Two Doublesdouble A = 3.1;double B = 2;double sum = A + B;Irvine, Kip R. Assembly Language for x86 Processors 7/e, 2015.

91 Java Disassembly Examples
Conditional Branchdouble A = 3.0;boolean result = false;if( A > 2.0 )result = false;elseresult = true;Irvine, Kip R. Assembly Language for x86 Processors 7/e, 2015.

92 .NET Assembly in CLRThe .NET Framework provides a run-time environment called the common language runtime, which runs the code and provides .NET services.Assemblies are the building blocks of .NET Framework applications.You can use the Ildasm.exe (MSIL Disassembler) to view Microsoft intermediate language (MSIL) information in a file.Ildasm.exe Tutorial atDemo of Disassembly: A C# console application.Irvine, Kip R. Assembly Language for x86 Processors 6/e, 2010.

93 Summary Stack parameters Local variables
more convenient than register parameterspassed by value or referenceENTER and LEAVE instructionsLocal variablescreated on the stack below stack pointerLOCAL directiveRecursive procedure calls itselfCalling conventions (C, stdcall)MASM procedure-related directivesINVOKE, PROC, PROTOJava Bytecodes – another approch to programmingIrvine, Kip R. Assembly Language for x86 Processors 7/e, 2015.

94 FIrvine, Kip R. Assembly Language for x86 Processors 7/e, 2015.

Presentation on theme: 'Assembly Language for x86 Processors 7th Edition'— Presentation transcript:

1 Assembly Language for x86 Processors 7th Edition
Kip IrvineChapter 1: Basic ConceptsSlides prepared by the authorRevision date: 1/15/2014(c) Pearson Education, All rights reserved. You may modify and copy this slide show for your personal use, or for use in the classroom, as long as this copyright statement, the author's name, and the title are not changed.

2 Chapter Overview Welcome to Assembly Language Virtual Machine Concept
Data RepresentationBoolean OperationsIrvine, Kip R. Assembly Language for Intel-Based Computers 7/e, 2015.

3 Welcome to Assembly Language
Some Good Questions to AskAssembly Language ApplicationsIrvine, Kip R. Assembly Language for Intel-Based Computers 7/e, 2015.

4 Questions to Ask Why am I learning Assembly Language?
What background should I have?What is an assembler?What hardware/software do I need?What types of programs will I create?What do I get with this book?What will I learn?Irvine, Kip R. Assembly Language for Intel-Based Computers 7/e, 2015.

Assembly Language For X86 Processors 7th Edition Pdf Download

5 Welcome to Assembly Language (cont)
How does assembly language (AL) relate to machine language?How do C++ and Java relate to AL?Is AL portable?Why learn AL?Irvine, Kip R. Assembly Language for Intel-Based Computers 7/e, 2015.

6 Assembly Language Applications
Some representative types of applications:Business application for single platformHardware device driverBusiness application for multiple platformsEmbedded systems & computer games(see next panel)Irvine, Kip R. Assembly Language for Intel-Based Computers 7/e, 2015.

7 Comparing ASM to High-Level Languages
Irvine, Kip R. Assembly Language for Intel-Based Computers 7/e, 2015.

8 What's Next Welcome to Assembly Language Virtual Machine Concept
Data RepresentationBoolean OperationsIrvine, Kip R. Assembly Language for Intel-Based Computers 7/e, 2015.

9 Virtual Machine Concept
Virtual MachinesSpecific Machine LevelsIrvine, Kip R. Assembly Language for Intel-Based Computers 7/e, 2015.

10 Virtual Machines Tanenbaum: Virtual machine concept
Programming Language analogy:Each computer has a native machine language (language L0) that runs directly on its hardwareA more human-friendly language is usually constructed above machine language, called Language L1Programs written in L1 can run two different ways:Interpretation – L0 program interprets and executes L1 instructions one by oneTranslation – L1 program is completely translated into an L0 program, which then runs on the computer hardwareIrvine, Kip R. Assembly Language for Intel-Based Computers 7/e, 2015.

11 Translating Languages
English: Display the sum of A times B plus C.C++: cout << (A * B + C);Assembly Language:mov eax,Amul Badd eax,Ccall WriteIntIntel Machine Language:AFEIrvine, Kip R. Assembly Language for Intel-Based Computers 7/e, 2015.

12 Specific Machine Levels
(descriptions of individual levels follow )Irvine, Kip R. Assembly Language for Intel-Based Computers 7/e, 2015.

13 High-Level Language Level 4 Application-oriented languages
C++, Java, Pascal, Visual Basic . . .Programs compile into assembly language (Level 4)Irvine, Kip R. Assembly Language for Intel-Based Computers 7/e, 2015.

14 Assembly Language Level 3
Instruction mnemonics that have a one-to-one correspondence to machine languagePrograms are translated into Instruction Set Architecture Level - machine language (Level 2)Irvine, Kip R. Assembly Language for Intel-Based Computers 7/e, 2015.

15 Instruction Set Architecture (ISA)
Level 2Also known as conventional machine languageExecuted by Level 1 (Digital Logic)Irvine, Kip R. Assembly Language for Intel-Based Computers 7/e, 2015.

16 Digital Logic Level 1 CPU, constructed from digital logic gates
System busMemoryImplemented using bipolar transistorsnext: Data RepresentationIrvine, Kip R. Assembly Language for Intel-Based Computers 7/e, 2015.

17 What's Next Welcome to Assembly Language Virtual Machine Concept
Data RepresentationBoolean OperationsIrvine, Kip R. Assembly Language for Intel-Based Computers 7/e, 2015.

18 Data Representation Binary Numbers Binary Addition
Translating between binary and decimalBinary AdditionInteger Storage SizesHexadecimal IntegersTranslating between decimal and hexadecimalHexadecimal subtractionSigned IntegersBinary subtractionCharacter StorageIrvine, Kip R. Assembly Language for Intel-Based Computers 7/e, 2015.

19 Binary Numbers Digits are 1 and 0 MSB – most significant bit
1 = true0 = falseMSB – most significant bitLSB – least significant bitBit numbering:Irvine, Kip R. Assembly Language for Intel-Based Computers 7/e, 2015.

20 Binary Numbers Every binary number is a sum of powers of 2
Each digit (bit) is either 1 or 0Each bit represents a power of 2:Every binary number is a sum of powers of 2Irvine, Kip R. Assembly Language for Intel-Based Computers 7/e, 2015.

21 Translating Binary to Decimal
Weighted positional notation shows how to calculate the decimal value of each binary bit:dec = (Dn-1  2n-1) + (Dn-2  2n-2) (D1  21) + (D0  20)D = binary digitbinary = decimal 9:(1  23) + (1  20) = 9Irvine, Kip R. Assembly Language for Intel-Based Computers 7/e, 2015.

22 Translating Unsigned Decimal to Binary
Repeatedly divide the decimal integer by 2. Each remainder is a binary digit in the translated value:37 =Irvine, Kip R. Assembly Language for Intel-Based Computers 7/e, 2015.

23 Binary AdditionStarting with the LSB, add each pair of digits, include the carry if present.Irvine, Kip R. Assembly Language for Intel-Based Computers 7/e, 2015.

24 Integer Storage Sizes Standard sizes:
What is the largest unsigned integer that may be stored in 20 bits?Irvine, Kip R. Assembly Language for Intel-Based Computers 7/e, 2015.

25 Hexadecimal Integers Binary values are represented in hexadecimal.
Irvine, Kip R. Assembly Language for Intel-Based Computers 7/e, 2015.

26 Translating Binary to Hexadecimal
Each hexadecimal digit corresponds to 4 binary bits.Example: Translate the binary integer to hexadecimal:Irvine, Kip R. Assembly Language for Intel-Based Computers 7/e, 2015.

27 Converting Hexadecimal to Decimal
Multiply each digit by its corresponding power of 16:dec = (D3  163) + (D2  162) + (D1  161) + (D0  160)Hex 1234 equals (1  163) + (2  162) + (3  161) + (4  160), or decimal 4,660.Hex 3BA4 equals (3  163) + (11 * 162) + (10  161) + (4  160), or decimal 15,268.Irvine, Kip R. Assembly Language for Intel-Based Computers 7/e, 2015.

28 Powers of 16Used when calculating hexadecimal values up to 8 digits long:Irvine, Kip R. Assembly Language for Intel-Based Computers 7/e, 2015.

29 Converting Decimal to Hexadecimal
decimal 422 = 1A6 hexadecimalIrvine, Kip R. Assembly Language for Intel-Based Computers 7/e, 2015.

30 Hexadecimal Addition 36 28 28 6A 42 45 58 4B 78 6D 80 B5
Divide the sum of two digits by the number base (16). The quotient becomes the carry value, and the remainder is the sum digit.11AB78 6D 80 B521 / 16 = 1, rem 5Important skill: Programmers frequently add and subtract the addresses of variables and instructions.Irvine, Kip R. Assembly Language for Intel-Based Computers 7/e, 2015.

31 Hexadecimal Subtraction
When a borrow is required from the digit to the left, add 16 (decimal) to the current digit's value:= 21-1C6 75A2 4724 2EPractice: The address of var1 is The address of the next variable after var1 is A. How many bytes are used by var1?Irvine, Kip R. Assembly Language for Intel-Based Computers 7/e, 2015.

32 Signed IntegersThe highest bit indicates the sign. 1 = negative, 0 = positiveIf the highest digit of a hexadecimal integer is > 7, the value is negative. Examples: 8A, C5, A2, 9DIrvine, Kip R. Assembly Language for Intel-Based Computers 7/e, 2015.

X86

33 Forming the Two's Complement
Negative numbers are stored in two's complement notationRepresents the additive InverseNote that =Irvine, Kip R. Assembly Language for Intel-Based Computers 7/e, 2015.

34 Binary SubtractionWhen subtracting A – B, convert B to its two's complementAdd A to (–B)Practice: Subtract 0101 from 1001.Irvine, Kip R. Assembly Language for Intel-Based Computers 7/e, 2015.

35 Learn How To Do the Following:
Form the two's complement of a hexadecimal integerConvert signed binary to decimalConvert signed decimal to binaryConvert signed decimal to hexadecimalConvert signed hexadecimal to decimalIrvine, Kip R. Assembly Language for Intel-Based Computers 7/e, 2015.

36 Ranges of Signed Integers
The highest bit is reserved for the sign. This limits the range:Practice: What is the largest positive value that may be stored in 20 bits?Irvine, Kip R. Assembly Language for Intel-Based Computers 7/e, 2015.

37 Character Storage Character sets Null-terminated String
Standard ASCII (0 – 127)Extended ASCII (0 – 255)ANSI (0 – 255)Unicode (0 – 65,535)Null-terminated StringArray of characters followed by a null byteUsing the ASCII tableback inside cover of bookIrvine, Kip R. Assembly Language for Intel-Based Computers 7/e, 2015.

38 Numeric Data Representation
pure binarycan be calculated directlyASCII binarystring of digits: ' 'ASCII decimalstring of digits: '65'ASCII hexadecimalstring of digits: '9C'next: Boolean OperationsIrvine, Kip R. Assembly Language for Intel-Based Computers 7/e, 2015.

Assembly Language For X86 Processors 7th Edition Pdf Download Windows 10

39 What's Next Welcome to Assembly Language Virtual Machine Concept
Data RepresentationBoolean OperationsIrvine, Kip R. Assembly Language for Intel-Based Computers 7/e, 2015.

40 Boolean Operations NOT AND OR Operator Precedence Truth Tables
Irvine, Kip R. Assembly Language for Intel-Based Computers 7/e, 2015.

41 Boolean Algebra Based on symbolic logic, designed by George Boole
Boolean expressions created from:NOT, AND, ORIrvine, Kip R. Assembly Language for Intel-Based Computers 7/e, 2015.

42 Digital gate diagram for NOT:
Inverts (reverses) a boolean valueTruth table for Boolean NOT operator:Digital gate diagram for NOT:Irvine, Kip R. Assembly Language for Intel-Based Computers 7/e, 2015.

43 Digital gate diagram for AND:
Truth table for Boolean AND operator:Digital gate diagram for AND:Irvine, Kip R. Assembly Language for Intel-Based Computers 7/e, 2015.

44 Digital gate diagram for OR:
Truth table for Boolean OR operator:Digital gate diagram for OR:Irvine, Kip R. Assembly Language for Intel-Based Computers 7/e, 2015.

45 Operator Precedence Examples showing the order of operations:
Irvine, Kip R. Assembly Language for Intel-Based Computers 7/e, 2015.

46 Truth Tables (1 of 3) Example: X  Y
A Boolean function has one or more Boolean inputs, and returns a single Boolean output.A truth table shows all the inputs and outputs of a Boolean functionExample: X  YIrvine, Kip R. Assembly Language for Intel-Based Computers 7/e, 2015.

47 Truth Tables (2 of 3) Example: X  Y
Irvine, Kip R. Assembly Language for Intel-Based Computers 7/e, 2015.

48 Two-input multiplexer
Truth Tables (3 of 3)Example: (Y  S)  (X  S)Two-input multiplexerIrvine, Kip R. Assembly Language for Intel-Based Computers 7/e, 2015.

49 SummaryAssembly language helps you learn how software is constructed at the lowest levelsAssembly language has a one-to-one relationship with machine languageEach layer in a computer's architecture is an abstraction of a machinelayers can be hardware or softwareBoolean expressions are essential to the design of computer hardware and softwareIrvine, Kip R. Assembly Language for Intel-Based Computers 7/e, 2015.

Assembly Language For X86 Processors 7th Edition Pdf Download Pc

50 What do these numbers represent?
Irvine, Kip R. Assembly Language for Intel-Based Computers 7/e, 2015.