Your expectation of what the TEST
instruction does is incorrect.
The instruction is used to perform bit tests. You would typically use it to "test" if certain bits are set given a mask. It would be used in conjunction with the JZ
(jump if zero) or JNZ
(jump if not zero) instructions.
The test involves performing a bitwise-AND on the two operands and sets the appropriate flags (discarding the result). If none of the corresponding bits in the mask are set, then the ZF (zero flag) will be 1
(all bits are zero). If you wanted to test if any were set, you'd use the JNZ
instruction. If you wanted to test if none were set, you'd use the JZ
instruction.
The JE
and JNE
are not appropriate for this instruction because they interpret the flags differently.
You are trying to perform an equality check on some variables. You should be using the CMP
instruction. You would typically use it to compare values with each other.
The comparison effectively subtracts the operands and only sets the flags (discarding the result). When equal, the difference of the two values is 0
(ZF = 1). When not equal, the difference of the two values is non-zero (ZF = 0). If you wanted to test if they were equal, you'd use the JE
(jump if equal) instruction. If you wanted to test if they were not equal, you'd use the JNE
(jump if not equal) instruction.
In this case, since you used TEST
, the resulting flags would yield ZF = 0
(0x1 & 0x1 = 0x1, non-zero). Since ZF = 0
, the JNE
instruction would take the branch as you are seeing here.
tl;dr
You need to compare the values using the CMP
instruction if you are checking for equality, not TEST
them.
int main()
{
__asm
{
mov EAX, 1
mov EDX, EAX
cmp EAX, EDX
L: jne L ; no more infinite loop
}
}