6

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?

Sep Roland
  • 33,889
  • 7
  • 43
  • 76
def
  • 521
  • 4
  • 16
  • 2
    On reset, the direction flag is cleared. It is considered polite to save `DF` before changing it, and restoring it afterwards. – Weather Vane Dec 11 '16 at 19:48
  • 3
    The calling convention/ABI specifies the state for the `DF` and the compiler relies on that. – Jester Dec 11 '16 at 20:20

2 Answers2

7

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.

Daniel Kamil Kozar
  • 18,476
  • 5
  • 50
  • 64
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

Bo Persson
  • 90,663
  • 31
  • 146
  • 203