Chapter 5 Branching and Looping Contents: Jump instructions & Loop instructions Implementing loop...
-
date post
19-Dec-2015 -
Category
Documents
-
view
232 -
download
1
Transcript of Chapter 5 Branching and Looping Contents: Jump instructions & Loop instructions Implementing loop...
Chapter 5 Branching and Looping
Contents:Jump instructions & Loop instructionsImplementing loop structures & selective structuresApplication: 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 GOTOJMP quit
.
.quit: INVOKE ExitProcess, 0
Example:5.1
output explain ; initial instructions mov sum,0 ; sum := 0 mov ebx,0 ; count := 0forever: 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 ASCIIoutput sumLabel ; display label for sumoutput value ; display sum
Example:5.1
mov eax,sum ; get sumcdq ; extend sum to 64 bitsidiv ebx ; sum / countdtoa value,eax ; convert average to ASCIIoutput avgLabel ; display label for averageoutput 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 n
ext instruction Target address label is contained in jump ins
truction. 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->EIPTarget dword 98098912hjmp Target ; [target]->EIPjmp DWORD PTR [ebx] ; [ebx]->EIP
5.2 Conditional JUMP (条件转移)
Jcc targetStatement ;target address->EIP cc identifies the condition under which the jum
p is to be executed. If the condition holds, then the jump takes pla
ce; 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.
mnemonic flags description mnemonic flags description
JZ/JE ZF=1
Jump if equal/zero
JNZ/JNE ZF=0 Jump if not equal/not zero
JS SF=1
Jump if sign JNS SF=0 Jump if not sign
JP/JPE PF=1
Jump if parity/even
JNP/JPO PF=0 Jump if not parity/odd
JO OF=1
Jump if overflow JNO OF=0 Jump if not overflow
JC/JB/JNAE CF=1
Jump if below/ not above or equal
JNC/JNB/JAE CF=0 Jump if above or equal/not below
JBE/JNA CF=1 or ZF=1
Jump if below or equal/not above
JNBE/JA CF=0 & ZF=0
Jump if above/not below or equal
JL/JNGE SFOF
Jump if less/not greater or equal
JNL/JGE SF=OF Jump if not less/greater or equal
JLE/JNG ZF=1 or ZF OF
Jump if less or equal/ not greater
JNLE/JG ZF=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 endBalanceCheckelseIfZero: jnz elsePos… jmp endBanlanceCheckelsePos: …
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=00000000H(1)(2) NOT JUMPEAX=80000000H(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 endValueCheckelaseLarge: inc lartgeCout endValueCheck:
IF structure(2) if (total>=100) or (count=10) then add value to total; endif
cmp total , 100; total <=100? jge addValuecmp cx, 10; count=100? jne endAddCheckaddValue: mov ebx, value; copy valueadd total , ebx ; add value to totalendAddCheck:
IF structure(3) if (count>0) and (ch=backspace) then subtract 1 from count; endif
cmp cx , 0 ; count>0?jng endCheckChcmp al , backspace ; ch a backspace?jne endCheckChdec count ; subtract 1 from countendCheckCh:
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 againendWhileSum:
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, 1whileLE: 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 againendWhileSum:
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 againendWhileSum:
while loop structure(5)sum:=0while (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 structurePrompt for tally of numbers;Input tally;Sun:=0For count:=1 to tally loopPrompt for number;Input number;Add number to sum;End for ;
output prompt1 input value , 20 atoi valuemov tally , ax mov edx, 0 ; sum:=0mov bx, 1 ; count:=1
forCount: cmp bx, tallyjnle endfor ; exit if notoutput prompt2input value, 20atod valueadd edx, eaxinc bxjmp forCount ;repeatendFor:
until loop structureCount :=0;Until (sum>1000) or (count =100) loop ….{ body of loop}Add 1 to count;End until;
mov cx, 0 ;count :=0Until: ;body of loop
inc cx ;add 1 to countcmp sum, 1000 ; sum>1000?jg endUntil ; exit if sum >1000
cmp cx , 100 ; count=100? jne until ; continue if count not =100endUntil:
Loop instructions
Loop statementLabel1. statementLabel is the label of a statement th
at is a short displacement from the loop instruction.
2. ECX -1->ECX3. if ECX =0, then execute the statement followi
ng the looop instruction4. if ECX !=0, then a jump to the instruction at st
atementLabel 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?
232=4294967296
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 iterationsforYear: . ;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 re
gister 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 endCompareifLess: jnl isGreater ; guess < target ? output lowOutput ; display "too low" jmp endCompareisGreater: 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 notendUntilDone:
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 ; repeatendWhile:
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 numbersforCount1: 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 lessdtoa outValue,[ebx] ; convert value from array to ASCIIoutput outValue ; display valueendIfBig:add ebx,4 ; get address of next item of arrayloop 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