'How to read and write x86 flags registers directly?

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?



Solution 1:[1]

You can use the pushf and popf instructions which will push the flags onto the stack, you can modify them, and then pop them back off.

Solution 2:[2]

If you need only the lower byte of the flags register (which contains SF,ZF,AF,PF,CF), then there is the odd but convenient instruction LAHF (ha ha), which loads the bottom 8 bits of the flags register into AH, and its counterpart SAHF to store AH into flags.

For the carry flag specifically, x86 offers CLC, STC and CMC, to clear, set, and complement the carry flag, respectively.

Solution 3:[3]

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.

Solution 4:[4]

SETcc

This instruction family is another way to observe some flags / combination of flags.

It sets the value of a byte based on the individual FLAGS.

E.g., for CF:

stc
setc al
; al == 1

clc
setc al
; al == 0

Runnable GitHub upstream with assertions.

Jcc

This instruction family is of course another possibility for certain flags, and could be used to implement SETcc:

jc set
mov al, 0
jmp end
set:
mov al, 1
end:

Runnable GitHub upstream with assertions.

Solution 5:[5]

  • LAHF: loads status flags into AH
  • Copies the low byte of the EFLAGS register including Sign, Zero, and Carry flags.
  • Save a copy of the flags in a variable for safekeeping

    .data
     saveflags BYTE ? 
    .code 
     lahf ; load flags into AH 
     mov saveflags,ah ; save them into a variable 
    
  • SAHF: stores AH into status flags

  • Copies AH into the low byte of the EFLAGS register
  • Retrieve the value of flags stored earlier

    .code
     mov ah, saveflags ; load save flags into AH 
     sahf ; copy into flags register 
    

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Michael
Solution 2 I. J. Kennedy
Solution 3 Peter Cordes
Solution 4
Solution 5 Jongware