flow control instructions and addressing modes

Download Flow Control Instructions and Addressing Modes

If you can't read please download the document

Upload: nessa

Post on 09-Jan-2016

35 views

Category:

Documents


4 download

DESCRIPTION

Flow Control Instructions and Addressing Modes. Chapter 3. Jumps and Loops. The basic instructions for branching are jumps and loops Loops are instructions to repeat a block of code a certain number of times - PowerPoint PPT Presentation

TRANSCRIPT

  • Flow Control Instructions andAddressing ModesChapter 3

  • Jumps and LoopsThe basic instructions for branching are jumps and loopsLoops are instructions to repeat a block of code a certain number of timesJumps are instructions that branch to a distant labeled instruction when a flag condition is metStatus flags are modified by arithmetic instructions so these are normally used just before a jumpExample: the JNZ (jump if not zero) instruction jumps to the destination-label if ZF = 0. Usage:JNZ destination-label

  • Simple Example Using JNZThis program prints all the lower case letters in increasing orderWe jump to again whenever ZF=0 (when ebx != eax)We do not jump (and execute ret) when ZF=1 (when ebx = eax)The code would be simpler if the sub instruction would not change the value of the destination operandWe do have such an instruction. It is the CMP (compare) instruction. .386.model flatinclude csi2121.inc

    .code main: mov eax,61h ;char 'a'again: mov ebx,7bh ;one after 'z' putch eax inc eax sub ebx,eax jnz again retend

  • The CMP InstructionUsage:cmp destinat,sourcePerforms: destination - source but does not store the result of the subtraction into destinationBut the flags are affected just like SUBSame restrictions on operands as for SUBVery often used just before performing a jump The previous program is now simpler

    .386.model flatinclude csi2121.inc

    .code main:mov eax,61h ;char'a'again:putch eaxinc eaxcmp eax,7bhjnz againretend

  • Single-Flag JumpsThese are jumps where the flag condition consist of a single flag. The following are often used:InstructionDescriptionCondition for Jump

    JZ / JEJump if zeroZF = 1Jump if equalJNZ / JNEJump if not zeroZF = 0Jump if not equalJSJump if negativeSF = 1JNSJump if nonnegativeSF = 0JOJump if overflowOF = 1JNOJump if no overflowOF = 0JCJump if carryCF = 1JNCJump if no carryCF = 0

    Note: sometimes the same instruction has 2 different mnemonics (like JZ and JE)

  • Jumping on a Register ConditionThere exists two jumps where the condition for jumping is given by a register

    The JCXZ instruction jumps if the content of register CX is zero. Usage:JCXZ destination-label

    The JECXZ instruction jumps if the content of register ECX is zero. Usage:JECXZ destination-label

  • Jumping on a Inequality ConditionOften, we need to branch when some value is larger (or smaller) than an other. Ex:CMP eax, ebx;now jump somewhere when eax > ebxHowever, integer order (larger or smaller) depends on the chosen interpretationEx: if AL contains 05h and BL contains A0h. Then:AL > BL for a signed interpretationAL < BL for a unsigned interpretation Hence, we have these two types jumps:Unsigned comparison jumps: for an unsigned interpretation of a comparison used just before the jump (ex: with CMP)Signed comparison jumps: for a signed interpretation of a comparison used just before the jump (ex: with CMP)

  • Unsigned Comparison JumpsInstructionDescription Jump Condition

    JA / JNBEJump if above (if op1>op2) CF=0 and ZF=0Jump if not below or equal

    JAE / JNBJump if above or equal CF=0Jump if not below

    JB / JNAEJump if below (if op1

  • Signed Comparison JumpsInstructionDescription Jump Condition

    JG / JNLEJump if greater (op1>op2) ZF=0 and SF=OFJump if not less or equal

    JGE / JNLJump if greater or equal SF=OFJump if not less

    JL / JNGEJump if less (if op1

  • Using Comparison JumpsCMP is normally used before a comparison jumpEx: to branch to exit when AX > BX under a signed interpretation (ex: AX=1, BX=FFFFh):cmp ax,bxjg exitBut to branch to exit when AX > BX under a unsigned interpretation:cmp ax,bxja exitNote that the jump is not performed when AX=1 and BX =FFFFh

  • Unconditional JumpSometimes we need to jump without any condition

    Just use the JMP instruction. JMP destination.386.model flatinclude csi2121.inc

    .code main: jmp over msg db "hello!",0over: putstr msg retend

  • Application: an Echo ProgramThe input buffer is initially empty. So getch returns only when the user press The macro putch prints the first character entered.When getch is executed again, then the next character in the input buffer is printed.Hence this program echoes on the screen the user string entered on the keyboardBut if the user press , then getch returns 1 in eax and the program exits.Try it!.386.model flatinclude csi2121.inc

    .code main: getch cmp eax,-1 ; ? je exit ;yes then exit putch eax ;no, print char jmp mainexit: retend

  • File Redirection of I/OI/O operations done with macros in csi2121.inc can be redirected to/from files. If the previous (executable) program is called echo1.exe, then echo1 < infile > outfileTakes its input from the file infile and writes its output to the file outfileIf infile is a text file, then outfile will be an identical copybecause getch return 1 when the EOF is reachedBut if infile is a binary file, then outfile will generally not be an identical copy because: getch returns 1 if it reads 1Ah (the ASCII code of ) from infile. So echo1 will exit on the first occurrence of 1Ah in infileWhen getch reads 0Ah, putch will output 0Dh, 0Ah Each 0Dh on input will be ignored by getchThis does not occur in Unix and an equivalent C program that uses getchar() and putchar() can copy any file

  • Exercise 1Without modifying the content of AX, write a sequence of 2 instructions that will transfer the execution to the instruction labeled by L1 when:(a) the signed value of AX is greater than 128(b) the unsigned value of AX is lower or equal to 255(c) AL contains an upper case letter (supposing that AL always contains a letter)(d) AL contains an lower case letter (supposing that AL always contains a letter)

  • High-Level Flow Control StructuresHigh-level languages uses high-level structures such as if-then-else, case, while... to control the flow of executionalgorithms are normally expressed in terms of these high-level structuresProcessors only provide conditional and unconditional jumps and loopsthus we need to decompose the high-level control flow structures into low-level onesWe give here a few examples on how this can be done by using jumps

  • If-Then-ElseHLL ObservationIf Condition { Code-Block-1} else { Code-Block-2}The program branches to Code-Block-2 if Condition is FalseAssembler ObservationJcc Code-Block-2The program branches to Code-Block-2 if cc e.g.,JE or JNZ, is True Therefore HLL not Condition Assembler Jcc

  • If-Then-Else (Continued)Example:if (op1 < op2) thenstatement 1else statement 2end ifAnalysis:there is a conditional jump (JXXX) to else when op1 >= op2there is a unconditional jump (JMP) from end of statement 1 to end_if ASM solution for signed comparison:cmp op1,op2jge else_;statement 1jmp end_ifelse_:;statement 2end_if:Note: else is a ASM reserved word. We use else_ instead

  • WhileExample :

    do while (op1 < op2)statementend do

    Analysis: JXXX to end_do when op1 >= op2JMP from end_do to while ASM solution for an unsigned comparison:

    do_while:cmp op1,op2jae end_do;statementjmp do_whileend_do:

  • CaseExample:

    case input ofA :DestAB :DestBC :DestCend case

    Analysis: CMP and JXXX for each caseASM solution:

    cmp input,Ajne L1JMP DestAL1:cmp input,Bjne L2JMP DestBL2:cmp input,Cjne L3JMP DestCL3:

  • Case (Continued)Example:

    case input ofA :DestAB :DestBC :DestCend case

    Analysis: CMP and JXXX for each caseASM solution 2:

    cmp input,Ajne L1DestA CodeJmp L3L1:cmp input,Bjne L2DestB CodeJmp L3L2:cmp input,Cjne L3DestC CodeL3:

  • The LOOP InstructionLOOP provides the easiest way to repeat a block of statements a specific number of times. Usage: LOOP destination-label

    where the destination-label must precede LOOP by less than 128 bytes of codeThis restriction does not exists for jumps (conditional and unconditional)

    The execution of LOOP produces the following sequence of events:(1) ECX is decremented by 1(2) IF (ECX=0) THEN go to the instruction following LOOP, ELSE go to destination-label

  • The LOOP Instruction (cont.)Example: the following code fragment will print all the ASCII codes by starting with 7Fh: mov ecx,7Fhnext: putch ecx loop nextIf (instead) ECX would be initialized to zero, then:after executing the block for the 1st time, ECX would be decremented by 1 and thus contain 0FFFFFFFFh. the loop would thus be repeated again 0FFFFFFFFh times!!

    Hence, if ECX contains an unspecified value, it is better to write:

    ;a loop to be ;executed ECX times

    jecxz overnext:putch ecxloop nextover:

  • Conditional LoopsLOOPZ and LOOPE continues a loop while ZF=1 and ECX!=0ECX is first decremented, then the condition is tested (a trivial extension of LOOP)LOOPNZ and LOOPNE continues a loop while ZF=0 and ECX != 0Syntax (same as LOOP):loop** dest-labelThe dest-label must precede loop** by < 128 bytesThe following program will print character 20h before exiting

    .386.model flatinclude csi2121.inc

    .code

    main:

    mov ecx,7Fh

    next:putch ecxcmp ecx,20hloopnz nextret

    end

  • Exercise 2Write a small piece of code that will display the character in AL iff it is an uppercase letter

    Write a small piece of code that will count the number of characters in a user input line

  • Addressing ModesOperands specify the data to be used by an instructionAn addressing mode refers to the way in which the data is specified by an operandAn operand is said to be direct when it specifies directly the data to be used by the instruction. This is the case for imm, reg, and mem operands (see previous chapter)An operand is said to be indirect when it specifies the address (in virtual memory) of the data to be used by the instruction To specify to the assembler that an operand is indirect we enclose it between [] Indirect addressing is a necessity when we want to manipulate values that are stored in large arrays because we need then an operand that can index (and run along) the arrayEx: to compute an average of values

  • Register Indirect AddressingWhen a register contains the address of the value that we want to use for an instruction, we can provide [reg] for the operandThis is called register indirect addressingThe register must be 32 bits wide because offset addresses are on 32 bits. Hence, we must use either EAX, EBX, ECX, EDX, ESI, EDI, ESP, EBPEx: Suppose that the double word located at address 100h contains 37A68AF2h. If ESI contains 100h, the next instruction will load EAX with the double word located at address 100h:mov eax,[esi] ;EAX=37A68AF2h (indirect addressing) In contrast, the next instruction will load EAX with the double word contained in ESI: mov eax, esi ;EAX=100h (direct addressing)

  • Getting the Address of a Memory LocationTo use indirect register addressing we need a way to load a register with the address of a memory locationFor this we can use the OFFSET operator. The next instruction loads EAX with the offset address of the memory location named result.dataresult dd 25.codemov eax, offset result;EAX now contains the offset address of resultWe can also use the LEA (load effective address) instruction to perform the same tasklea eax, result;EAX now contains the offset address of resultIn contrast, the following transfers the content of the operand mov eax, result ; EAX = 25

  • Ex: Summing the Elements of an ArrayRegister EBX holds the sumRegister ECX holds the number of elements to sumRegister EAX holds the address of the current double word elementWe say that EAX points to the current double wordADD EBX, [EAX] increases EBX by the number pointed by EAXWhen EAX is increased by 4, it points to the next double wordThe sum is printed byputint ebx.386.model flatinclude csi2121.inc .data arr dd 10,23,45,3,37,66 count dd 6 ;numb of elmts.code main: mov ebx, 0 ;holds the sum mov ecx, count mov eax, offset arrnext: add ebx,[eax] add eax,4 loop next putint ebx retend

  • The Type of an Indirect OperandThe type of an indirect operand is determined by the assembler when it is used in an instruction that needs two operands of the same type. Ex:mov eax,[ebx] ;a double word is movedmov ax,[ebx] ;a word is movedmov [ebx],ah ;a byte is movedHowever, in some cases, the assembler cannot determine the type. Ex:mov [eax],1 ;error Indeed, how many bytes should be moved at the address contained in EAX?Sould we move 01h? or 0001h? or 00000001h ?? Here we need to specify explicitly the type to the assemblerThe PTR operator forces the type of an operand. Hence:mov byte ptr [eax], 1 ;moves 01hmov word ptr [eax], 1 ;moves 0001hmov dword ptr [eax], 1 ;moves 00000001hmov qword ptr [eax], 1 ;error, illegal op. size

  • The LABEL DirectiveIt gives a name and a size to an existing storage location. It does not allocate storage.It must be used in conjunction with byte, word, dword, qword....data val16 label word ;no allocation val32 dd 12345678h ;allocates storage.code mov eax,val32 ;EAX = 12345678h mov ax,val32 ;error mov ax,val16 ;AX = 5678hval16 is just an alias for the first two bytes of the storage location val32

  • Indirect Addressing with DisplacementWe can add a constant (positive or negative) and a variable name to a register indirect operand. These are called displacements.Here are some forms that are permitted: .dataA dw 10,20,30,40,50,60.codemov ebp, offset Amov esi, 2mov ax, [ebp+4] ;AX = 30mov ax, 4[ebp] ;same as abovemov ax, [esi+A] ;AX = 20mov ax, A[esi] ;same as abovemov ax, A[esi+4] ;AX = 40Mov ax, [esi-2+A];AX = 10 We can also multiply by 1, 2, 4, or 8. Ex:mov ax, A[esi*2+2] ;AX = 40

  • Using Indirect Addressing with DisplacementThis is the same program as before for summing the elements of an array

    Except that the loop now contains only this instructionadd ebx,arr[(ecx-1)*4]

    It uses indirect addressing with displacement and a scaling factor

    It should be more efficient than the previous program

    .386.model flatinclude csi2121.inc .data arr dd 10,23,45,3,37,66 count dd 6 ;numb of elmts.code main: mov ebx, 0 ;holds the sum mov ecx, countnext: add ebx,arr[(ecx-1)*4] loop next putint ebx retend

  • Indirect Addressing with Two Registers*We can also use two registers. Ex:.dataA DB 10,20,30,40,50,60.codemov eax, 2mov ebx, 3mov dh, [A+eax+ebx] ;DH = 60mov dh, A[eax+ebx] ;same as abovemov dh, A[eax][ebx] ;same as aboveA two-dimensional array example: .data arr db 10h, 20h, 30h db 0Ah, 0Bh, 0Ch.code mov ebx, 3 ;choose 2nd row mov esi,2 ;choose 3rd column mov al, arr[ebx][esi] ;AL = 0Ch add ebx, offset arr ;EBX = address of arr+3 mov ah, [ebx][esi] ;AH = 0Ch

  • Exercise 3We have the following data segment :.dataYOUdw3421h, 5AC6hMEdd8AF67B11hGiven that MOV ESI, OFFSET YOU has just been executed, write the hexadecimal content of the destination operand immediately after the execution of each instruction below:MOV BH, BYTE PTR [ESI+1] ; BH =MOV BH, BYTE PTR [ESI+2] ; BH = MOV BX, WORD PTR [ESI+6] ; BX =MOV BX, WORD PTR [ESI+1] ; BX = MOV EBX, DWORD PTR [ESI+3] ; EBX =

  • Exercise 4Given the data segment.DATAA DW 1234HB LABEL BYTE DW 5678HC LABEL WORDC1 DB 9AHC2 DB 0BCHTell whether the following instructions are legal, if so give the number movedMOV AX,BMOV AH,BMOV CX,CMOV BX, WORD PTR BMOV DL, WORD PTR CMOV AX, WORD PTR C1MOV BX,[C]MOV BX,C