Chapter 5 Branching and Looping Contents: Jump instructions & Loop instructions Implementing loop structures & selective structures Application: Arrays programming
Outcomes Master jump instructions Master loop instructions Master the method of implementing loop structures & selective structures Master the method of programming arrays
Jump instructions (跳转指令) Change the sequences of the codes Implement selective structures and loop structures Two types Unconditional jump Conditional jump
5.1 Unconditional Jumps JMP Statementlable ; target address - >CS:EIP Statementlable : address of other assembly language statement Similar to GOTO JMP quit. quit: INVOKE ExitProcess, 0
Example:5.1 output explain ; initial instructions mov sum,0 ; sum := 0 mov ebx,0 ; count := 0 forever: output prompt ; prompt for number input number,16 ; read ASCII characters atod number ; convert to integer
Example:5.1 add sum,eax ; add number to sum inc ebx ; add 1 to count dtoa value,ebx ; convert count to ASCII output countLabel ; display label for count output value ; display count
Example:5.1 dtoa value,sum ; convert sum to ASCII output sumLabel ; display label for sum output value ; display sum
Example:5.1 mov eax,sum ; get sum cdq ; extend sum to 64 bits idiv ebx ; sum / count dtoa value,eax ; convert average to ASCII output avgLabel ; display label for average output value ; output average
Example:5.1 output nextPrompt ; skip down ; start next prompt jmp forever ; repeat
Jump direction Backward reference (向后跳转) Transfer control to a point that precedes the jmp statement itself. Example5.1 Forward reference (向前跳转) Transfer control to a point that is behind the jmp statement itself. Jmp quit
About JMP instructions … JMP instructions will change the value in the EIP register; Two kinds of JMP instructions Intersegment jump (段间转移) Change CS register Intrasegment jump (段内转移) Not change CS register
Relative jump/direct jump 相对跳转 / 直接转移 Contains the sign displacement of the target from the JMP statement itself. Positive for a forward reference Negative for a backward reference Target address = displacement + addr. of next instruction Target address label is contained in jump instruction. Example: Jmp forever
Displacement size short relative jump (短转移) Displacement is a single byte near relative format (近转移) 32-bit displacement
Indirect jump (间接转移) Use a 32-bit address for the target. Address is stored in a register or in a memory doubleword Example: jmp edx ;edx->EIP Target dword h jmp Target ; [target]->EIP jmp DWORD PTR [ebx] ; [ebx]->EIP
5.2 Conditional JUMP (条件转移) Jcc targetStatement ; target address->EIP cc identifies the condition under which the jump is to be executed. If the condition holds, then the jump takes place; Otherwise, the next instruction is executed. targetStatement must be relative addressing Conditional jump instructions do not modify the flags; they only react to previously set flag values.
mnemonicflagsdescriptionmnemonicflagsdescription JZ/JEZF=1Jump if equal/zeroJNZ/JNEZF=0Jump if not equal/not zero JSSF=1Jump if signJNSSF=0Jump if not sign JP/JPEPF=1Jump if parity/even JNP/JPOPF=0Jump if not parity/odd JOOF=1Jump if overflowJNOOF=0Jump if not overflow JC/JB/JNAECF=1Jump if below/ not above or equal JNC/JNB/JAECF=0Jump if above or equal/not below JBE/JNACF=1 or ZF=1 Jump if below or equal/not above JNBE/JACF=0 & ZF=0 Jump if above/not below or equal JL/JNGE SF O F Jump if less/not greater or equal JNL/JGESF=OFJump if not less/greater or equal JLE/JNGZF=1 or ZF OF Jump if less or equal/ not greater JNLE/JGZF=0 & ZF=OF Jump if not less or equal/greater
Example add value to balance; if balance<0 then … {design for negative banlance} elseif balance=0 then … {design for zro balance} Else … {design for positive balance} End if; add balance, eax jns elseIfZero … jmp endBalanceCheck elseIfZero: jnz elsePos … jmp endBanlanceCheck elsePos: … endBanlanceCheck: Note the begin and end of selective structure.
Set or reset flag Set flag (标志位置位) Give the value 1 to a flag Reset/clear flag (标志位复位) Give the value 0 to a flag Compare instructions are the most common way to establish flag values.
compare instruction CMP operand1, operand2 Calculating operand1 minus operand2, like a SUB instruction Set flags but do not change operand1 Addressing mode is the same as SUB.
Example if eax>100 then jump to Bigger; cmp eax, 100 ja Bigger ;(1) jg Bigger ;(2) Jump or not? EAX= H (1)(2) NOT JUMP EAX= H (1)JUMP (2)NOT JUMP
IF structure if value<10 then add 1 to smallCount; else add 1 to largetCount; endif cmp ebx, 10; value <10 jnl elseLarge inc smallCount jmp endValueCheck elaseLarge: inc lartgeCout endValueCheck:
IF structure(2) if (total>=100) or (count=10) then add value to total; endif cmp total, 100; total <=100? jge addValue cmp cx, 10; count=100? jne endAddCheck addValue: mov ebx, value; copy value add total, ebx ; add value to total endAddCheck:
IF structure(3) if (count>0) and (ch=backspace) then subtract 1 from count; endif cmp cx, 0 ; count>0? jng endCheckCh cmp al, backspace ; ch a backspace? jne endCheckCh dec count ; subtract 1 from count endCheckCh:
5.3 Implementing Loop Structures Loop structures include while, until and for loops. Use jump instructions Use loop instructions while continuation condition loop..{body of loop} end while; for index:=initialValue to finalValue loop..{body of loop} end for; until termination condition loop..{body of loop} end until;
while loop structure while (sum<1000) loop … {body of loop} end while; whileSum: cmp sum, 1000 ; sum<1000? jnl endWhileSum ;exit loop if not … jmp whileSum ; go check condition again endWhileSum:
while loop structure(2) X:=0; twoToX:=1; while twoToX<=number multiply twoToX by 2; add 1 to x; end while; subtract 1 from x mov cx, 0 mov eax, 1 whileLE: cmp eax, number jnle endWhileLE Body: add eax, eax inc cx jmp whileLE endWhileLE: dec cx
while loop structure(3) while (sum<1000) and (count<=24) loop … { body of loop} end while; whileSum: cmp sum, 1000 ; sum<1000? jnl endWhileSum ;exit loop if not cmp cx, 24 ; count<=24 jnle endWhileSum ; exit if not ;body of loop jmp whileSum ; go check condition again endWhileSum:
while loop structure(4) while (sum<1000) or (flag=1) loop … { body of loop} end while; whileSum: cmp eax, 1000 ; sum<1000? jl body ;execute bbody if so cmp dh, 1 ; flag=1? jne endWhileSum ; exit if not ;body of loop jmp whileSum ; go check condition again endWhileSum:
while loop structure(5) sum:=0 while (number keyed in is not negative) loop add number to sum; end while; mov ebx, 0 whileNotNeg: output prompt input number,10 atod number js endwhile add ebx, eax jmp whileSum endWhile:
For loop structure Index:=initialValue while index <=finalValue loop..{body of loop} add 1 to index; end while; for index:=initialValue to finalValue loop..{body of loop} end for;
for loop structure Prompt for tally of numbers; Input tally; Sun:=0 For count:=1 to tally loop Prompt for number; Input number; Add number to sum; End for ; output prompt1 input value, 20 atoi value mov tally, ax mov edx, 0 ; sum:=0 mov bx, 1; count:=1 forCount: cmp bx, tally jnle endfor; exit if not output prompt2 input value, 20 atod value add edx, eax inc bx jmp forCount ;repeat endFor:
until loop structure Count :=0; Until (sum>1000) or (count =100) loop ….{ body of loop} Add 1 to count; End until; mov cx,0;count :=0 Until: ;body of loop inccx;add 1 to count cmp sum, 1000; sum>1000? jg endUntil; exit if sum >1000 cmp cx, 100; count=100? jne until ; continue if count not =100 endUntil:
Loop instructions Loop statementLabel 1. statementLabel is the label of a statement that is a short displacement from the loop instruction. 2. ECX -1->ECX 3. if ECX =0, then execute the statement following the looop instruction 4. if ECX !=0, then a jump to the instruction at statementLabel takes place
For loop structure for count:=20 downto 1 loop … { body of loop} end for mov ecx,20;number of iterations 循环次数 forCount:.. ;body of loop loop forCount ; repeat body 20 times
For loop structure mov ecx,number;number of iterations 循环次数 cmp ecx, 0 je/jecxz endFor; skip loop if number=0 forIndex:.. ;body of loop loop forIndex ; repeat body number times How many times would repeat if ECX=0? 2 32 =
For loop structure for counter := 50 downto 1 loop ….{body of loop} end for; mov ecx, 50; number of iterations forCount: ; body of loop dec ecx;decrement loop counter jecxz endfor; exit if counter =0 jmp forCounter ; otherwise repeat body mov ecx, 50; number of iterations forCount:.; body of loop loop forCount; repeat body 20 times
For loop structure for index:=1 to 50 loop … { body of loop} end for mov ecx,50;number of iterations 循环次数 mov ebx, 1 ; index:=1 forCount:. ;body of loop inc ebx loop forCount ; repeat body 20 times
Conditional loop loopz/loope if ECX!=0 and ZF=1 then loop again loopnz/loopne if ECX!=0 and ZF=0 then loop again
For loop structure for year:=10 downto 1 until balance=0 loop … { body of loop} end for mov ecx,10;maximum number of iterations forYear:. ;body of loop cmp ebx, 0 ;balance=0? loopne forYear ; repeat body 20 times
Other instructions lea destination, source destination will normally be a 32-bit register; source is any reference to memory the address of the source is loaded into the register MOV destination, OFFSET source jecxz targetstatement jump if ecx=0
Game program untilDone: output prompt1 ; ask player 1 for target input stringIn, 20 ; get number atod stringIn ; convert to integer mov target,eax ; store target output clear ; clear screen mov cx, 0 ; zero count
Game program(2) untilMatch: inc cx ; increment count of guesses output prompt2 ; ask player 2 for guess input stringIn, 20 ; get number atod stringIn ; convert to integer cmp eax, target ; compare guess and target jne ifLess ; guess = target ?
Game program(3) equal: output gotItOutput ; display "you got it" jmp endCompare ifLess: jnl isGreater ; guess < target ? output lowOutput ; display "too low" jmp endCompare isGreater: output highOutput ; display "too high"
Game program(4) endCompare: cmp eax, target ; compare guess and target jne untilMatch ; ask again if guess not = target itoa countOut, cx ; convert count to ASCII output countLabel ; display label, count and prompt input stringIn, 20 ; get response cmp stringIn, 'n' ; response = 'n' ? je endUntilDone ; exit if so cmp stringIn, 'N' ; response = 'N' ? jne untilDone ; repeat if not endUntilDone:
Program using array ; input a collection of numbers ; report their average and the numbers which are ;above average output directions ; display directions mov nbrElts,0 ; nbrElts := 0 lea ebx,nbrArray ; get address of nbrArray
Program using array whilePos: output prompt ; prompt for number input number,20 ; get number atod number ; convert to integer jng endWhile ; exit if not positive mov [ebx],eax ; store number in array inc nbrElts ; add 1 to nbrElts add ebx,4 ; get address of next item of array jmp whilePos ; repeat endWhile:
Program using array ; find sum and average mov eax,0 ; sum := 0 lea ebx,nbrArray ; get address of nbrArray mov ecx,nbrElts ; count := nbrElts jecxz quit ; quit if no numbers forCount1: add eax,[ebx] ; add number to sum add ebx,4 ; get address of next item of array loop forCount1 ; repeat nbrElts times
Program using array cdq ; extend sum to quadword idiv nbrElts ; calculate average dtoa outValue,eax ; convert average to ASCII output avgLabel ; print label and average output aboveLabel ; print label for big numbers
Program using array ; display numbers above average lea ebx,nbrArray ; get address of nbrArray mov ecx,nbrElts ; count := nbrElts forCount2: cmp [ebx],eax ; doubleword > average ? jng endIfBig ; continue if average not less dtoa outValue,[ebx] ; convert value from array to ASCII output outValue ; display value endIfBig: add ebx,4 ; get address of next item of array loop forCount2 ; repeat
Exercises P185. Exercises5.5 1, 2, 3,4 P178. Exercises5.4 1, 2 P167. Exercises5.3 1, 2, 3 P157. Exercises5.2 1, 2 P143. Exercises5.1 2