Page 1 of 1
cld
Posted: Fri Jan 23, 2009 7:23 am
by yemista
What does this instruction do? I read the definition of it but its unclear as to how or why it is used. I also read that most x86 assembly errors come from improper use of this instruction, so how do you know when it should be used?
Re: cld
Posted: Fri Jan 23, 2009 7:26 am
by Love4Boobies
CLD = Clear Direction Flag (DF in EFLAGS), as opposed to STD = Set Direction Flag. DF is typically used with long strings (e.g. for REP MOVSB) - it points the direction in which CX should go: increment or decrement. You should really read the Intel manuals before asking such questions.
EDIT: Just to clarify, it's not REP that is affected by DF, it's the string instructions (MOVS, CMPS, SCAS, LODS, STOS - and friends). However, it makes sense to take advantage of it when string instructions are used in conjunction with REP.
Re: cld
Posted: Fri Jan 23, 2009 7:57 am
by yemista
Yes I read all that, but my question is, what does that mean? What direction can you go in for strings? I can see that maybe for some reason youd want the counter to go backwards in memory, but in general its used to go forward, so for what cases would you need to use this instruction? In which cases does the directional flag ever get changed that you would need to clear it again to be safe?
Re: cld
Posted: Fri Jan 23, 2009 8:16 am
by bewing
Let's say that you have some data stored in an array in memory.
You want to insert a block of new data into the middle of that array.
You therefore set a destination pointer to the end of the array + the size of the block, and a source pointer to the end of the array.
You set a counter to the size of the back half of the array that is being copied up, and you copy going down (otherwise you will overwrite the data in your array).
Theoretically, you can do this using REP MOVS?, and setting STD. Back in the days when REP MOVS? was not microcoded, it would be a lot faster to copy data using this method. If you are trying to minimize the size of your executable, this is by far the smallest way to do the copy.
The point is that:
1. Your kernel and libraries are almost certainly built and compiled to assume that the Direction bit is CLEAR.
2. Unless you are creating a "trusted computing" OS, then you don't know if some user program that is running has set this bit (and maybe not even then).
3. If your scheduler runs a user program that sets the bit, then you get a job swap to a kernel process, and then the kernel process does some sort of REP ????? -- your kernel may crash.
So, in your scheduler, after regaining control from a generic user app, you always need to reset CLD. In any interrupt or exception handler that may use REP ????? you need to reset CLD. After every time that your kernel or libraries use STD, you need to use CLD.
Re: cld
Posted: Fri Jan 23, 2009 8:54 am
by yemista
oh ok that makes sense. thank you