Default state of Direction Flag (DF) during x86 program execution
Asked Answered
H

2

7

In disassembly, I often see that string manipulation instructions are being used without regard to the state of the direction flag (DF), like this:

or      ecx, 0FFFFFFFFh
xor     eax, eax
mov     edi, ebp
repne scasb

CLD or STD instructions are not found since function begins, neither other instructions which could affect DF flag.
So does the compiler assume the predefined state of this flag since program launch, courtesy of the loader, and being preserved unchanged while program runs?

Healy answered 11/12, 2016 at 19:37 Comment(2)
On reset, the direction flag is cleared. It is considered polite to save DF before changing it, and restoring it afterwards.Tidy
The calling convention/ABI specifies the state for the DF and the compiler relies on that.Adventist
P
1

The compiler runtime, including the code compiled for the operating system, will expect the flag to be in a certain state. Other code can use this assumption too, and doesn't have to constantly clear the flag.

MSDN on Direction Flag

Protection answered 17/1, 2017 at 19:50 Comment(0)
M
8

This is specified by the ABI of the platform that you're using. The System V Intel386 ABI (chapter Registers and the Stack Frame) says that :

The direction flag must be set to the "forward" (that is, zero) direction before entry and upon exit from a function.

The same requirement is preserved in the AMD64 ABI (Dropbox link, since x86-64.org is down) (section 3.2.1 Registers and the Stack Frame) :

The direction flag DF in the %rFLAGS register must be clear (set to "forward" direction) on function entry and return.

So, yes, userland code can safely assume that DF is set to zero.

Maxama answered 17/1, 2017 at 22:52 Comment(1)
Quote for the i386 ABI is in page 38. This document has very useful information.Eugeneeugenia
P
1

The compiler runtime, including the code compiled for the operating system, will expect the flag to be in a certain state. Other code can use this assumption too, and doesn't have to constantly clear the flag.

MSDN on Direction Flag

Protection answered 17/1, 2017 at 19:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.