1

Starting in the Assembly areas and hard to find a decent tutorial of sort. Would like to find an "Assembly for Dummies" book.

I have come across the following and the 'test' command is always run using the same address or registry.

0x08048e14 <+21>:   test   %esi,%esi
0x08048e16 <+23>:   jne    0x8048e4b <main+76>

Since the same registry or address is being AND when would it not return that these are the same?

Jester
  • 56,577
  • 4
  • 81
  • 125
Unhandled Exception
  • 1,427
  • 14
  • 30
  • 2
    It's not checking for "same", it's not a `cmp`. It's checking whether the result of bitwise `and` is zero or not, in turn meaning `esi` is zero or not. – Jester Jun 21 '17 at 01:04
  • 1
    Possible duplicate of [The point of test %eax %eax](https://stackoverflow.com/questions/13064809/the-point-of-test-eax-eax) – Raymond Chen Jun 21 '17 at 01:30

1 Answers1

10
test reg, reg

(where reg is the same for both operands) is what you'll almost always see instead of:

cmp  reg, 0

in optimized code. Both instructions set the flags the same way, but the former takes fewer bytes to encode and is therefore slightly faster.

Therefore, your code just tests to see whether the esi register is zero or not. If it is non-zero, it takes the branch; if it is zero, execution falls through without branching.


Why does this work? Well, as you seem to already know, the TEST instruction just does a bitwise-AND on its operands. So what does the truth table say for bitwise-AND?

|===============================|
|  Bit 1  |  Bit 2  ||   AND    |
|---------|---------||----------|
|    0    |    0    ||    0     |
|    1    |    0    ||    0     |
|    0    |    1    ||    0     |
|    1    |    1    ||    1     |
|===============================|

The middle two cases can be ignored, since in this special case, we know that both operands are the same value. So, when esi is 0, TEST will set the zero flag (ZF) to 1, because the result of the bitwise-AND is 0. And, conversely, when esi is non-zero, TEST will turn off the zero flag, because the result if the bitwise-AND is non-zero.

Fifoernik
  • 9,779
  • 1
  • 21
  • 27
Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574