当前位置: 代码迷 >> VC >> 可执行文件映射到内存中的具体过程?该怎么解决
  详细解决方案

可执行文件映射到内存中的具体过程?该怎么解决

热度:1490   发布时间:2013-02-25 00:00:00.0
可执行文件映射到内存中的具体过程?
最近在看《Windows核心编程》,有一点很疑惑的地方:
可执行文件被存储在磁盘上,当要运行这个程序的时候,可执行文件中的内容会被映射到内存中,然后 CPU读取内存中的内容来执行指令。
我的疑惑在于可执行文件映射的时候是怎么一个过程,在《Windows核心编程》中提到了内存映射和虚拟内存的内容,我疑惑地方在于不知道映射内存的时候是直接映射到物理内存上呢,还是映射到虚拟内存上?

------解决方案--------------------------------------------------------
Loading the library

To emulate the PE loader, we must first understand, which steps are neccessary to load the file to memory and prepare the structures so they can be called from other programs.

When issuing the API call LoadLibrary, Windows basically performs these tasks:

Open the given file and check the DOS and PE headers.
Try to allocate a memory block of PEHeader.OptionalHeader.SizeOfImage bytes at position PEHeader.OptionalHeader.ImageBase.
Parse section headers and copy sections to their addresses. The destination address for each section, relative to the base of the allocated memory block, is stored in the VirtualAddress attribute of the IMAGE_SECTION_HEADER structure.
If the allocated memory block differs from ImageBase, various references in the code and/or data sections must be adjusted. This is called Base relocation.
The required imports for the library must be resolved by loading the corresponding libraries.
The memory regions of the different sections must be protected depending on the section’s characteristics. Some sections are marked as discardable and therefore can be safely freed at this point. These sections normally contain temporary data that is only needed during the import, like the informations for the base relocation.
Now the library is loaded completely. It must be notified about this by calling the entry point using the flag DLL_PROCESS_ATTACH.