Over the past few days I've been struggling with a weird behaviour trying to get the states of EFLAGS. To accomplish this I've written this code:
#include <stdio.h>
int flags_state()
{
int flags = 0;
__asm__ __volatile__("pushfq");
__asm__ __volatile__("pop %%rax": "=a"(flags));
return flags;
}
int main()
{
printf("Returning EFLAGS state: 0x%x\n", flags_state());
return 0;
}
When it runs, I got:
./flags
Returning EFLAGS state: 0x246
It's getting weirder when I print out the flags twice
Returning EFLAGS state: 0x246
Returning EFLAGS state: 0x206
It changed when I tried to print it out 6 times
Returning EFLAGS state: 0x246
Returning EFLAGS state: 0x202
Returning EFLAGS state: 0x202
Returning EFLAGS state: 0x202
Returning EFLAGS state: 0x202
Returning EFLAGS state: 0x202
And finally the weirdest (at least for me) when I print it out 8 times
Returning EFLAGS state: 0x246
Returning EFLAGS state: 0x206
Returning EFLAGS state: 0x206
Returning EFLAGS state: 0x206
Returning EFLAGS state: 0x206
Returning EFLAGS state: 0x206
Returning EFLAGS state: 0x206
Returning EFLAGS state: 0x206
So, why did I get 0x246 at the first time? Shouldn't be 0x2 according Intel's manual? Why did it change when I try to print it more times and continue change?
before
flags_state()
called first time, some code executed in system, as result most flags state is random, you can not assume any values on generic flags, likeZF (0x40)
it can be and set and reset.. and how Intel's manual? can be related here ?function must not preserve
ZF
flag (unlike for instanceDF
in windows - must be 0 on return) - so which value this flag have after function return - also undefined - if only you by self not write all code on asm and gave full control over this. by factZF
is reset afterflags_state
return and not changed in prolog offlags_state
- as result first time - you have value which is set in previous code and then already all time the same value, which set inflags_state
(you wrong that it continue change - it not change already, as show your output - 0x206 all time)