views:

124

answers:

3

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.)

+5  A: 

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.
Michael
A: 

The one example I can think of for a reason to read code is to allow for self modifying code. Code must necessarily be able to read itself in order to be self modifying.

Also consider the opposite side. What advantage is gained from disallowing code from reading itself? I struggled for a bit on this one but I can see no advantage gained from doing so.

JaredPar
+1  A: 

Compile-time constants, particularly for long long or double values, are often loaded with a mov register, address statement from the code segment.

Joshua