NmdMystery
NmdMystery

Reputation: 2868

How are win32 executable resources handled?

I don't know why it's so difficult to find the answer to this question on Google, but I want to set something straight.

Are win32 resources handled in the same way static data is where that data is kept in the RAM for the entire runtime of a process, or are they kept on disk like a regular file until loaded into memory? Functions like LoadResource / LoadString imply the latter, but I want to be absolutely sure I'm not being fooled by abstraction.

Upvotes: 8

Views: 852

Answers (2)

Adrian McCarthy
Adrian McCarthy

Reputation: 47962

In olden days (like Windows 3.1 and earlier), resources were copied into memory during load, and you just got a handle to them. The memory manager could do things like move the copy around in memory to defragment space or even secretly unload the resource until you needed it again. When you needed the resource, there was a second step to "lock" it into memory. This gave you a pointer to the copy and made sure the resource manager didn't move it around until you unlocked it again.

In 32-bit versions of Windows, resources aren't copied. The executable (or DLL) is mapped into memory, and if you touch the resource, the virtual memory manager will make sure it's there for you.

The APIs (FindResource, LoadResource, LockResource) reflect the old days, with handles to resources, and locking of handles, etc. But the implementations are much simpler now because the handle is just a pointer to the beginning of the resource and locking is effectively a no-op, casting the handle to a pointer type and returning it.

Upvotes: 8

Igor Skochinsky
Igor Skochinsky

Reputation: 25278

You may notice that all resource APIs accept an hModule argument - this is in fact a pointer to the PE header of the module in memory and not the handle to the file on disk. Thus the resource section of the PE file (.rsrc) must be present in the memory space of the program for those APIs to work. Of course, as with all memory-mapped files the data is probably not actually paged into the physical RAM until it's needed.

Upvotes: 3

Related Questions