What is the default value of the Zero Flag in x86 assembly MASM?

811 views Asked by At

For example if I have the following piece of code:

L1:
        cmp WORD PTR[ebx],0
        jnz found
        add ebx,2
        loop L1
        jmp notFound

Is the zero flag undefined for its default value?

1

There are 1 answers

6
Peter Cordes On BEST ANSWER

There is no "default", unless you mean initial power-on before running the first instruction of the BIOS. Any other time, the value is whatever previous instructions put there, just like other registers.

If you mean the very first user-space instruction of a process, that would depend on the kernel. Try it in a debugger and see what your version of your OS happens to do. For example, Linux zeros integer/vector registers before entering user-space (to avoid leaking any kernel data), and clears all the condition-code flags in EFLAGS.


Think of registers (including condition FLAGS) like you would uninitialized local variables in C. (Except asm doesn't have Undefined Behaviour; you can read whatever garbage previous code left in a register, there's just no guarantee what the value will be.)

That's why this code uses cmp to set FLAGS including ZF before running jnz, so it doesn't matter what was there before.


Instructions like mul that leave some flags "undefined" will set it to some value according to some internal condition on any given CPU, the manual just doesn't guarantee anything across different CPUs. e.g. on some CPUs, mul may always clear ZF. On others, it might get set according to the low or high half, or whole thing, being zero. (Or it might usually do that but sometimes not, depending on microarchitectural conditions.) The lack of documented guarantees means that experimenting to see what actually happens is not a safe way to write portable code.

But whatever happens, ZF will be either 0 or 1 even after an instruction like mul, and won't for example change a couple instructions after mul is finished.