Analysis of PE file resources

Source: Internet
Author: User

Text/figure df
PE file, the full name of Portable Executable file, is a common format for Windows system Executable files, such as EXE, DLL, OCX, and even SYS files that we usually contact belong to the scope of PE files. To easily reference other types of resources in an executable file, the PE file has an independent resource segment that links all the resource files required for program execution to the PE file for ease of use. Today, we will study the content and format of PE file resource segments.
Memory ing File
As the saying goes, if you want to do your best, you can use your tools first. To analyze the PE file structure, we must map the PE file to the memory space of the process. Here we strongly recommend the new features supported by Windows 2000 and later versions, and the memory ing file, this mechanism can map a file completely or partially into the address space of the current process, and the system hosts all disk IO operations to automatically implement functions such as buffer management and read/write control, high efficiency.
Here we provide a file read class written based on this technology. This class maps the first address pointer and size of a specific file in the constructor by referencing it, then the program can use the pointer just like the local memory. The class code is as follows.

// Statement
Class CMapFile
{
Public:
CMapFile (LPCTSTR pPath, bool bWrite, PVOID & pMap, DWORD & dwFileSize );
~ CMapFile (void );
Private:
HANDLE hFileHandle;
HANDLE hFileMapHandle;
PVOID & pImageView;
DWORD & dwSize;
};
// Constructor
CMapFile: CMapFile (LPCTSTR pPath, bool bWrite, PVOID & pMap, DWORD & dwFileSize)
: PImageView (pMap)
, DwSize (dwFileSize)
{
This-> hFileHandle = INVALID_HANDLE_VALUE;
This-> hFileMapHandle = INVALID_HANDLE_VALUE;
This-> pImageView = NULL;
This-> dwSize = 0;
Try
{
If (bWrite)
{
This-> hFileHandle = CreateFile (pPath, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL );
}
Else
{
This-> hFileHandle = CreateFile (pPath, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL );
}
If (this-> hFileHandle = INVALID_HANDLE_VALUE)
{
Throw (0 );
}
This-> dwSize = GetFileSize (this-> hFileHandle, NULL );
If (this-> dwSize = 0)
{
Throw (1 );
}
If (bWrite)
{
This-> hFileMapHandle = CreateFileMapping (this-> hFileHandle, NULL, PAGE_READWRITE, 0, 0, NULL );
}
Else
{
This-> hFileMapHandle = CreateFileMapping (this-> hFileHandle, NULL, PAGE_READONLY, 0, 0, NULL );
}
If (this-> hFileMapHandle = INVALID_HANDLE_VALUE)
{
Throw (2 );
}
CloseHandle (this-> hFileHandle );
This-> hFileHandle = INVALID_HANDLE_VALUE;
If (bWrite)
{
This-> pImageView = MapViewOfFile (this-> hFileMapHandle, FILE_MAP_WRITE | FILE_MAP_READ, 0, 0 );
}
Else
{
This-> pImageView = MapViewOfFile (this-> hFileMapHandle, FILE_MAP_READ, 0, 0 );
}
If (this-> pImageView = NULL)
{
Throw (4 );
}
}
Catch (...)
{
This-> pImageView = NULL;
}

}
// Destructor
CMapFile ::~ CMapFile (void)
{
Try
{
If (this-> pImageView! = NULL)
{
UnmapViewOfFile (this-> pImageView );
}
If (this-> hFileMapHandle! = INVALID_HANDLE_VALUE)
{
CloseHandle (this-> hFileMapHandle );
}
If (this-> hFileHandle! = INVALID_HANDLE_VALUE)
{
CloseHandle (this-> hFileHandle );
}
}
Catch (...)
{
}
}

Before studying PE file resource segments, we must understand the structure of PE file headers. Next we will analyze the format of the PE file header. The overall structure of the PE File Header 1 shows that the format of the PE file is relatively complex. In the following section, I will analyze the meaning of each part.

Figure 1 PE file structure

MS-DOS head
The first structure is the MS-DOS header, this is designed to be compatible with the old DOS program, if a Win32 program runs in DOS mode (the so-called DOS mode refers to the pure DOS environment, instead of Windows console), the DOS header will locate the execution to the MS-DOS real-mode residual program, the program will call int 21 to interrupt the output of a string "This program cannot be run in DOS mode ", then exit directly. The MS-DOS header is defined in winnt. h.
Typedef struct _ IMAGE_DOS_HEADER {// DOS. EXE header
WORD e_magic; // Magic number
WORD e_cblp; // Bytes on last page of file
WORD e_cp; // Pages in file
WORD e_crlc; // Relocations
WORD e_cparhdr; // Size of header in paragraphs
WORD e_minalloc; // Minimum extra paragraphs needed
WORD e_maxalloc; // Maximum extra paragraphs needed
WORD e_ss; // Initial (relative) SS value
WORD e_sp; // Initial SP value
WORD e_csum; // Checksum
WORD e_ip; // Initial IP value
WORD e_cs; // Initial (relative) CS value
WORD e_lfarlc; // File address of relocation table
WORD e_ovno; // Overlay number
WORD e_res [4]; // Reserved words
WORD e_oemid; // OEM identifier (for e_oeminfo)
WORD e_oeminfo; // OEM information; e_oemid specific
WORD e_res2 [10]; // Reserved words
LONG e_lfanew; // File address of new exe header
} IMAGE_DOS_HEADER, * PIMAGE_DOS_HEADER;

The first member variable e_magic is called a magic number and is used to represent a MS-DOS-compatible file type. All MS-DOS-compatible executable files set this value to 0x5A4D, representing the ASCII character MZ. This is why MS-DOS headers are sometimes called MZ headers.
The rest of the member variables are basically designed for the real-time mode of DOS, but now there is no practical effect, except for the last member variable e_lfanew. This member variable is used to indicate the offset of the PE Header in this PE file. Run the following code to obtain the PE Header address:

BYTE * pFileImage = (BYTE *) pPeImage;
PIMAGE_DOS_HEADER pDosHeader = (PIMAGE_DOS_HEADER) pFileImage;
PIMAGE_FILE_HEADER pFileHeader = (PIMAGE_FILE_HEADER) (pFileImage + pDosHeader-> e_lfanew + 4 );

Note: When calculating the offset address, in addition to the offset pDosHeader-> e_lfanew, there is also a DWORD offset. This DWORD stores the PE file identifier, and the value is 0x4550, it corresponds to the ASCII character "PE ".
PE Header
Next we will introduce the content of the PE Header. The PE Header is defined as follows in "winnt. h.

Typedef struct _ IMAGE_FILE_HEADER {
WORDMachine;
WORDNumberOfSections;
DWORD TimeDateStamp;
DWORD PointerToSymbolTable;
DWORD NumberOfSymbols;
WORDSizeOfOptionalHeader;
WORDCharacteristics;
} IMAGE_FILE_HEADER, * PIMAGE_FILE_HEADER;

This structure is relatively simple. Machine indicates the type of the target Machine that the executable file is built. The Machine value obtained by this program is 0x14c, which indicates i386; numberOfSection indicates the number of segment headers and number of segment entities in this PE file. Each segment header and segment entity are arranged consecutively in the file, therefore, it is necessary to determine where the segment header and the segment object end. TimeDataStamp is a timestamp variable. PointerToSymbolTable and NumberOfSymbols determine the position and size of the symbol table. SizeOfOptionalHeader indicates the size of the Option header. The option header is linearly arranged behind the PE file header. This structure is described later, but you should not be confused by the name, the option header is a vital structure for executing PE files, not "Optional ". Characteristics indicates some Characteristics of a file. For example, how to detach a debug file for an executable file.
Option Header
The option header is defined in "winnt. h" as follows.

Typedef struct _ IMAGE_OPTIONAL_HEADER {
// Standard fields.
WORDMagic;
BYTEMajorLinkerVersion;
BYTEMinorLinkerVersion;
DWORD SizeOfCode;
DWORD SizeOfInitializedData;
DWORD SizeOfUninitializedData;
DWORD AddressOfEntryPoint;
DWORD BaseOfCode;
DWORD BaseOfData;
// NT additional fields.
DWORD ImageBase;
DWORD SectionAlignment;
DWORD FileAlignment;
WORDMajorOperatingSystemVersion;
WORDMinorOperatingSystemVersion;
WORDMajorImageVersion;
WORDMinorImageVersion;
WORDMajorSubsystemVersion;
WORDMinorSubsystemVersion;
DWORD Win32VersionValue;
DWORD SizeOfImage;
DWORD SizeOfHeaders;
DWORD CheckSum;
WORDSubsystem;
WORDDllCharacteristics;
DWORD SizeOfStackReserve;
DWORD SizeOfStackCommit;
DWORD SizeOfHeapReserve;
DWORD SizeOfHeapCommit;
DWORD LoaderFlags;
DWORD NumberOfRvaAndSizes;
IMAGE_DATA_DIRECTORY DataDirectory [IM

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.