Direction Flag in x86

This flag is used in string operations, and specifies if strings begin at a low address and proceed to higher addresses or vice versa.

For string instructions, ECX has the number of iterations, DS:ESI has the source address and ES:EDI has the destination (hence the s in ESI and the d in EDI).

After each iteration, ECX is decremented by one, and ESI and EDI are either incremented or decremented by the element size (1 for byte operations, 2 for word operations etc) according to EFLAGS.DF.

If EFLAGS.DF is 0, ESI and EDI are incremented, otherwise they're decremented.


Let's take rep movsb as an example of an instruction that depends on the direction flag.

When you do a rep movsb, you supply a source address in esi, a destination address in edi, and count in ecx. The processor basically executes a loop. In the normal case (when the direction flag is clear) it increments esi and edi each iteration of the loop, so you initialize them to point to the beginning of the source and destination blocks you're copying. While executing the REP MOVSB, the processor increments the source and destination addresses until it reaches the end of the block being copied.

When the direction flag is set, the processor decrements the registers instead. This means you need to start with them pointing to the end of the memory block you're copying. Instead of starting from the beginning and copying to the end, it starts at the end and copies backward until it gets to the beginning.