X86 TEST instruction not working?

I hit my head against the wall, figuring it out, and it makes no sense to me ...

Why is this program entering an endless loop ?!

I thought you can use testto compare two values ​​for equality, as shown here ... why doesn't it work?

int main()
{
    __asm
    {
        mov EAX, 1;
        mov EDX, EAX;
        test EAX, EDX;
L:      jne L;
    }
}
+5
source share
3 answers

Your expectation of what the instruction does TESTis incorrect.

The instruction is used to perform bit tests. You would usually use it to β€œcheck” if certain bits are specified with respect to the mask. It will be used in conjunction with JZ(jump if zero) or JNZ(jump if not zero) instructions .

- ( ). , ZF ( ) 1 ( ). , , JNZ. , , JZ.

JE JNE , -.


. CMP. .

( ). 0 (ZF = 1). , (ZF = 0). , , JE (jump if equal). , , JNE (jump if not equal).


, TEST, ZF = 0 (0x1 0x1 = 0x1, ). ZF = 0, JNE , .

TL;DR

CMP, , TEST .

int main()
{
    __asm
    {
        mov EAX, 1
        mov EDX, EAX
        cmp EAX, EDX
L:      jne L          ; no more infinite loop
    }
}
+7

this ( asm ) this

JNE ZF (Zero Flag) = 0

TEST ZF = 0 EAX AND EDX 1 1, 0

AND 0, ZF 1, 0.

1 1 0 ZF.

, .

, @A.Webb - , JNZ, TEST, bitwuse, , SUB Zero .

+3

. , , , , . , . Intel x86 .

:

    mov EAX, 1;

1 EAX. .

    mov EDX, EAX;

EAX EDX, 1.

    test EAX, EDX;

( ?), . 31 , d - . - ; and'd 1. , 32 "" , . , "Z" (ero), , . "", Z reset. .

 L:      jne L;

This is "Jmp on Not Equal", for example, jmps if the Z bit is reset. For your Z program - reset, jmp appears. After execution, the processor is in the same construction and sees another (the same jmp). The bits of the condition code are not changed by the jmp command.

So ... he goes into an endless cycle.

There are many synonyms for the various opcodes supported by assemblers. For example, "JZ" and "JE" are synonyms for the same instruction. Do not let synonyms be confused.

+1
source

All Articles