Lecture 6 Conditional Processing Assembly Language for IntelBased
Lecture 6 Conditional Processing Assembly Language for Intel-Based Computers, 4 th edition Kip R. Irvine 1
Outline n n 2 Boolean and Comparison Instructions Conditional Jumps Conditional Loops High-Level Logic Structures
Logic Instructions n n n 3 Syntax for AND, OR, XOR, and TEST: op-code destination, source AND, OR and XOR perform the Boolean bitwise operation and store the result into destination. TEST is just an AND but the result is not stored Both operands must be of the same type u either byte, word or doubleword Both operands cannot be memory at same time u again: memory to memory operations are forbidden They modify OF, CF, SF, ZF, PF according to the result of the operation (as usual)
Logic Instructions (cont. ) n n The source is often an immediate operand called a bit mask: used to fix certain bits to 0 or 1 To clear a bit we use an AND since: u 0 AND b = 0 (b is cleared) u 1 AND b = b (b is conserved) n Ex: to clear the sign bit of AL without affecting the others, we do: al, 7 Fh ; msb of AL is cleared since 7 Fh = 0111 1111 b u AND 4
Logic Instructions (cont. ) n To set (ie: set to 1) certain bits, we use OR: u 1 OR b = 1 u 0 OR b = b n To set the sign bit of AH, we do: u OR n (b is set) (b is conserved) ah, 80 h To test if ECX=0 we can do: u OR ecx, ecx u since this does not change the number in ECX and set ZF=1 if and only if ecx=0 5
Logic Instructions (cont. ) n XOR can be used to complement, conserve, or clear certain bits because: ub XOR 1 = NOT(b) (b is complemented) u b XOR 0 = b (b is conserved) u b XOR b = 0 (b is cleared) n Ex: to initialize a register to 0 we can use a two-byte instruction: u XOR ax, ax u instead of the three-byte instruction: u MOV ax, 0 This was faster on 8088's 6
Logic Instructions (cont. ) n n n 7 Using OR and XOR in strange ways: XOR ax, ax MOV ax, 0 OR ax, ax CMP ax, 0 bytes 2 3 86/88 3 cycles 4 cycles 286 2 cycles 386 2 cycles 486 1 cycle Machine code 33 C 0 0 B C 0 B 8 0000 83 F 8 00
Logic Instructions (cont. ) n n To convert from upper case to lower case we can use the usual method: u ADD dl, 20 h Bit 5 But 8 0100 0001 b 0110 0001 b dl, 20 h ; converts from upper to lower case u AND dl, 0 DFh ; converts from lower to upper case since DFh = 1101 1111 b OR dl, 20 h and AND dh, 20 h leaves lower case characters in dl unchanged and upper case characters in dh unchanged u OR n "A" = "a" =
Logic Instructions (cont. ) n To invert all the bits (ones complement): NOT destination u does not affect any flag and destination cannot be an immediate operand n Reflection u 9 What are the easiest ways to clearing or setting individual CPU flags?
The CMP instruction CMP destination, source n n n 10 Performs: destination - source but does not store the result of this subtraction into destination But the flags are affected like SUB Same restrictions on operands as SUB Very often used just before performing a conditional jump CMP is similar to TEST except TEST does AND operation
Conditional Jumps n Jumps Based On. . . u. Specific flags u. Equality u. Unsigned comparisons u. Signed Comparisons n n n 11 Applications Encrypting a String Bit Test (BT) Instruction
Jcond Instruction n n A conditional jump instruction branches to a label when specific register or flag conditions are met Examples: JB, JC jump to a label if the Carry flag is set u JE, JZ jump to a label if the Zero flag is set u JS jumps to a label if the Sign flag is set u JNE, JNZ jump to a label if the Zero flag is clear u JECXZ jumps to a label if ECX equals 0 u 12
Jumps Based on Specific Flags 13
Jumps Based on Equality 14
Jumps Based on Unsigned Comparisons 15
Jumps Based on Signed Comparisons 16
Applications (1 of 5) • Task: Jump to a label if unsigned EAX is greater than EBX • Solution: Use CMP, followed by JA cmp eax, ebx ja Larger • Task: Jump to a label if signed EAX is greater than EBX • Solution: Use CMP, followed by JG cmp eax, ebx jg Greater 17
Applications (2 of 5) • Jump to label L 1 if unsigned EAX is less than or equal to Val 1 cmp eax, Val 1 jbe L 1 ; below or equal • Jump to label L 1 if signed EAX is less than or equal to Val 1 cmp eax, Val 1 jle L 1 18
Applications (3 of 5) • Compare unsigned AX to BX, and copy the larger of the two into a variable named Large mov cmp jna mov Next: Large, bx ax, bx Next Large, ax • Compare signed AX to BX, and copy the smaller of the two into a variable named Small mov cmp jnl mov Next: 19 Small, ax bx, ax Next Small, bx
Applications (4 of 5) • Jump to label L 1 if the memory word pointed to by ESI equals Zero cmp WORD PTR [esi], 0 je L 1 • Jump to label L 2 if the doubleword in memory pointed to by EDI is even test DWORD PTR [edi], 1 jz L 2 20
Applications (5 of 5) • Task: Jump to label L 1 if bits 0, 1, and 3 in AL are all set. • Solution: Clear all bits except bits 0, 1, and 3. Then compare the result with 00001011 binary. and al, 00001011 b cmp al, 00001011 b je L 1 21 ; clear unwanted bits ; check remaining bits ; all set? jump to L 1
Your turn. . . n n n 22 Write code that jumps to label L 1 if either bit 4, 5, or 6 is set in the BL register. Write code that jumps to label L 1 if bits 4, 5, and 6 are all set in the BL register. Write code that jumps to label L 3 if EAX is negative.
Encrypting a String The following loop uses the XOR instruction to transform every character in a string into a new value. KEY = 239 ; can be any byte value BUFMAX = 128. data buffer BYTE BUFMAX+1 DUP(0) buf. Size DWORD BUFMAX. code mov ecx, buf. Size mov esi, 0 L 1: xor buffer[esi], KEY inc esi loop L 1 23 ; loop counter ; index 0 in buffer ; translate a byte ; point to next byte
String Encryption Program n Tasks: u Input a message (string) from the user u Encrypt the message u Display the encrypted message u Decrypt the message u 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. 24
Conditional Loop Instructions n n 25 LOOPZ and LOOPE LOOPNZ and LOOPNE
LOOPZ and LOOPE n n n 26 Syntax: LOOPE destination LOOPZ destination Logic: u ECX – 1 u 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.
LOOPNZ and LOOPNE n n n LOOPNZ (LOOPNE) is a conditional loop instruction Syntax: LOOPNZ destination LOOPNE destination Logic: ECX – 1; u if ECX > 0 and ZF=0, jump to destination u n 27 Useful when scanning an array for the first element that matches a given value.
LOOPNZ Example The following code finds the first positive value in an array: . data array SWORD -3, -6, -10, 10, 30, 4 sentinel SWORD 0. code mov esi, OFFSET array mov ecx, LENGTHOF array next: test WORD PTR [esi], 8000 h ; test sign bit pushfd ; push flags on stack add esi, TYPE array popfd ; pop flags from stack loopnz next ; continue loop jnz quit ; none found sub esi, TYPE array ; ESI points to value quit: 28
Your turn. . . Locate the first nonzero value in the array. If none is found, let ESI point to the sentinel value: . data array SWORD 50 DUP(? ) sentinel SWORD 0 FFFFh. code mov esi, OFFSET array mov ecx, LENGTHOF array L 1: cmp WORD PTR [esi], 0 (fill in your code here) quit: 29 ; check for zero
. . . (solution). data array SWORD 50 DUP(? ) sentinel SWORD 0 FFFFh. code mov esi, OFFSET array mov ecx, LENGTHOF array L 1: cmp WORD PTR [esi], 0 pushfd add esi, TYPE array popfd loope L 1 jz quit sub esi, TYPE array quit: 30 ; check for zero ; push flags on stack ; ; pop flags from stack continue loop none found ESI points to value
Conditional Structures 31 • Block-Structured IF Statements • Compound Expressions with AND • Compound Expressions with OR • WHILE Loops • Table-Driven Selection
Block-Structured IF Statements Assembly language programmers can easily translate logical statements written in C++/Java into assembly language. For example: if( op 1 == op 2 ) X = 1; else X = 2; 32 mov cmp jne mov jmp L 1: mov L 2: eax, op 1 eax, op 2 L 1 X, 1 L 2 X, 2
Your turn. . . Implement the following pseudocode in assembly language. All values are unsigned: if( ebx <= ecx ) { eax = 5; edx = 6; } cmp ja mov next: ebx, ecx next eax, 5 edx, 6 (There are multiple correct solutions to this problem. ) 33
Your turn. . . Implement the following pseudocode in assembly language. All values are 32 -bit signed integers: if( var 1 var 3 = else { var 3 = var 4 = } <= var 2 ) 10; 6; 7; mov cmp jle mov jmp L 1: mov L 2: eax, var 1 eax, var 2 L 1 var 3, 6 var 4, 7 L 2 var 3, 10 (There are multiple correct solutions to this problem. ) 34
Compound Expression with AND (1 of 3) n n 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; 35
Compound Expression with AND (2 of 3) if (al > bl) AND (bl > cl) X = 1; This is one possible implementation. . . cmp al, bl ja L 1 jmp next ; first expression. . . cmp bl, cl ja L 2 jmp next ; second expression. . . L 1: L 2: mov X, 1 next: 36 ; both are true ; set X to 1
Compound Expression with AND (3 of 3) 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: cmp jbe mov next: 37 al, bl next bl, cl next X, 1 ; ; ; first expression. . . quit if false second expression. . . quit if false both are true
Your turn. . . Implement the following pseudocode in assembly language. All values are unsigned: if( ebx <= ecx && ecx > edx ) { eax = 5; edx = 6; } cmp ja cmp jbe mov next: ebx, ecx next ecx, edx next eax, 5 edx, 6 (There are multiple correct solutions to this problem. ) 38
Compound Expression with OR (1 of 2) n n 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; 39
Compound Expression with OR (1 of 2) if (al > bl) OR (bl > cl) X = 1; We can use "fall-through" logic to keep the code as short as possible: cmp ja cmp jbe L 1: mov next: 40 al, bl L 1 bl, cl next X, 1 ; ; ; is AL > BL? yes no: is BL > CL? no: skip next statement set X to 1
WHILE Loops 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: while( eax < ebx) eax = eax + 1; This is a possible implementation: top: cmp jae inc jmp next: 41 eax, ebx next eax top ; ; check loop condition false? exit loop body of loop repeat the loop
Your turn. . . Implement the following loop, using unsigned 32 -bit integers: while( ebx <= val 1) { ebx = ebx + 5; val 1 = val 1 - 1 } top: cmp ja add dec jmp next: 42 ebx, val 1 next ebx, 5 val 1 top ; check loop condition ; false? exit loop ; body of loop ; repeat the loop
Using the. IF Directive n n n 43 Runtime Expressions Relational and Logical Operators MASM-Generated Code. REPEAT Directive. WHILE Directive
Runtime Expressions • . IF, . ELSEIF, and. ENDIF can be used to evaluate runtime expressions and create block-structured IF statements. • Examples: . IF eax > ebx mov edx, 1. ELSE mov edx, 2. ENDIF . IF eax > ebx && eax > ecx mov edx, 1. ELSE mov edx, 2. ENDIF • MASM generates "hidden" code for you, consisting of code labels, CMP and conditional jump instructions. 44
Relational and Logical Operators 45
MASM-Generated Code. data val 1 DWORD 5 result DWORD ? . code mov eax, 6. IF eax > val 1 mov result, 1. ENDIF Generated code: mov eax, 6 cmp eax, val 1 jbe @C 0001 mov result, 1 @C 0001: MASM automatically generates an unsigned jump (JBE) because val 1 is unsigned. 46
MASM-Generated Code. data val 1 SDWORD 5 result SDWORD ? . code mov eax, 6. IF eax > val 1 mov result, 1. ENDIF Generated code: mov eax, 6 cmp eax, val 1 jle @C 0001 mov result, 1 @C 0001: MASM automatically generates a signed jump (JLE) because val 1 is signed. 47
MASM-Generated Code. data result DWORD ? . code mov ebx, 5 mov eax, 6. IF eax > ebx mov result, 1. ENDIF Generated code: mov ebx, 5 mov eax, 6 cmp eax, ebx jbe @C 0001 mov result, 1 @C 0001: MASM automatically generates an unsigned jump (JBE) when both operands are registers. . . 48
MASM-Generated Code. data result SDWORD ? . code mov ebx, 5 mov eax, 6. IF SDWORD PTR eax > ebx mov result, 1. ENDIF Generated code: mov ebx, 5 mov eax, 6 cmp eax, ebx jle @C 0001 mov result, 1 @C 0001: . . . unless you prefix one of the register operands with the SDWORD PTR operator. Then a signed jump is generated. 49
. REPEAT Directive Executes the loop body before testing the loop condition associated with the. UNTIL directive. Example: ; Display integers 1 – 10: mov eax, 0. REPEAT inc eax call Write. Dec call Crlf. UNTIL eax == 10 50
. WHILE Directive Tests the loop condition before executing the loop body The. ENDW directive marks the end of the loop. Example: ; Display integers 1 – 10: mov eax, 0. WHILE eax < 10 inc eax call Write. Dec call Crlf. ENDW 51
Macros n n n 52 Introducing Macros Defining Macros Invoking Macros Macro Examples Nested Macros Example Program: Wrappers
Introducing Macros n n A macro 1 is a named block of assembly language statements. Once defined, it can be invoked (called) one or more times. During the assembler's preprocessing step, each macro call is expanded into a copy of the macro. The expanded code is passed to the assembly step, where it is checked for correctness. 1 Also 53 called a macro procedure.
Defining Macros • A macro must be defined before it can be used. • Parameters are optional. • • Each parameter follows the rules for identifiers. It is a string that is assigned a value when the macro is invoked. Syntax: macroname MACRO [parameter-1, parameter-2, . . . ] statement-list ENDM 54
m. New. Line Macro Example This is how you define and invoke a simple macro. m. New. Line MACRO call Crlf ENDM. data. code m. New. Line ; define the macro ; invoke the macro The assembler will substitute "call crlf" for "m. New. Line". 55
m. Put. Char Macro Writes a single character to standard output. Definition: Invocation: Expansion: 56 m. Putchar MACRO char push eax mov al, char call Write. Char pop eax ENDM. code m. Putchar 'A' 1 1 push eax mov al, 'A' call Write. Char pop eax viewed in the listing file
Invoking Macros (1 of 2) n n 57 When you invoke a macro, each argument you pass matches a declared parameter. Each parameter is replaced by its corresponding argument when the macro is expanded. When a macro expands, it generates assembly language source code. Arguments are treated as simple text by the preprocessor.
Invoking Macros (2 of 2) Relationships between macros, arguments, and parameters: 58
m. Write. Str Macro (1 of 2) Provides a convenient way to display a string, by passing the string name as an argument. m. Write. Str MACRO buffer push edx mov edx, OFFSET buffer call Write. String pop edx ENDM. data str 1 BYTE "Welcome!", 0. code m. Write. Str str 1 59
m. Write. Str Macro (2 of 2) The expanded code shows how the str 1 argument replaced the parameter named buffer: 60 m. Write. Str push mov call pop ENDM MACRO buffer edx, OFFSET buffer Write. String edx 1 1 edx, OFFSET str 1 Write. String edx push mov call pop
Invalid Argument n n If you pass an invalid argument, the error is caught when the expanded code is assembled. Example: m. Putchar MACRO char push eax mov al, char call Write. Char pop eax ENDM . code m. Putchar 1234 h 61 1 1 push eax mov al, 1234 h call Write. Char pop eax ; error!
Blank Argument n n If you pass a blank argument, the error is also caught when the expanded code is assembled. Example: m. Putchar MACRO char push eax mov al, char call Write. Char pop eax ENDM . code m. Putchar 62 1 1 push eax mov al, call Write. Char pop eax
Your turn. . . n Write a macro named m. Move 32 that receives two 32 -bit memory operands. The macro should move the source operand to the destination operand. . Solution m. Move 32 MACRO destination, source push eax mov eax, source mov destination, eax pop eax ENDM 63
- Slides: 63