Search code examples
winapimemoryexecutableportable-executable

Executable sections marked as "execute" AND "read"?


I've noticed (on Win32 at least) that in executables, code sections (.text) have the "read" access bit set, as well as the "execute" access bit. Are there any bonafide legit reasons for code to be reading itself instead of executing itself? I thought this was what other sections were for (such as .rdata).

(Specifically, I'm talking about IMAGE_SCN_MEM_READ.)


Solution

  • IMAGE_SCN_MEM_EXECUTE |IMAGE_SCN_MEM_READ are mapped into memory as PAGE_EXECUTE_READ, which is equivalent to PAGE_EXECUTE_WRITECOPY. This is needed to enable copy-on-write access. Copy-on-write means that any attempts to modify the page results in a new, process-private copy of the page being created.

    There are a few different reasons for needing write-copy:

    • Code that needs to be relocated by the loader must have this set so that the loader can do the fix-ups. This is very common.
    • Sections that have code and data in single section would need this as well, to enable modifying process globals. Code & data in a single section can save space, and possibly improve locality by having code and the globals the code uses being on the same page.
    • Code that attempts to modify itself. I believe this is fairly rare.