How to read and write x86 flags registers directly?

Viewed 43360

From what I've read, seems like there are 9 different flags. Is it possible to read/change them directly? I know I can know for example if the zero flag is set after doing a cmp/jmp instruction, but I'm asking if it's possible to do something like

mov eax, flags

or something.

Also, for writing, is it possible to set them by hand?

6 Answers

Simplest way is using pushfd/pushfw and pop (r16/r32).

If you want to move eflags into eax, use code below.

pushfd                 # push eflags into stack
pop %eax               # pop it into %eax

Or, if you only want the first 16 bits from eflags:

pushfw
pop %ax

In most assemblers (at least GAS and NASM, likely others), pushf without an explicit operand-size defaults to the mode you're in. e.g. pushfq in 64-bit mode. You'd normally only need an explicit operand-size if you wanted to use pushfd in 16-bit mode to match a 32-bit pop. But it doesn't hurt.

Related