Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a register is zero in x86_64 assembly [duplicate]

I'm trying to check if a value is zero in x86_64 assembly code. I know that this usually consist of a cmp variant followed by a jmp variant, but I'm not sure of the exact instructions to use.

like image 782
Jack Maloney Avatar asked Apr 21 '15 02:04

Jack Maloney


People also ask

Is there a zero register in x86?

While the x86/x64 architectures do not have an architectural zero register it seems likely that the Sandybridge processor has a physical zero register. When the renamer detects one of these special instructions it just renames the architectural register to point at the zero register.

Which instruction would check the contents of register is zero or not?

If you need to test a register for zero, but don't want to alter its value, you use the test instruction.

How can we check whether two pieces of data each from a register are equal?

One of the first relational operators any programmer comes across is the equality/equivalence operator or ==. It is used to evaluate whether any given two operands are equal to each other or not.

What is test EAX EAX?

TEST EAX,EAX tests whether EAX is zero or not and sets or unsets the ZF bit.


2 Answers

If you've just used an instruction that modifies ZF before, simply check that flag and jump using JZ or JE. For example

and rax, rbx ; ZF was modified
jz  is_zero  ; so to check if rax is zero, a single jump is enough

If ZF was not set, you need to do that explicitly. The obvious way is

cmp rax, 0
je  equal_zero

However since cmp is longer if you look at the output binary, test or sometimes and, or is preferred

83F800  cmp eax, 0
09C0    or eax, eax
85C0    test eax, eax

The resulting code will be

test rax, rax
jz   is_zero

You can get the assembly output from a compiler and check or view it in an online tool like gcc godbolt

Read more: http://en.wikibooks.org/wiki/X86_Assembly/Control_Flow

like image 128
phuclv Avatar answered Jun 09 '23 21:06

phuclv


test %eax, %eax   ; set ZF to 1 if eax == 0
je 0x804f430      ; jump to 0x00804f4 if ZF == 1

ZF is a single bit zero flag which will be set to 1 if eax be equal to zero. je will take the jump to 0x804f430 if the ZF be set to 1.

like image 36
Tim Biegeleisen Avatar answered Jun 09 '23 21:06

Tim Biegeleisen