The point of test %eax %eax

pauliwago picture pauliwago · Oct 25, 2012 · Viewed 175.6k times · Source

Possible Duplicate:
x86 Assembly - ‘testl’ eax against eax?

I'm very very new to assembly language programming, and I'm currently trying to read the assembly language generated from a binary. I've run across

 test   %eax,%eax

or test %rdi, %rdi, etc. etc. I'm very confused as to what this does. Isn't the values in %eax, %eax the same? What is it testing? I read somewhere that it is doing the AND operation.....but since they are the same value, wouldn't it just return %eax?

The following is just one instance where I found this usage:

   400e6e:       85 c0                   test   %eax,%eax
   400e70:       74 05                   je     400e77 <phase_1+0x23>

I thought je jumps if the two values being compared are equal......well, because %eax is well, itself, in what situation would we NOT jump?

I'm a beginner to programming in general, so I'd appreciate it very much if someone could explain this to me. Thanks!

Answer

John Dvorak picture John Dvorak · Oct 25, 2012

CMP subtracts the operands and sets the flags. Namely, it sets the zero flag if the difference is zero (operands are equal).

TEST sets the zero flag, ZF, when the result of the AND operation is zero. If two operands are equal, their bitwise AND is zero when both are zero. TEST also sets the sign flag, SF, when the most significant bit is set in the result, and the parity flag, PF, when the number of set bits is even.

JE [Jump if Equals] tests the zero flag and jumps if the flag is set. JE is an alias of JZ [Jump if Zero] so the disassembler cannot select one based on the opcode. JE is named such because the zero flag is set if the arguments to CMP are equal.

So,

TEST %eax, %eax
JE   400e77 <phase_1+0x23>

jumps if the %eax is zero.