Direction Flag in x86
Asked Answered
K

2

9

I am unable to understand how does the direction flag work in x86. The text in my lectures say that it increments or decrements the source or destination register but that does not make sense with its name. Can someone explain what it does?

Kinnikinnick answered 30/4, 2012 at 7:36 Comment(0)
S
14

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.

Skurnik answered 30/4, 2012 at 7:39 Comment(4)
So it increases or decreases the string accordingly. If a string starts with a lower address it would add to it or in the other case perform the opposite, right?Kinnikinnick
Nathan Fellman, @Jerry Coffin, I think that the default behaviour is to copy from the beginning of a memory block (DF cleared). In what cases one would want to copy a memory block from the end instead (DF set)?Domiciliate
@golem: Consider copying stacks, that generally grow downwards. Consider comparing (not copying) strings, where you want to check backwards until the first difference. In these cases the direction matters.Skurnik
Another use case I've just discovered is when you want to insert a substring into a string and for that move the tail part to the right. In that case you have to copy byte from the len(str) location to len(str)+len(substr), then len(str-1) to len(str-1)+len(substr), and so on going downwards in the memory.Domiciliate
P
5

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.

Pleasurable answered 30/4, 2012 at 7:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.