>

那么只需要将这个入口地址指向附加的代码就可

- 编辑:澳门博发娱乐官网 -

那么只需要将这个入口地址指向附加的代码就可

208/224

[PE结构分析] 5.IMAGE_OPTIONAL_HEADER,imageoptionalheader

结构体源代码如下:

typedef struct _IMAGE_OPTIONAL_HEADER 
{
    //
    // Standard fields.  
    //
+18h    WORD    Magic;                   // 标志字, ROM 映像(0107h),普通可执行文件(010Bh)
+1Ah    BYTE    MajorLinkerVersion;      // 链接程序的主版本号
+1Bh    BYTE    MinorLinkerVersion;      // 链接程序的次版本号
+1Ch    DWORD   SizeOfCode;              // 所有含代码的节的总大小
+20h    DWORD   SizeOfInitializedData;   // 所有含已初始化数据的节的总大小
+24h    DWORD   SizeOfUninitializedData; // 所有含未初始化数据的节的大小
+28h    DWORD   AddressOfEntryPoint;     // 程序执行入口RVA ***(必须了解)***
+2Ch    DWORD   BaseOfCode;              // 代码的区块的起始RVA
+30h    DWORD   BaseOfData;              // 数据的区块的起始RVA
    //
    // NT additional fields.    以下是属于NT结构增加的领域。
    //
+34h    DWORD   ImageBase;               // 程序的首选装载地址 ***(必须了解)***
+38h    DWORD   SectionAlignment;        // 内存中的区块的对齐大小 ***(必须了解)***
+3Ch    DWORD   FileAlignment;           // 文件中的区块的对齐大小 ***(必须了解)***
+40h    WORD    MajorOperatingSystemVersion;  // 要求操作系统最低版本号的主版本号
+42h    WORD    MinorOperatingSystemVersion;  // 要求操作系统最低版本号的副版本号
+44h    WORD    MajorImageVersion;       // 可运行于操作系统的主版本号
+46h    WORD    MinorImageVersion;       // 可运行于操作系统的次版本号
+48h    WORD    MajorSubsystemVersion;   // 要求最低子系统版本的主版本号
+4Ah    WORD    MinorSubsystemVersion;   // 要求最低子系统版本的次版本号
+4Ch    DWORD   Win32VersionValue;       // 莫须有字段,不被病毒利用的话一般为0
+50h    DWORD   SizeOfImage;             // 映像装入内存后的总尺寸
+54h    DWORD   SizeOfHeaders;           // 所有头 + 区块表的尺寸大小
+58h    DWORD   CheckSum;                // 映像的校检和
+5Ch    WORD    Subsystem;               // 可执行文件期望的子系统 ***(必须了解)***
+5Eh    WORD    DllCharacteristics;      // DllMain()函数何时被调用,默认为 0
+60h    DWORD   SizeOfStackReserve;      // 初始化时的栈大小
+64h    DWORD   SizeOfStackCommit;       // 初始化时实际提交的栈大小
+68h    DWORD   SizeOfHeapReserve;       // 初始化时保留的堆大小
+6Ch    DWORD   SizeOfHeapCommit;        // 初始化时实际提交的堆大小
+70h    DWORD   LoaderFlags;             // 与调试有关,默认为 0 
+74h    DWORD   NumberOfRvaAndSizes;     // 下边数据目录的项数,这个字段自Windows NT 发布以来一直是16
+78h    IMAGE_DATA_DIRECTORY DataDirectory[IMAGE_NUMBEROF_DIRECTORY_ENTRIES];   
// 数据目录表 ***(必须了解,重点)*** winNT发布到win10,IMAGE_NUMBEROF_DIRECTORY_ENTRIES一直都是16
} IMAGE_OPTIONAL_HEADER32, *PIMAGE_OPTIONAL_HEADER32;

AddressOfEntryPoint  ***(必须了解)***

程序开始执行的地址,这是一个RVA(相对虚拟地址)。对于exe文件,这里是启动代码;对于dll文件,这里是libMain()的地址。如果在一个可执行文件上附加了一段代码并想让这段代码首先被执行,那么只需要将这个入口地址指向附加的代码就可以了。在脱壳时第一件事就是找入口点,指的就是这个值。

ImageBase  ***(必须了解)***

PE文件的优先装入地址。也就是说,当文件被执行时,如果可能的话(当前地址没有被使用),Windows优先将文件装入到由ImageBase字段指定的地址中。

对于EXE文件来说,由于每个文件总是使用独立的虚拟地址空间,优先装入地址不可能被**模块占据,所以EXE总是能够按照这个地址装入

这也意味着EXE文件不再需要重定位信息。

对于DLL文件来说,由于多个DLL文件全部使用宿主EXE文件的地址空间,不能保证优先装入地址没有被**的DLL使用,所以DLL文件中必须包含重定位信息以防万一。

因此,在前面介绍的 IMAGE_FILE_HEADER 结构的 Characteristics 字段中,DLL 文件对应的 IMAGE_FILE_RELOCS_STRIPPED 位总是为0,而EXE文件的这个标志位总是为1。

如果没有指定的话,dll文件默认为0x10000000;exe文件默认为0x00400000,但是在Windows CE平台上是0x00010000。此值必须是64K bytes的倍数!

SectionAlignment ***(必须了解)***

内存中区块的对齐单位。区块总是对齐到这个值的整数倍。此字段必须大于或等于 FileAlignment ,默认值是系统页面的大小。32位cpu通常值为 0x1000(十六进制),即4096,即4KB。64位cpu通常为 8kB
FileAlignment ***(必须了解)*****

pe文件中区块的对齐单位,以bytes(字节)为单位。此值必须是2的次方倍,但是必须在512和64K区间之间(闭区间[521, 64*1024=65536]),如果SectionAlignment小于系统页面的大小,那么SectionAlignment的大小就和FileAlignment相同。pe文件中默认值为 521 字节(0.5KB) 即 0x200(十六进制)。

Subsystem ***(必须了解)***

pe文件的用户界面使用的子系统类型。定义如下:

#define IMAGE_SUBSYSTEM_UNKNOWN              0   // 未知子系统
#define IMAGE_SUBSYSTEM_NATIVE               1   // 不需要子系统(如驱动程序)
#define IMAGE_SUBSYSTEM_WINDOWS_GUI          2   // Windows GUI 子系统
#define IMAGE_SUBSYSTEM_WINDOWS_CUI          3   // Windows 控制台子系统
#define IMAGE_SUBSYSTEM_OS2_CUI              5   // OS/2 控制台子系统
#define IMAGE_SUBSYSTEM_POSIX_CUI            7   // Posix 控制台子系统
#define IMAGE_SUBSYSTEM_NATIVE_WINDOWS       8   // 镜像是原生 Win9x 驱动程序
#define IMAGE_SUBSYSTEM_WINDOWS_CE_GUI       9   // Windows CE 图形界面

例如,Visual Studio 2015中编译程序时可以在图形界面设置链接选项:

更多请查看:

微软官方文档:

DataDirectory ***(必须了解,重要)***

这个字段可以说是最重要的字段之一,它由16个相同的IMAGE_DATA_DIRECTORY结构组成。其结构如下:

typedef struct _IMAGE_DATA_DIRECTORY {

   DWORD   VirtualAddress; // 相对虚拟地址 

   DWORD   Size;           // 数据块的大小

} IMAGE_DATA_DIRECTORY, *PIMAGE_DATA_DIRECTORY;

也就是定义了某块的位置和大小。

虽然PE文件中的数据是按照装入内存后的页属性归类而被放在不同的节中的,但是这些处于各个节中的数据按照用途可以被分为导出表、导入表、资源、重定位表等数据块,这16个IMAGE_DATA_DIRECTORY结构就是用来定义多种不同用途的数据块的(如下表所示)。IMAGE_DATA_DIRECTORY结构的定义很简单,它仅仅指出了某种数据块的位置和长度。

#define IMAGE_DIRECTORY_ENTRY_EXPORT          0   // 导出表
#define IMAGE_DIRECTORY_ENTRY_IMPORT          1   // 导入表
#define IMAGE_DIRECTORY_ENTRY_RESOURCE        2   // 资源表
#define IMAGE_DIRECTORY_ENTRY_EXCEPTION       3   // 异常表(具体资料不详)
#define IMAGE_DIRECTORY_ENTRY_SECURITY        4   // 安全表(具体资料不详)
#define IMAGE_DIRECTORY_ENTRY_BASERELOC       5   // 重定位表
#define IMAGE_DIRECTORY_ENTRY_DEBUG           6   // 调试表
//      IMAGE_DIRECTORY_ENTRY_COPYRIGHT       7   // (X86 usage) 版权信息
#define IMAGE_DIRECTORY_ENTRY_ARCHITECTURE    7   // 版权信息
#define IMAGE_DIRECTORY_ENTRY_GLOBALPTR       8   // RVA of GP (具体资料不详)
#define IMAGE_DIRECTORY_ENTRY_TLS             9   // TLS Directory (线程位置存储,具体资料不详)
#define IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG    10   // Load Configuration Directory (不详)
#define IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT   11   // Bound Import Directory in headers(不详)
#define IMAGE_DIRECTORY_ENTRY_IAT            12   // 导入函数地址表
#define IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT   13   // Delay Load Import Descriptors(不详)
#define IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR 14   // COM Runtime descriptor(不详)

] 5.IMAGE_OPTIONAL_HEADER,imageoptionalheader 结构体源代码如下: typedef struct _IMAGE_OPTIONAL_HEADER { // // Standard fields. // +18h WORD Magic; // 标志...

  • IMAGE_FILE_HEADER中的SizeOfOptionalHeader表示IMAGE_OPTIONAL_HEADER结构体的长度。另一层含义是确定节区头(IMAGE_SECTION_HEADER)的起始偏移。

  • 从IMAGE_OPTIONAL_HEADER的起始偏移加上SizeOfOptionalHeader的值的位置开始才是IMAGE_SECTION_HEADER

  • IMAGE_OPTIONAL_HEADER在32位PE32中大小为E0,64位PE32+中的大小为F0

  • Data_Directories中Import_Table为八个字节。前四个字节为导入表的地址(RVA),后四个字节为导入表的大小(SIZE)。如下图:导入表的RVA为271EE

Data sections, .bss, .rdata, .data

The .bss section represents uninitialized data for the application, including all variables declared as static within a function or source module.

The .rdata section represents read-only data, such as literal strings, constants, and debug directory information.

All other variables (except automatic variables, which appear on the stack) are stored in the .data section. Basically, these are application or module global variables.

120/136

e_lfanew = MZ文件头大小(40) + DOS存根大小(可变:VC++下为A0) = E0

Predefined Sections

An application for Windows NT typically has the nine predefined sections named .text, .bss, .rdata, .data, .rsrc, .edata, .idata, .pdata, and .debug. Some applications do not need all of these sections, while others may define still more sections to suit their specific needs. This behavior is similar to code and data segments in MS-DOS and Windows version 3.1. In fact, the way an application defines a unique section is by using the standard compiler directives for naming code and data segments or by using the name segment compiler option -NT —exactly the same way in which applications defined unique code and data segments in Windows version 3.1.

The following is a discussion of some of the more interesting sections common to typical Windows NT PE files.

Reserved, must be 0

WINNT.H

[cpp] view plain copy

 

  1. #define IMAGE_DOS_SIGNATURE             0x5A4D      // MZ  
  2. #define IMAGE_OS2_SIGNATURE             0x454E      // NE  
  3. #define IMAGE_OS2_SIGNATURE_LE          0x454C      // LE  
  4. #define IMAGE_NT_SIGNATURE              0x00004550  // PE00  

At first it seems curious that Windows executable file types do not appear on this list. But then, after a little investigation, the reason becomes clear: There really is no difference between Windows executables and OS/2 executables other than the operating system version specification. Both operating systems share the same executable file structure.

Turning our attention back to the Windows NT PE file format, we find that once we have the location of the file signature, the PE file follows four bytes later. The next macro identifies the PE file header:

The base relocation table address and size. For more information, see section 6.6, "The .reloc Section (Image Only)."

  • 使用SDK或Visual C++创建PE文件时,EXE默认的ImageBase为00400000,DLL默认10000000。使用DDK创建的SYS文件默认的ImageBase为10000。

  • Windows Vista之后的版本引入了ASLR安全机制,每次运行EXE文件都会被加载到随机地址,增强了系统安全性。

  • VC++中生成的PE文件的重定位节区名为.reloc,删除该节区后文件照常运行。

  • .reloc删除:

  • 首先在 IMAGE_SECTION_HEADER .reloc 处查看该节区头的长度和 .reloc 节区的偏移地址,以及 Virtual Size

  • 然后将 .reloc 的节区头中的值替换为0, .reloc 节区整个删除

  • 删除节区后,修改 IMAGE_FILE_HEADER 中的 Number of Sections 项。

  • 通过 IMAGE_OPTIONAL_HEADER - size of Image 修改映像值大小。

  • 需要减去的值根据之前记录的 Virtual Size 和 IMAGE_OPTIONAL_HEADER - Section Alignment 值扩展后所得。

  • 根据PE文件格式规范,IMAGE_NT_HEADERS的起始位置是“可变的”,由IMAGE_DOS_HEADER中的e_lfanew的值决定。一般拥有如下值(不同构建环境会有不同):

WINNT.H

[cpp] view plain copy

 

  1. typedef struct _IMAGE_RESOURCE_DATA_ENTRY {  
  2.     ULONG   OffsetToData;  
  3.     ULONG   Size;  
  4.     ULONG   CodePage;  
  5.     ULONG   Reserved;  
  6. } IMAGE_RESOURCE_DATA_ENTRY, *PIMAGE_RESOURCE_DATA_ENTRY;  

The two fields OffsetToData and Size indicate the location and size of the actual resource data. Since this information is used primarily by functions once the application has been loaded, it makes more sense to make the OffsetToData field a relative virtual address. This is precisely the case. Interestingly enough, all other offsets, such as pointers from directory entries to other directories, are offsets relative to the location of the root node.

To make all of this a little clearer, consider Figure 2.

澳门博发娱乐官网 1

Figure 2. A simple resource tree structure

Figure 2 depicts a very simple resource tree containing only two resource objects, a menu, and a string table. Further, the menu and string table have only one item each. Yet, you can see how complicated the resource tree becomes—even with as few resources as this.

At the root of the tree, the first directory has one entry for each type of resource the file contains, no matter how many of each type there are. In Figure 2, there are two entries identified by the root, one for the menu and one for the string table. If there had been one or more dialog resources included in the file, the root node would have had one more entry and, consequently, another branch for the dialog resources.

The basic resource types are identified in the file WINUSER.H and are listed below:

这也意味着EXE文件不再需要重定位信息。

澳门博发娱乐官网 2

Section Header Fields

  • Name . Each section header has a name field up to eight characters long, for which the first character must be a period.
  • PhysicalAddress or VirtualSize . The second field is a union field that is not currently used.
  • VirtualAddress . This field identifies the virtual address in the process's address space to which to load the section. The actual address is created by taking the value of this field and adding it to the ImageBase virtual address in the optional header structure. Keep in mind, though, that if this image file represents a DLL, there is no guarantee that the DLL will be loaded to the ImageBase location requested. So once the file is loaded into a process, the actual ImageBase value should be verified programmatically using GetModuleHandle .
  • SizeOfRawData . This field indicates the FileAlignment -relative size of the section body. The actual size of the section body will be less than or equal to a multiple of FileAlignment in the file. Once the image is loaded into a process's address space, the size of the section body becomes less than or equal to a multiple of SectionAlignment .
  • PointerToRawData . This is an offset to the location of the section body in the file.
  • PointerToRelocations , PointerToLinenumbers , NumberOfRelocations , NumberOfLinenumbers . None of these fields are used in the PE file format.
  • Characteristics . Defines the section characteristics. These values are found both in WINNT.H and in the Portable Executable Format specification located on this CD.
Value Definition
0x00000020 Code section
0x00000040 Initialized data section
0x00000080 Uninitialized data section
0x04000000 Section cannot be cached
0x08000000 Section is not pageable
0x10000000 Section is shared
0x20000000 Executable section
0x40000000 Readable section
0x80000000 Writable section

 

具体资料见:www.microsoft.com/whdc/system/platform/firmware/PECOFF.mspx 中的pecoff.docx文档

WINNT.H

[cpp] view plain copy

 

  1. // Directory Entries  
  2.   
  3. // Export Directory  
  4. #define IMAGE_DIRECTORY_ENTRY_EXPORT         0  
  5. // Import Directory  
  6. #define IMAGE_DIRECTORY_ENTRY_IMPORT         1  
  7. // Resource Directory  
  8. #define IMAGE_DIRECTORY_ENTRY_RESOURCE       2  
  9. // Exception Directory  
  10. #define IMAGE_DIRECTORY_ENTRY_EXCEPTION      3  
  11. // Security Directory  
  12. #define IMAGE_DIRECTORY_ENTRY_SECURITY       4  
  13. // Base Relocation Table  
  14. #define IMAGE_DIRECTORY_ENTRY_BASERELOC      5  
  15. // Debug Directory  
  16. #define IMAGE_DIRECTORY_ENTRY_DEBUG          6  
  17. // Description String  
  18. #define IMAGE_DIRECTORY_ENTRY_COPYRIGHT      7  
  19. // Machine Value (MIPS GP)  
  20. #define IMAGE_DIRECTORY_ENTRY_GLOBALPTR      8  
  21. // TLS Directory  
  22. #define IMAGE_DIRECTORY_ENTRY_TLS            9  
  23. // Load Configuration Directory  
  24. #define IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG    10  

Each data directory is basically a structure defined as an IMAGE_DATA_DIRECTORY . And although data directory entries themselves are the same, each specific directory type is entirely unique. The definition of each defined data directory is described in "Predefined Sections" later in this article.

8

WINNT.H

[cpp] view plain copy

 

  1. typedef struct _IMAGE_EXPORT_DIRECTORY {  
  2.     ULONG   Characteristics;  
  3.     ULONG   TimeDateStamp;  
  4.     USHORT  MajorVersion;  
  5.     USHORT  MinorVersion;  
  6.     ULONG   Name;  
  7.     ULONG   Base;  
  8.     ULONG   NumberOfFunctions;  
  9.     ULONG   NumberOfNames;  
  10.     PULONG  *AddressOfFunctions;  
  11.     PULONG  *AddressOfNames;  
  12.     PUSHORT *AddressOfNameOrdinals;  
  13. } IMAGE_EXPORT_DIRECTORY, *PIMAGE_EXPORT_DIRECTORY;  

The Name field in the export directory identifies the name of the executable module. NumberOfFunctions and NumberOfNames fields indicate how many functions and function names are being exported from the module.

The AddressOfFunctions field is an offset to a list of exported function entry points. The AddressOfNames field is the address of an offset to the beginning of a null-separated list of exported function names. AddressOfNameOrdinals is an offset to a list of ordinal values (each 2 bytes long) for the same exported functions.

The three AddressOf... fields are relative virtual addresses into the address space of a process once the module has been loaded. Once the module is loaded, the relative virtual address should be added to the module base address to get the exact location in the address space of the process. Before the file is loaded, however, the address can be determined by subtracting the section header virtual address (VirtualAddress ) from the given field address, adding the section body offset (PointerToRawData ) to the result, and then using this value as an offset into the image file. The following example illustrates this technique:

The import table address and size. For more information, see section 6.4, “The .idata Section.”

WINNT.H

[cpp] view plain copy

 

  1. typedef struct _IMAGE_RESOURCE_DIRECTORY {  
  2.     ULONG   Characteristics;  
  3.     ULONG   TimeDateStamp;  
  4.     USHORT  MajorVersion;  
  5.     USHORT  MinorVersion;  
  6.     USHORT  NumberOfNamedEntries;  
  7.     USHORT  NumberOfIdEntries;  
  8. } IMAGE_RESOURCE_DIRECTORY, *PIMAGE_RESOURCE_DIRECTORY;  

Looking at the directory structure, you won't find any pointer to the next nodes. Instead, there are two fields, NumberOfNamedEntries and NumberOfIdEntries , used to indicate how many entries are attached to the directory. By attached , I mean the directory entries follow immediately after the directory in the section data. The named entries appear first in ascending alphabetical order, followed by the ID entries in ascending numerical order.

A directory entry consists of two fields, as described in the following IMAGE_RESOURCE_DIRECTORY_ENTRY structure:

8

Export data section, .edata

The .edata section contains export data for an application or DLL. When present, this section contains an export directory for getting to the export information.

The bound import table address and size.

PEFILE.H

#define NTSIGNATURE(a) ((LPVOID)((BYTE *)a +    /
                        ((PIMAGE_DOS_HEADER)a)->e_lfanew))

When manipulating PE file information, I found that there were several locations in the file that I needed to refer to often. Since these locations are merely offsets into the file, it is easier to implement these locations as macros because they provide much better performance than functions do.

Notice that instead of retrieving the offset of the PE file header, this macro retrieves the location of the PE file signature. Starting with Windows and OS/2 executables, .EXE files were given file signatures to specify the intended target operating system. For the PE file format in Windows NT, this signature occurs immediately before the PE file header structure. In versions of Windows and OS/2, the signature is the first word of the file header. Also, for the PE file format, Windows NT uses a DWORD for the signature.

The macro presented above returns the offset of where the file signature appears, regardless of which type of executable file it is. So depending on whether it's a Windows NT file signature or not, the file header exists either after the signature DWORD or at the signature WORD. To resolve this confusion, I wrote the ImageFileType function (following), which returns the type of image file:

内存中区块的对齐单位。区块总是对齐到这个值的整数倍。此字段必须大于或等于 FileAlignment ,默认值是系统页面的大小。32位cpu通常值为 0x1000(十六进制),即4096,即4KB。64位cpu通常为 8kB
FileAlignment ***(必须了解)*****

PEFILE.C

[cpp] view plain copy

 

  1. int    WINAPI RetrieveModuleName (  
  2.     LPVOID    lpFile,  
  3.     HANDLE    hHeap,  
  4.     char      **pszModule)  
  5. {  
  6.   
  7.     PIMAGE_DEBUG_DIRECTORY    pdd;  
  8.     PIMAGE_DEBUG_MISC         pdm = NULL;  
  9.     int                       nCnt;  
  10.   
  11.     if (!(pdd = (PIMAGE_DEBUG_DIRECTORY)ImageDirectoryOffset  
  12.                (lpFile, IMAGE_DIRECTORY_ENTRY_DEBUG)))  
  13.         return 0;  
  14.   
  15.     while (pdd->SizeOfData)  
  16.         {  
  17.         if (pdd->Type == IMAGE_DEBUG_TYPE_MISC)  
  18.             {  
  19.             pdm = (PIMAGE_DEBUG_MISC)  
  20.                 ((DWORD)pdd->PointerToRawData + (DWORD)lpFile);  
  21.   
  22.             nCnt = lstrlen (pdm->Data)*(pdm->Unicode?2:1);  
  23.             *pszModule = (char *)HeapAlloc (hHeap,  
  24.                                             HEAP_ZERO_MEMORY,  
  25.                                             nCnt+1;  
  26.             CopyMemory (*pszModule, pdm->Data, nCnt);  
  27.   
  28.             break;  
  29.             }  
  30.   
  31.         pdd ++;  
  32.         }  
  33.   
  34.     if (pdm != NULL)  
  35.         return nCnt;  
  36.     else  
  37.         return 0;  
  38. }  

As you can see, the structure of the debug directory makes it relatively easy to locate a specific type of debug information. Once the IMAGE_DEBUG_MISC structure is located, extracting the image name is as simple as invoking the CopyMemory function.

As mentioned above, debug information can be stripped into separate .DBG files. The Windows NT SDK includes a utility called REBASE.EXE that serves this purpose. For example, in the following statement an executable image named TEST.EXE is being stripped of debug information:

rebase -b 40000 -x c:/samples/testdir test.exe

The debug information is placed in a new file called TEST.DBG and located in the path specified, in this case c:/samples/testdir. The file begins with a single IMAGE_SEPARATE_DEBUG_HEADER structure, followed by a copy of the section headers that exist in the stripped executable image. Then the .debug section data follows the section headers. So, right after the section headers are the series of IMAGE_DEBUG_DIRECTORY structures and their associated data. The debug information itself retains the same structure as described above for normal image file debug information.

Resource Table

Windows NT Additional Fields

The additional fields added to the Windows NT PE file format provide loader support for much of the Windows NT–specific process behavior. Following is a summary of these fields.

  • ImageBase . Preferred base address in the address space of a process to map the executable image to. The linker that comes with the Microsoft Win32 SDK for Windows NT defaults to 0x00400000, but you can override the default with the -BASE: linker switch.
  • SectionAlignment . Each section is loaded into the address space of a process sequentially, beginning at ImageBase . SectionAlignment dictates the minimum amount of space a section can occupy when loaded—that is, sections are aligned on SectionAlignment boundaries.

    Section alignment can be no less than the page size (currently 4096 bytes on the x 86 platform) and must be a multiple of the page size as dictated by the behavior of Windows NT's virtual memory manager. 4096 bytes is the x 86 linker default, but this can be set using the -ALIGN: linker switch.

  • FileAlignment . Minimum granularity of chunks of information within the image file prior to loading. For example, the linker zero-pads a section body (raw data for a section) up to the nearest FileAlignment boundary in the file. Version 2.39 of the linker mentioned earlier aligns image files on a 0x200-byte granularity. This value is constrained to be a power of 2 between 512 and 65,535.

  • MajorOperatingSystemVersion . Indicates the major version of the Windows NT operating system, currently set to 1 for Windows NT version 1.0.
  • MinorOperatingSystemVersion . Indicates the minor version of the Windows NT operating system, currently set to 0 for Windows NT version 1.0
  • MajorImageVersion . Used to indicate the major version number of the application; in Microsoft Excel version 4.0, it would be 4.
  • MinorImageVersion . Used to indicate the minor version number of the application; in Microsoft Excel version 4.0, it would be 0.
  • MajorSubsystemVersion . Indicates the Windows NT Win32 subsystem major version number, currently set to 3 for Windows NT version 3.10.
  • MinorSubsystemVersion . Indicates the Windows NT Win32 subsystem minor version number, currently set to 10 for Windows NT version 3.10.
  • Reserved1 . Unknown purpose, currently not used by the system and set to zero by the linker.
  • SizeOfImage . Indicates the amount of address space to reserve in the address space for the loaded executable image. This number is influenced greatly by SectionAlignment . For example, consider a system having a fixed page size of 4096 bytes. If you have an executable with 11 sections, each less than 4096 bytes, aligned on a 65,536-byte boundary, the SizeOfImage field would be set to 11 * 65,536 = 720,896 (176 pages). The same file linked with 4096-byte alignment would result in 11 * 4096 = 45,056 (11 pages) for the SizeOfImage field. This is a simple example in which each section requires less than a page of memory. In reality, the linker determines the exact SizeOfImage by figuring each section individually. It first determines how many bytes the section requires, then it rounds up to the nearest page boundary, and finally it rounds page count to the nearest SectionAlignment boundary. The total is then the sum of each section's individual requirement.
  • SizeOfHeaders . This field indicates how much space in the file is used for representing all the file headers, including the MS-DOS header, PE file header, PE optional header, and PE section headers. The section bodies begin at this location in the file.
  • CheckSum . A checksum value is used to validate the executable file at load time. The value is set and verified by the linker. The algorithm used for creating these checksum values is proprietary information and will not be published.
  • Subsystem . Field used to identify the target subsystem for this executable. Each of the possible subsystem values are listed in the WINNT.H file immediately after the IMAGE_OPTIONAL_HEADER structure.
  • DllCharacteristics . Flags used to indicate if a DLL image includes entry points for process and thread initialization and termination.
  • SizeOfStackReserve , SizeOfStackCommit , SizeOfHeapReserve , SizeOfHeapCommit . These fields control the amount of address space to reserve and commit for the stack and default heap. Both the stack and heap have default values of 1 page committed and 16 pages reserved. These values are set with the linker switches -STACKSIZE: and -HEAPSIZE: .
  • LoaderFlags . Tells the loader whether to break on load, debug on load, or the default, which is to let things run normally.
  • NumberOfRvaAndSizes . This field identifies the length of the DataDirectory array that follows. It is important to note that this field is used to identify the size of the array, not the number of valid entries in the array.
  • DataDirectory . The data directory indicates where to find other important components of executable information in the file. It is really nothing more than an array of IMAGE_DATA_DIRECTORY structures that are located at the end of the optional header structure. The current PE file format defines 16 possible data directories, 11 of which are now being used.

The CLR runtime header address and size. For more information, see section 6.10, “The .cormeta Section (Object Only).”

PEFILE.DLL Function Descriptions

PEFILE.DLL consists mainly of functions that either retrieve an offset into a given PE file or copy a portion of the file data to a specific structure. Each function has a single requirement—the first parameter is a pointer to the beginning of the PE file. That is, the file must first be memory-mapped into the address space of your process, and the base location of the file mapping is the value lpFile that you pass as the first parameter to every function.

The function names are meant to be self-explanatory, and each function is listed with a brief comment describing its purpose. If, after reading through the list of functions, you cannot determine what a function is for, refer to the EXEVIEW.EXE sample application to find an example of how the function is used. The following list of function prototypes can also be found in PEFILE.H:

8

PE Optional Header

The next 224 bytes in the executable file make up the PE optional header. Though its name is "optional header," rest assured that this is not an optional entry in PE executable files. A pointer to the optional header is obtained with the OPTHDROFFSET macro:

也就是定义了某块的位置和大小。

Summary of the PE File Format

The PE file format for Windows NT introduces a completely new structure to developers familiar with the Windows and MS-DOS environments. Yet developers familiar with the UNIX environment will find that the PE file format is similar to, if not based on, the COFF specification.

The entire format consists of an MS-DOS MZ header, followed by a real-mode stub program, the PE file signature, the PE file header, the PE optional header, all of the section headers, and finally, all of the section bodies.

The optional header ends with an array of data directory entries that are relative virtual addresses to data directories contained within section bodies. Each data directory indicates how a specific section body's data is structured.

The PE file format has eleven predefined sections, as is common to applications for Windows NT, but each application can define its own unique sections for code and data.

The .debug predefined section also has the capability of being stripped from the file into a separate debug file. If so, a special debug header is used to parse the debug file, and a flag is specified in the PE file header to indicate that the debug data has been stripped.

The export table address and size. For more information see section 6.3, “The .edata Section (Image Only).”

PEFILE.C

[cpp] view plain copy

 

  1. int   WINAPI NumOfSections (  
  2.     LPVOID    lpFile)  
  3. {  
  4.     /* Number of sections is indicated in file header. */  
  5.     return (int)((PIMAGE_FILE_HEADER)  
  6.                   PEFHDROFFSET (lpFile))->NumberOfSections);  
  7. }  

As you can see, the PEFHDROFFSET and the other macros are pretty handy to have around.

TLS Table

PEFILE.C

[cpp] view plain copy

 

  1. int     WINAPI GetListOfResourceTypes (  
  2.     LPVOID    lpFile,  
  3.     HANDLE    hHeap,  
  4.     char      **pszResTypes)  
  5. {  
  6.     PIMAGE_RESOURCE_DIRECTORY          prdRoot;  
  7.     PIMAGE_RESOURCE_DIRECTORY_ENTRY    prde;  
  8.     char                               *pMem;  
  9.     int                                nCnt, i;  
  10.   
  11.   
  12.     /* Get root directory of resource tree. */  
  13.     if ((prdRoot = PIMAGE_RESOURCE_DIRECTORY)ImageDirectoryOffset  
  14.            (lpFile, IMAGE_DIRECTORY_ENTRY_RESOURCE)) == NULL)  
  15.         return 0;  
  16.   
  17.     /* Allocate enough space from heap to cover all types. */  
  18.     nCnt = prdRoot->NumberOfIdEntries * (MAXRESOURCENAME + 1);  
  19.     *pszResTypes = (char *)HeapAlloc (hHeap,  
  20.                                       HEAP_ZERO_MEMORY,  
  21.                                       nCnt);  
  22.     if ((pMem = *pszResTypes) == NULL)  
  23.         return 0;  
  24.   
  25.     /* Set pointer to first resource type entry. */  
  26.     prde = (PIMAGE_RESOURCE_DIRECTORY_ENTRY)((DWORD)prdRoot +  
  27.                sizeof (IMAGE_RESOURCE_DIRECTORY));  
  28.   
  29.     /* Loop through all resource directory entry types. */  
  30.     for (i=0; i<prdRoot->NumberOfIdEntries; i++)  
  31.         {  
  32.         if (LoadString (hDll, prde->Name, pMem, MAXRESOURCENAME))  
  33.             pMem += strlen (pMem) + 1;  
  34.   
  35.         prde++;  
  36.         }  
  37.   
  38.     return nCnt;  
  39. }  

This function returns a list of resource type names in the string identified by pszResTypes . Notice that, at the heart of this function, LoadString is called using the Name field of each resource type directory entry as the string ID. If you look in the PEFILE.RC, you'll see that I defined a series of resource type strings whose IDs are defined the same as the type specifiers in the directory entries. There is also a function in PEFILE.DLL that returns the total number of resource objects in the .rsrc section. It would be rather easy to expand on these functions or write new functions that extracted other information from this section.

pe文件的用户界面使用的子系统类型。定义如下:

Debug information section, .debug

Debug information is initially placed in the .debug section. The PE file format also supports separate debug files (normally identified with a .DBG extension) as a means of collecting debug information in a central location. The debug section contains the debug information, but the debug directories live in the .rdata section mentioned earlier. Each of those directories references debug information in the .debug section. The debug directory structure is defined as an IMAGE_DEBUG_DIRECTORY , as follows:

ImageBase  ***(必须了解)***

Real-Mode Stub Program

The real-mode stub program is an actual program run by MS-DOS when the executable is loaded. For an actual MS-DOS executable image file, the application begins executing here. For successive operating systems, including Windows, OS/2®, and Windows NT, an MS-DOS stub program is placed here that runs instead of the actual application. The programs typically do no more than output a line of text, such as: "This program requires Microsoft Windows v3.1 or greater." Of course, whoever creates the application is able to place any stub they like here, meaning you may often see such things as: "You can't run a Windows NT application on OS/2, it's simply not possible."

When building an application for Windows version 3.1, the linker links a default stub program called WINSTUB.EXE into your executable. You can override the default linker behavior by substituting your own valid MS-DOS–based program in place of WINSTUB and indicating this to the linker with the STUB module definition statement. Applications developed for Windows NT can do the same thing by using the -STUB: linker option when linking the executable file.

结构体源代码如下:

WINNT.H

[cpp] view plain copy

 

  1. typedef struct _IMAGE_RESOURCE_DIRECTORY_ENTRY {  
  2.     ULONG   Name;  
  3.     ULONG   OffsetToData;  
  4. } IMAGE_RESOURCE_DIRECTORY_ENTRY, *PIMAGE_RESOURCE_DIRECTORY_ENTRY;  

The two fields are used for different things depending on the level of the tree. The Name field is used to identify either a type of resource, a resource name, or a resource's language ID. The OffsetToData field is always used to point to a sibling in the tree, either a directory node or a leaf node.

Leaf nodes are the lowest node in the resource tree. They define the size and location of the actual resource data. Each leaf node is represented using the following IMAGE_RESOURCE_DATA_ENTRY structure:

对于EXE文件来说,由于每个文件总是使用独立的虚拟地址空间,优先装入地址不可能被**模块占据,所以EXE总是能够按照这个地址装入

PEFILE.C

[cpp] view plain copy

 

  1. BOOL    WINAPI GetSectionHdrByName (  
  2.     LPVOID                   lpFile,  
  3.     IMAGE_SECTION_HEADER     *sh,  
  4.     char                     *szSection)  
  5. {  
  6.     PIMAGE_SECTION_HEADER    psh;  
  7.     int                      nSections = NumOfSections (lpFile);  
  8.     int                      i;  
  9.   
  10.   
  11.     if ((psh = (PIMAGE_SECTION_HEADER)SECHDROFFSET (lpFile)) !=  
  12.          NULL)  
  13.         {  
  14.         /* find the section by name */  
  15.         for (i=0; i<nSections; i++)  
  16.             {  
  17.             if (!strcmp (psh->Name, szSection))  
  18.                 {  
  19.                 /* copy data to header */  
  20.                 CopyMemory ((LPVOID)sh,  
  21.                             (LPVOID)psh,  
  22.                             sizeof (IMAGE_SECTION_HEADER));  
  23.                 return TRUE;  
  24.                 }  
  25.             else  
  26.                 psh++;  
  27.             }  
  28.         }  
  29.   
  30.     return FALSE;  
  31. }  

The function simply locates the first section header via the SECHDROFFSET macro. Then the function loops through each section, comparing each section's name with the name of the section it's looking for, until it finds the right one. When the section is found, the function copies the data from the memory-mapped file to the structure passed in to the function. The fields of the IMAGE_SECTION_HEADER structure can then be accessed directly from the structure.

The debug data starting address and size. For more information, see section 6.1, “The .debug Section.”

PEFILE.C

[cpp] view plain copy

 

  1. LPVOID  WINAPI GetModuleEntryPoint (  
  2.     LPVOID    lpFile)  
  3. {  
  4.     PIMAGE_OPTIONAL_HEADER   poh;  
  5.   
  6.     poh = (PIMAGE_OPTIONAL_HEADER)OPTHDROFFSET (lpFile);  
  7.   
  8.     if (poh != NULL)  
  9.         return (LPVOID)poh->AddressOfEntryPoint;  
  10.     else  
  11.         return NULL;  
  12. }  
  • BaseOfCode . Relative offset of code (".text" section) in loaded image.
  • BaseOfData . Relative offset of uninitialized data (".bss" section) in loaded image.

200/216

Abstract

The Windows NT™ version 3.1 operating system introduces a new executable file format called the Portable Executable (PE) file format. The Portable Executable File Format specification, though rather vague, has been made available to the public and is included on the Microsoft Developer Network CD (Specs and Strategy, Specifications, Windows NT File Format Specifications).

Yet this specification alone does not provide enough information to make it easy, or even reasonable, for developers to understand the PE file format. This article is meant to address that problem. In it you'll find a thorough explanation of the entire PE file format, along with descriptions of all the necessary structures and source code examples that demonstrate how to use this information.

All of the source code examples that appear in this article are taken from a dynamic-link library (DLL) called PEFILE.DLL. I wrote this DLL simply for the purpose of getting at the important information contained within a PE file. The DLL and its source code are also included on this CD as part of the PEFile sample application; feel free to use the DLL in your own applications. Also, feel free to take the source code and build on it for any specific purpose you may have. At the end of this article, you'll find a brief list of the functions exported from the PEFILE.DLL and an explanation of how to use them. I think you'll find these functions make understanding the PE file format easier to cope with.

8

WINNT.H

[cpp] view plain copy

 

  1. typedef struct _IMAGE_OPTIONAL_HEADER {  
  2.     //  
  3.     // Standard fields.  
  4.     //  
  5.     USHORT  Magic;  
  6.     UCHAR   MajorLinkerVersion;  
  7.     UCHAR   MinorLinkerVersion;  
  8.     ULONG   SizeOfCode;  
  9.     ULONG   SizeOfInitializedData;  
  10.     ULONG   SizeOfUninitializedData;  
  11.     ULONG   AddressOfEntryPoint;  
  12.     ULONG   BaseOfCode;  
  13.     ULONG   BaseOfData;  
  14.     //  
  15.     // NT additional fields.  
  16.     //  
  17.     ULONG   ImageBase;  
  18.     ULONG   SectionAlignment;  
  19.     ULONG   FileAlignment;  
  20.     USHORT  MajorOperatingSystemVersion;  
  21.     USHORT  MinorOperatingSystemVersion;  
  22.     USHORT  MajorImageVersion;  
  23.     USHORT  MinorImageVersion;  
  24.     USHORT  MajorSubsystemVersion;  
  25.     USHORT  MinorSubsystemVersion;  
  26.     ULONG   Reserved1;  
  27.     ULONG   SizeOfImage;  
  28.     ULONG   SizeOfHeaders;  
  29.     ULONG   CheckSum;  
  30.     USHORT  Subsystem;  
  31.     USHORT  DllCharacteristics;  
  32.     ULONG   SizeOfStackReserve;  
  33.     ULONG   SizeOfStackCommit;  
  34.     ULONG   SizeOfHeapReserve;  
  35.     ULONG   SizeOfHeapCommit;  
  36.     ULONG   LoaderFlags;  
  37.     ULONG   NumberOfRvaAndSizes;  
  38.     IMAGE_DATA_DIRECTORY DataDirectory[IMAGE_NUMBEROF_DIRECTORY_ENTRIES];  
  39. } IMAGE_OPTIONAL_HEADER, *PIMAGE_OPTIONAL_HEADER;  

As you can see, the list of fields in this structure is rather lengthy. Rather than bore you with descriptions of all of these fields, I'll simply discuss the useful ones—that is, useful in the context of exploring the PE file format.

Offset

PEFILE.C

[cpp] view plain copy

 

  1. int  WINAPI GetImportFunctionNamesByModule (  
  2.     LPVOID    lpFile,  
  3.     HANDLE    hHeap,  
  4.     char      *pszModule,  
  5.     char      **pszFunctions)  
  6. {  
  7.     PIMAGE_IMPORT_MODULE_DIRECTORY  pid;  
  8.     IMAGE_SECTION_HEADER     idsh;  
  9.     DWORD                    dwBase;  
  10.     int                      nCnt = 0, nSize = 0;  
  11.     DWORD                    dwFunction;  
  12.     char                     *psz;  
  13.   
  14.   
  15.     /* Locate section header for ".idata" section. */  
  16.     if (!GetSectionHdrByName (lpFile, &idsh, ".idata"))  
  17.         return 0;  
  18.   
  19.     pid = (PIMAGE_IMPORT_MODULE_DIRECTORY)ImageDirectoryOffset   
  20.              (lpFile, IMAGE_DIRECTORY_ENTRY_IMPORT);  
  21.   
  22.     dwBase = ((DWORD)pid. idsh.VirtualAddress);  
  23.   
  24.     /* Find module's pid. */  
  25.     while (pid->dwRVAModuleName &&  
  26.            strcmp (pszModule,   
  27.                   (char *)(pid->dwRVAModuleName+dwBase)))  
  28.         pid++;  
  29.   
  30.     /* Exit if the module is not found. */  
  31.     if (!pid->dwRVAModuleName)  
  32.         return 0;  
  33.   
  34.     /* Count number of function names and length of strings. */  
  35.     dwFunction = pid->dwRVAFunctionNameList;  
  36.     while (dwFunction                      &&  
  37.            *(DWORD *)(dwFunction + dwBase) &&  
  38.            *(char *)((*(DWORD *)(dwFunction + dwBase)) +  
  39.             dwBase+2))  
  40.         {  
  41.         nSize += strlen ((char *)((*(DWORD *)(dwFunction +  
  42.              dwBase)) + dwBase+2)) + 1;  
  43.         dwFunction += 4;  
  44.         nCnt++;  
  45.         }  
  46.   
  47.     /* Allocate memory off heap for function names. */  
  48.     *pszFunctions = HeapAlloc (hHeap, HEAP_ZERO_MEMORY, nSize);  
  49.     psz = *pszFunctions;  
  50.   
  51.     /* Copy function names to memory pointer. */  
  52.     dwFunction = pid->dwRVAFunctionNameList;  
  53.     while (dwFunction                      &&  
  54.            *(DWORD *)(dwFunction + dwBase) &&  
  55.            *((char *)((*(DWORD *)(dwFunction + dwBase)) +  
  56.             dwBase+2)))  
  57.         {  
  58.         strcpy (psz, (char *)((*(DWORD *)(dwFunction + dwBase)) +  
  59.                 dwBase+2));  
  60.         psz += strlen((char *)((*(DWORD *)(dwFunction + dwBase))+  
  61.                 dwBase+2)) + 1;  
  62.         dwFunction += 4;  
  63.         }  
  64.   
  65.     return nCnt;  
  66. }  

Like the GetImportModuleNames function, this function relies on the end of each list of information to have a zeroed entry. In this case, the list of function names ends with one that is zero.

The final field, dwRVAFunctionAddressList , is a relative virtual address to a list of virtual addresses that will be placed in the section data by the loader when the file is loaded. Before the file is loaded, however, these virtual addresses are replaced by relative virtual addresses that correspond exactly to the list of function names. So before the file is loaded, there are two identical lists of relative virtual addresses pointing to imported function names.

本文由胜博发-操作发布,转载请注明来源:那么只需要将这个入口地址指向附加的代码就可