Reverse Engineering for Beginners

(avery) #1

CHAPTER 14. LOOPS CHAPTER 14. LOOPS


14.3 Conclusion.


Rough skeleton of loop from 2 to 9 inclusive:


Listing 14.15: x86
mov [counter], 2 ; initialization
jmp check
body:
; loop body
; do something here
; use counter variable in local stack
add [counter], 1 ; increment
check:
cmp [counter], 9
jle body


The increment operation may be represented as 3 instructions in non-optimized code:


Listing 14.16: x86
MOV [counter], 2 ; initialization
JMP check
body:
; loop body
; do something here
; use counter variable in local stack
MOV REG, [counter] ; increment
INC REG
MOV [counter], REG
check:
CMP [counter], 9
JLE body


If the body of the loop is short, a whole register can be dedicated to the counter variable:


Listing 14.17: x86
MOV EBX, 2 ; initialization
JMP check
body:
; loop body
; do something here
; use counter in EBX, but do not modify it!
INC EBX ; increment
check:
CMP EBX, 9
JLE body


Some parts of the loop may be generated by compiler in different order:


Listing 14.18: x86
MOV [counter], 2 ; initialization
JMP label_check
label_increment:
ADD [counter], 1 ; increment
label_check:
CMP [counter], 10
JGE exit
; loop body
; do something here
; use counter variable in local stack
JMP label_increment
exit:


Usually the condition is checkedbeforeloop body, but the compiler may rearrange it in a way that the condition is checked
afterloop body. This is done when the compiler is sure that the condition is alwaystrueon the first iteration, so the body
of the loop is to be executed at least once:

Free download pdf