Reversing : The Hacker's Guide to Reverse Engineering

(ff) #1
Without branchless logic, a compiler would have to generate the following
code or something very similar to it:

cmp [result], 0
jne NotEquals
mov eax, 0
ret
NotEquals:
mov eax, 1
ret

Using the SETccinstruction, compilers can generate branchless logic. In
this particular example, the SETNEinstruction would be employed in the same
way as the JEinstruction was employed in the previous example:

xor eax, eax // Make sure EAX is all zeros
cmp [result], 0
setne al
ret

The use of the SETNEinstruction in this context provides an elegant solu-
tion. If result == 0, EAXwill be set to zero. If not, it will be set to one. Of
course, like Jcc, the specific condition in each of the SETccinstructions is
based on the conditional codes described earlier in this chapter.

Conditional Move (CMOVcc)
The CMOVccinstruction is another predicated execution feature in the IA-32
instruction set. It conditionally copies data from the second operand to the
first. The specific condition that is checked depends on the specific conditional
code used. Just like SETcc, CMOVccalso has multiple versions—one for each
of the conditional codes described earlier in this chapter. The following code
demonstrates a simple use of the CMOVccinstruction:

mov
ecx, 2000
cmp
edx, 0
mov
eax, 1000
cmove
eax, ecx
ret

The preceding code (generated by the Intel C/C++ compiler) demonstrates
an elegant use of the CMOVccinstruction. The idea is that EAXmust receive one
of two different values depending on the value of EDX. The implementation

514 Appendix A

21_574817 appa.qxd 3/16/05 8:54 PM Page 514

Free download pdf