What happens when you mark a section as DISCARDABLE?
In the flags you pass to the linker, you can specify that a section be made discardable. What does that mean?
If you are a kernel-mode driver, the discardable flag means that the contents will be removed from memory after initialization is complete. This is where you put your initialization code and data.
But if you’re writing user-mode code, the discardable flag has no effect.
Not relevant to the topic but people are going to ask anyway: The discardable flag on resources also has no effect.
The discardable attribute for user-mode code is a left-over from 16-bit Windows, which had to simulate a hardware memory manager in software. The rule in 16-bit code was that if you marked a segment or resource as discardable, then when memory ran out, the kernel was allowed to throw the segment away, safe in the knowledge that it could get the information back by reading it from the original image.
In 32-bit Windows, this marking of discardable versus non-discardable memory is not necessary because the memory manager (with the assistance of hardware) can manage it all transparently. For example, if you never modified a code segment, the memory manager knows that it can simply discard the memory because it can recover the data from the original image. If you allocated some zero-initialized memory and never modified it, then the memory manager can just throw the data away because it is very easy to “recover” a page full of zeroes. On the other hand, if you modified some memory, then there is nowhere the memory manager can go to recover the data, so it has to put it in the page file.
Bonus chatter: “If discardability is meaningless in user mode, should we just delete it?”
Well, the PE file format is used for both user-mode and kernel-mode components, so you can’t delete it from one and not the other since they are the same thing.
“I have some code that uses the pragma to make a section discardable. Should I just delete it?”
Maybe. Or maybe that flag is being used by some other part of your application. After all, the flag exists. Maybe some other part of your program uses it as a “free flag” that it usurps for some other purpose. For example, it might be used as a signal to some post-processing tool to mean “This section is exempt from the frob catalog.”
Hopefully there’s a comment that tells you why the section is being marked as discardable, and that will help you decide whether it’s safe to remove the marking. Windows doesn’t care, but some other part of your program might.