What does this assembly code do? (TEST,XOR,JNZ)

2019-03-31 02:04发布

问题:

1.

TEST EAX,EAX
JNZ SHORT program.00407190

2.

XOR EAX,EAX
JNZ SHORT program.00407190

Kindly correct me if I'm wrong. Thank you! :)

From my understanding so far:

JNZ is jump if not equal to zero, it will jump or not depending on whether ZF is set to 1 or not. If it's 1, it will not jump. Else, it will jump.

From my understanding for code #1, TEST EAX,EAX will check whether it's zero or not. If it's not equal to zero(ZF is 0), it will jump to address 00407190.

For code #2
XOR EAX,EAX will set EAX register to 0. Does it set any flags? If not, how does JNZ instruction determine to jump or not?

Lastly, why would people want to check if EAX is 0 or not? Kindly please assist me in a easier and detailed explanation, I'm still a beginner.

回答1:

TEST and XOR are logical instructions used to perform logical operations on the operands.

TEST INSTRUCTION (comparing the operands)

TEST destiny, source

It performs a conjunction, bit by bit, of the operands, but differing from AND, this instruction does not place the result in the destination operand, it only has effect on the state of the flags.

Source Destiny | Destiny
--------------------------
1      1       | 1      
1      0       | 0
0      1       | 0
0      0       | 0    <---

XOR INSTRUCTION (Exclusive OR)

XOR destiny, source 

Its function is to perform the logical exclusive disjunction of the two operands bit by bit.

Source Destiny | Destiny
--------------------------
1      1       | 0    <---
1      0       | 1
0      1       | 1
0      0       | 0    <---

As you see in the tables:

XOR EAX,EAX will set the EAX register to zero. The ZF will be set if the result of the XOR is zero. So in this case: (ZF=1)

TEST EAX,EAX does not place the result on the register, it only has effect on the state of the ZF. In this case if EAX == 0, then (ZF=1)


JNZ (JNE) INSTRUCTION (Conditional jump)

JNZ label

It jumps to label if it is not equal or zero. The jump will be done if ZF is deactivated. (ZF=0)