lecture 11: conditional processing

51
3/17/2003 Lecture 11: Conditional Processing Assembly Language for Intel-Based Computers 4th edition Kip R. Irvine

Upload: oleg

Post on 02-Feb-2016

24 views

Category:

Documents


0 download

DESCRIPTION

Lecture 11: Conditional Processing. Assembly Language for Intel-Based Computers 4th edition Kip R. Irvine. Outline. Defining and Using Procedures Program Design Using Procedures Boolean and Comparison Instructions Conditional Jumps Conditional Loop Instructions Conditional Structures - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Lecture 11:  Conditional Processing

3/17/2003

Lecture 11: Conditional Processing

Assembly Language forIntel-Based Computers

4th editionKip R. Irvine

Page 2: Lecture 11:  Conditional Processing

Outline

• Defining and Using Procedures• Program Design Using Procedures• Boolean and Comparison Instructions• Conditional Jumps• Conditional Loop Instructions• Conditional Structures• Application: Finite-State Machines• Using the .IF Directive

Page 3: Lecture 11:  Conditional Processing

Conditional Jumps

• Jumps Based On . . .– Specific flags– Equality– Unsigned comparisons– Signed Comparisons

• Applications• Encrypting a String• Bit Test (BT) Instruction

Page 4: Lecture 11:  Conditional Processing

Jumps Based on Specific Flags

Page 5: Lecture 11:  Conditional Processing

Jumps Based on Equality

Page 6: Lecture 11:  Conditional Processing

Jumps Based on Unsigned Comparisons

Page 7: Lecture 11:  Conditional Processing

Jumps Based on Signed Comparisons

Page 8: Lecture 11:  Conditional Processing

Exercise

• Write code that jumps to label L1 if either bit 4, 5, or 6 is set in the BL register.

• Write code that jumps to label L1 if bits 4, 5, and 6 are all set in the BL register.

• Write code that jumps to label L2 if AL has even parity.

• Write code that jumps to label L3 if EAX is negative.

• Write code that jumps to label L4 if the expression (EBX – ECX) is greater than zero.

Page 9: Lecture 11:  Conditional Processing

Ex: checking for alphabetic input

• The Isalpha procedure sets ZF to 1 iff the character in AL is alphabetic (upper or lower case). – When comparing characters: use unsigned

comparison jumps– Trick: clear bit #5 and check if ‘A’ <= char <= ‘Z’

(converts lower case to upper case)– cmp al, ‘A’ will clear ZF when char < ‘A’ – cmp al, ‘Z’ will clear ZF when char > ‘Z’– test ax, 0 is executed only if

‘A’ <= char <= ‘Z’ and sets ZF to 1

Page 10: Lecture 11:  Conditional Processing

The Isalpha Procedure

; Isalpha sets ZF = 1 iff the character; in AL is alphabetic.

Isalpha proc push ax ; save AX and al,11011111b ; clear bit 5 cmp al,'A' ; check 'A'..'Z' range jb B1 cmp al,'Z' ja B1 test ax,0 ; ZF = 1 B1: pop ax ; restore AX retIsalpha endp

Page 11: Lecture 11:  Conditional Processing

Ex: file encryption

• The following property of XOR b XOR 0 = b (bit b is conserved) b XOR 1 = NOT(b) (bit b is complemented)can be used to encrypt files

• If a character is stored in AL, XORing AL once encrypts the character. Using it the second time decrypts (restores) the character. – key = 137 ;a 1-byte secret key– xor al,key ;AL is encrypted– xor al,key ;AL is restored to its original value

Page 12: Lecture 11:  Conditional Processing

Encrypting a String

KEY = 239.databuffer BYTE BUFMAX DUP(0)bufSize DWORD ?.code

mov ecx,bufSize ; loop countermov esi,0 ; index 0 in buffer

L1:xor buffer[esi],KEY ; translate a byteinc esi ; point to next byteloop L1

The following loop uses the XOR instruction to transform every character in a string into a new value.

Page 13: Lecture 11:  Conditional Processing

String Encryption Program

• Tasks:– Input a message (string) from the user– Encrypt the message– Display the encrypted message– Decrypt the message– Display the decrypted message

View the Encrypt.asm program's source code. Sample output:

Enter the plain text: Attack at dawn.

Cipher text: «¢¢Äîä-Ä¢-ïÄÿü-Gs

Decrypted: Attack at dawn.

Page 14: Lecture 11:  Conditional Processing

BT (Bit Test) Instruction

• Copies bit n from an operand into the Carry flag• Syntax: BT bitBase, n

– bitBase may be r/m16 or r/m32– n may be r16, r32, or imm8

• Example: jump to label L1 if bit 9 is set in the AX register:

bt AX,9 ; CF = bit 9jc L1 ; jump if Carry

Page 15: Lecture 11:  Conditional Processing

Conditional Loop Instructions

• LOOPZ and LOOPE• LOOPNZ and LOOPNE

Page 16: Lecture 11:  Conditional Processing

LOOPZ and LOOPE

• Syntax: LOOPE destinationLOOPZ destination

• Logic: – ECX ECX – 1– if ECX > 0 and ZF=1, jump to destination

• Useful when scanning an array for the first element that does not match a given value.

Page 17: Lecture 11:  Conditional Processing

LOOPNZ and LOOPNE

• LOOPNZ (LOOPNE) is a conditional loop instruction• Syntax:

LOOPNZ destinationLOOPNE destination

• Logic: – ECX ECX – 1; – if ECX > 0 and ZF=0, jump to destination

• Useful when scanning an array for the first element that matches a given value.

Page 18: Lecture 11:  Conditional Processing

LOOPNZ Example

.dataarray SWORD -3,-6,-1,-10,10,30,40,4sentinel SWORD 0.code

mov esi,OFFSET arraymov ecx,LENGTHOF array

next:test WORD PTR [esi],8000h ; test sign bitpushfd ; push flags on stackadd esi,TYPE arraypopfd ; pop flags from stackloopnz next ; continue loopjnz quit ; none foundsub esi,TYPE array ; ESI points to value

quit:

The following code finds the first positive value in an array:

Page 19: Lecture 11:  Conditional Processing

Exercise

.dataarray SWORD 50 DUP(?)sentinel SWORD 0FFFFh.code

mov esi,OFFSET arraymov ecx,LENGTHOF array

L1: cmp WORD PTR [esi],0 ; check for zero

(fill in your code here)

quit:

Locate the first nonzero value in the array. If none is found, let ESI point to the sentinel value:

Page 20: Lecture 11:  Conditional Processing

. . . (solution)

.dataarray SWORD 50 DUP(?)sentinel SWORD 0FFFFh.code

mov esi,OFFSET arraymov ecx,LENGTHOF array

L1: cmp WORD PTR [esi],0 ; check for zeropushfd ; push flags on stackadd esi,TYPE arraypopfd ; pop flags from stackloope L1 ; continue loopjz quit ; none foundsub esi,TYPE array ; ESI points to value

quit:

Page 21: Lecture 11:  Conditional Processing

Conditional Structures

• Block-Structured IF Statements• Compound Expressions with AND• Compound Expressions with OR• WHILE Loops• Table-Driven Selection

Page 22: Lecture 11:  Conditional Processing

Block-Structured IF Statements

Assembly language programmers can easily translate logical statements written in C++/Java into assembly language. For example:

mov eax,op1cmp eax,op2jne L1mov X,1jmp L2

L1: mov X,2L2:

if( op1 == op2 ) X = 1;else X = 2;

Page 23: Lecture 11:  Conditional Processing

Exercise

Implement the following pseudocode in assembly language. All values are unsigned:

cmp ebx,ecxja nextmov eax,5mov edx,6

next:

if( ebx <= ecx ){ eax = 5; edx = 6;}

(There are multiple correct solutions to this problem.)

Page 24: Lecture 11:  Conditional Processing

Exercise

Implement the following pseudocode in assembly language. All values are 32-bit signed integers:

mov eax,var1cmp eax,var2jle L1mov var3,6mov var4,7jmp L2

L1: mov var3,10L2:

if( var1 <= var2 ) var3 = 10;else{ var3 = 6; var4 = 7;}

(There are multiple correct solutions to this problem.)

Page 25: Lecture 11:  Conditional Processing

Compound Expression with AND (1 of 3)

• When implementing the logical AND operator, consider that HLLs use short-circuit evaluation

• In the following example, if the first expression is false, the second expression is skipped:

if (al > bl) AND (bl > cl) X = 1;

Page 26: Lecture 11:  Conditional Processing

Compound Expression with AND (2 of 3)

cmp al,bl ; first expression...ja L1jmp next

L1:cmp bl,cl ; second expression...ja L2jmp next

L2: ; both are truemov X,1 ; set X to 1

next:

if (al > bl) AND (bl > cl) X = 1;

This is one possible implementation . . .

Page 27: Lecture 11:  Conditional Processing

Compound Expression with AND (3 of 3)

cmp al,bl ; first expression...jbe next ; quit if falsecmp bl,cl ; second expression...jbe next ; quit if falsemov X,1 ; both are true

next:

if (al > bl) AND (bl > cl) X = 1;

But the following implementation uses 29% less code by reversing the first relational operator. We allow the program to "fall through" to the second expression:

Page 28: Lecture 11:  Conditional Processing

Exercise

Implement the following pseudocode in assembly language. All values are unsigned:

cmp ebx,ecxja nextcmp ecx,edxjbe nextmov eax,5mov edx,6

next:

if( ebx <= ecx && ecx > edx )

{ eax = 5; edx = 6;}

(There are multiple correct solutions to this problem.)

Page 29: Lecture 11:  Conditional Processing

Compound Expression with OR (1 of 2)

• When implementing the logical OR operator, consider that HLLs use short-circuit evaluation

• In the following example, if the first expression is true, the second expression is skipped:

if (al > bl) OR (bl > cl) X = 1;

Page 30: Lecture 11:  Conditional Processing

Compound Expression with OR (1 of 2)

cmp al,bl ; is AL > BL?ja L1 ; yescmp bl,cl ; no: is BL > CL?jbe next ; no: skip next statement

L1: mov X,1 ; set X to 1next:

if (al > bl) OR (bl > cl) X = 1;

We can use "fall-through" logic to keep the code as short as possible:

Page 31: Lecture 11:  Conditional Processing

WHILE Loops

while( eax < ebx)eax = eax + 1;

A WHILE loop is really an IF statement followed by the body of the loop, followed by an unconditional jump to the top of the loop. Consider the following example:

top:cmp eax,ebx ; check loop conditionjae next ; false? exit loopinc eax ; body of loopjmp top ; repeat the loop

next:

This is a possible implementation:

Page 32: Lecture 11:  Conditional Processing

Exercise

top:cmp ebx,val1 ; check loop conditionja next ; false? exit loopadd ebx,5 ; body of loopdec val1jmp top ; repeat the loop

next:

while( ebx <= val1){

ebx = ebx + 5;val1 = val1 - 1

}

Implement the following loop, using unsigned 32-bit integers:

Page 33: Lecture 11:  Conditional Processing

Table-Driven Selection (1 of 3)

• Table-driven selection uses a table lookup to replace a multiway selection structure

• Create a table containing lookup values and the offsets of labels or procedures

• Use a loop to search the table• Suited to a large number of comparisons

Page 34: Lecture 11:  Conditional Processing

Table-Driven Selection (2 of 3)

.dataCaseTable BYTE 'A' ; lookup value

DWORD Process_A ; address of procedureEntrySize = ($ - CaseTable)BYTE 'B'DWORD Process_BBYTE 'C'DWORD Process_CBYTE 'D'DWORD Process_D

NumberOfEntries = ($ - CaseTable) / EntrySize

Step 1: create a table containing lookup values and procedure offsets:

Page 35: Lecture 11:  Conditional Processing

Table-Driven Selection (3 of 3)

mov ebx,OFFSET CaseTable ; point EBX to the tablemov ecx,NumberOfEntries ; loop counter

L1: cmp al,[ebx] ; match found?jne L2 ; no: continuecall NEAR PTR [ebx + 1] ; yes: call the procedurejmp L3 ; and exit the loop

L2: add ebx,EntrySize ; point to next entryloop L1 ; repeat until ECX = 0

L3:

Step 2: Use a loop to search the table. When a match is found, we call the procedure offset stored in the current table entry:

required for procedure pointers

Page 36: Lecture 11:  Conditional Processing

Application: Finite-State Machines

• A finite-state machine (FSM) is a graph structure that changes state based on some input. Also called a state-transition diagram.

• We use a graph to represent an FSM, with squares or circles called nodes, and lines with arrows between the circles called edges (or arcs).

• A FSM is a specific instance of a more general structure called a directed graph (or digraph).

• Three basic states, represented by nodes:– Start state– Terminal state(s)– Nonterminal state(s)

Page 37: Lecture 11:  Conditional Processing

Finite-State Machine

• Accepts any sequence of symbols that puts it into an accepting (final) state

• Can be used to recognize, or validate a sequence of characters that is governed by language rules (called a regular expression)

• Advantages:– Provides visual tracking of program's flow of

control– Easy to modify– Easily implemented in assembly language

Page 38: Lecture 11:  Conditional Processing

FSM Examples

• FSM that recognizes strings beginning with 'x', followed by letters 'a'..'y', ending with 'z':

• FSM that recognizes signed integers:

Page 39: Lecture 11:  Conditional Processing

Exercise

• Explain why the following FSM does not work as well for signed integers as the one shown on the previous slide:

startdigit

+,-A B

digit

Page 40: Lecture 11:  Conditional Processing

Implementing an FSM

StateA:call Getnext ; read next char into ALcmp al,'+' ; leading + sign?je StateB ; go to State Bcmp al,'-' ; leading - sign?je StateB ; go to State Bcall IsDigit ; ZF = 1 if AL = digitjz StateC ; go to State Ccall DisplayErrorMsg ; invalid input foundjmp Quit

The following is code from State A in the Integer FSM:

View the Finite.asm source code.

Page 41: Lecture 11:  Conditional Processing

Flowchart of State A

State A accepts a plus or minus sign, or a decimal digit.

Page 42: Lecture 11:  Conditional Processing

Mealy Machine

• An output is associated with each transitionEx. The successor function for binary numbers. Use the standard addition algorithm with carry. Assume the input is the binary number in reverse order.

Start 0

0/1

11/0

1/0

0/01/12

0/1

Page 43: Lecture 11:  Conditional Processing

Exercise

• Implement a Mealy machine that identifies substring 1011 from the input

Page 44: Lecture 11:  Conditional Processing

Using the .IF Directive

• Runtime Expressions• Relational and Logical

Operators• MASM-Generated Code• .REPEAT Directive• .WHILE Directive

Page 45: Lecture 11:  Conditional Processing

Runtime Expressions

.IF eax > ebxmov edx,1

.ELSEmov edx,2

.ENDIF

• .IF, .ELSE, .ELSEIF, and .ENDIF can be used to evaluate runtime expressions and create block-structured IF statements.

• Examples:

• MASM generates "hidden" code for you, consisting of code labels, CMP and conditional jump instructions.

.IF eax > ebx && eax > ecxmov edx,1

.ELSEmov edx,2

.ENDIF

Page 46: Lecture 11:  Conditional Processing

Relational and Logical Operators

Page 47: Lecture 11:  Conditional Processing

MASM-Generated Code

mov eax,6cmp eax,val1jbe @C0001 mov result,1

@C0001:

.dataval1 DWORD 5result DWORD ?.codemov eax,6.IF eax > val1mov result,1.ENDIF

Generated code:

MASM automatically generates an unsigned jump (JBE).

Page 48: Lecture 11:  Conditional Processing

MASM-Generated Code

mov eax,6cmp eax,val1jle @C0001 mov result,1

@C0001:

.dataval1 SDWORD 5result SDWORD ?.codemov eax,6.IF eax > val1mov result,1.ENDIF

Generated code:

MASM automatically generates a signed jump (JLE).

Page 49: Lecture 11:  Conditional Processing

.REPEAT Directive

; Display integers 1 – 10:

mov eax,0.REPEAT

inc eaxcall WriteDeccall Crlf

.UNTIL eax == 10

Executes the loop body before testing the loop condition associated with the .UNTIL directive.

Example:

Page 50: Lecture 11:  Conditional Processing

.WHILE Directive

; Display integers 1 – 10:

mov eax,0.WHILE eax < 10

inc eaxcall WriteDeccall Crlf

.ENDW

Tests the loop condition before executing the loop body The .ENDW directive marks the end of the loop.

Example:

Page 51: Lecture 11:  Conditional Processing

• CSCE 380• Department of Computer Science

and Computer Engineering• Pacific Lutheran University• 3/17/2003