美文网首页
基础C++教学⮱⮱002【目标文件简介】2019-11-17

基础C++教学⮱⮱002【目标文件简介】2019-11-17

作者: 平知 | 来源:发表于2019-11-17 11:10 被阅读0次

    ←↑→↓↖↙↗↘↕⏤
    unicode=Geometric Shapes
    ▶ 仅仅个别字不同的时候的对比标识

    ◉ 着重强调
    Miscellaneous Symbols

    Dingbats
    ✍ 重点记忆,个人总结的点,或者知识。
    ✎✎

    章节号 内容            
    1图片格式(png) 宽度大于620px,保持高宽比减低为620px
    1-1 应用
    1-1-1 方法

    第1章节  目标文件概述

      编译器编译源代码后生成的文件叫做目标文件。目标文件从结构上讲,它是已经编译后的可执行文件格式, 只是跟真正的可执行文件在结构上稍有不同。
      使用前述的二进制工具objdump来具体查看一下:

    C:\Users\lo\Desktop\New Folder\1\1>objdump -f main.o
    
    main.o:     file format pe-i386
    architecture: i386, flags 0x00000039:
    HAS_RELOC, HAS_DEBUG, HAS_SYMS, HAS_LOCALS
    start address 0x00000000
    
    
    C:\Users\lo\Desktop\New Folder\1\1>objdump -f main.oo
    
    main.oo:     file format pei-i386
    architecture: i386, flags 0x0000013a:
    EXEC_P, HAS_DEBUG, HAS_SYMS, HAS_LOCALS, D_PAGED
    start address 0x00401280
    

      PC下主流的可执行文件格式主要是Windows下的PE(Portable Executable)和Linux的ELF (Executable Linkable Format),都是COFF (Common file format)格式的变种 。
      目标文件就是源代码编译后但未进行链接的那些中间文件。目标文件可以说还比较“单纯”,没有链接一些程序运行所必要的库,可以从体量和内容两个方面比较一斑。

      体积差:
      比较反汇编后的代码量,把输入到屏幕的内容重定向到1.txt和2.txt文件中:
    objdump -d main.oo > 1.txt
    objdump -d main.o > 2.txt
    

      另有:动态链接库DLL之Dynamic Linking Library,含 Windows的.dll和Linux的.so;
      以及静态链接库之Static Linking Library ,含Windows的lib和Linux的.a 文件都按照可执行文 件格式存储。
      它们在Windows下都按照PE-COFF格式存储,Linux下按照ELF格式存储。

    • 1-1 目标文件概述—在windows下查看COFF信息

      Common Object File Format (COFF)文中提及工具dumpbin,本机未安装相关的SDK,故想能否从其他已安装visual studio的电脑上直接拷贝。
      具体操作过程:
      1、在目标电脑上搜索dumpbin,找到正常能正常运行的


      2、复制到其他文件夹内测试运行

      3、复制到其他文件夹内测试运行

      4、把提示缺少的link.exe复制到相同位置

      5、提示缺少dll

      6、继续复制dll

      7、运行成功

      拷贝至本机测试运行

      成功!
      下面使用dumpbin对上面提及的mian.o和main.oo测试。可见两个文件的type和明细均识别不同。
    • 1-2 目标文件概述—PE文件格式

      PE Format根据微软文档,上述的.o和.oo文件具体格式有所区别,其中上述的.o文件应该对应于object files;本例中的.oo文件应该对应于executable (image) files。上图的type字段也得出同样结论。

      1-2-1. 目标文件概述—PE文件格式—COFF文件头

       根据文档描述,在object file(上述.o文件)的开头或者在image file(上述.oo文件)的signature字段之后,是一个标准的COFF文件头。
       COFF File Header (Object and Image)
      At the beginning of an object file, or immediately after the signature of an image file, is a standard COFF file header in the following format. Note that the Windows loader limits the number of sections to 96.

       COFF 文件头格式如下

    | Offset | Size | Field                | Description                                                  |
    | 0      | 2    | Machine              | The number that identifies the type of target machine. For more information, see [Machine Types](https://docs.microsoft.com/en-us/windows/win32/debug/pe-format#machine-types). |
    | 2      | 2    | NumberOfSections     | The number of sections. This indicates the size of the section table, which immediately follows the headers. |
    | 4      | 4    | TimeDateStamp        | The low 32 bits of the number of seconds since 00:00 January 1, 1970 (a C run-time time_t value), that indicates when the file was created. |
    | 8      | 4    | PointerToSymbolTable | The file offset of the COFF symbol table, or zero if no COFF symbol table is present. This value should be zero for an image because COFF debugging information is deprecated. |
    | 12     | 4    | NumberOfSymbols      | The number of entries in the symbol table. This data can be used to locate the string table, which immediately follows the symbol table. This value should be zero for an image because COFF debugging information is deprecated. |
    | 16     | 2    | SizeOfOptionalHeader | The size of the optional header, which is required for executable files but not for object files. This value should be zero for an object file. For a description of the header format, see [Optional Header (Image Only)](https://docs.microsoft.com/en-us/windows/win32/debug/pe-format#optional-header-image-only). |
    | 18     | 2    | Characteristics      | The flags that indicate the attributes of the file. For specific flag values, see [Characteristics](https://docs.microsoft.com/en-us/windows/win32/debug/pe-format#characteristics). |
    

      上表第一行的 “ Machine ” Field 数据表示如下(Machine Types):

    | Constant                     | Value  | Description                                                  |
    | IMAGE_FILE_MACHINE_UNKNOWN   | 0x0    | The contents of this field are assumed to be applicable to any machine type |
    | IMAGE_FILE_MACHINE_AM33      | 0x1d3  | Matsushita AM33                                              |
    | IMAGE_FILE_MACHINE_AMD64     | 0x8664 | x64                                                          |
    | IMAGE_FILE_MACHINE_ARM       | 0x1c0  | ARM little endian                                            |
    | IMAGE_FILE_MACHINE_ARM64     | 0xaa64 | ARM64 little endian                                          |
    | IMAGE_FILE_MACHINE_ARMNT     | 0x1c4  | ARM Thumb-2 little endian                                    |
    | IMAGE_FILE_MACHINE_EBC       | 0xebc  | EFI byte code                                                |
    | IMAGE_FILE_MACHINE_I386      | 0x14c  | Intel 386 or later processors and compatible processors      |
    | IMAGE_FILE_MACHINE_IA64      | 0x200  | Intel Itanium processor family                               |
    | IMAGE_FILE_MACHINE_M32R      | 0x9041 | Mitsubishi M32R little endian                                |
    | IMAGE_FILE_MACHINE_MIPS16    | 0x266  | MIPS16                                                       |
    | IMAGE_FILE_MACHINE_MIPSFPU   | 0x366  | MIPS with FPU                                                |
    | IMAGE_FILE_MACHINE_MIPSFPU16 | 0x466  | MIPS16 with FPU                                              |
    | IMAGE_FILE_MACHINE_POWERPC   | 0x1f0  | Power PC little endian                                       |
    | IMAGE_FILE_MACHINE_POWERPCFP | 0x1f1  | Power PC with floating point support                         |
    | IMAGE_FILE_MACHINE_R4000     | 0x166  | MIPS little endian                                           |
    | IMAGE_FILE_MACHINE_RISCV32   | 0x5032 | RISC-V 32-bit address space                                  |
    | IMAGE_FILE_MACHINE_RISCV64   | 0x5064 | RISC-V 64-bit address space                                  |
    | IMAGE_FILE_MACHINE_RISCV128  | 0x5128 | RISC-V 128-bit address space                                 |
    | IMAGE_FILE_MACHINE_SH3       | 0x1a2  | Hitachi SH3                                                  |
    | IMAGE_FILE_MACHINE_SH3DSP    | 0x1a3  | Hitachi SH3 DSP                                              |
    | IMAGE_FILE_MACHINE_SH4       | 0x1a6  | Hitachi SH4                                                  |
    | IMAGE_FILE_MACHINE_SH5       | 0x1a8  | Hitachi SH5                                                  |
    | IMAGE_FILE_MACHINE_THUMB     | 0x1c2  | Thumb                                                        |
    | IMAGE_FILE_MACHINE_WCEMIPSV2 | 0x169  | MIPS little-endian WCE v2                                    |
    
    
      有了这些内容,现在可以对照mian.o文件的内容来具体看一看(使用winhex打开main.o文件):

      首先看前两个字节,内容为4C 01的位置。根据COFF文件头的格式,可以知道前2个字节的值代表着目标机器的类型,具体数据应该是符合上表的多个值的其中一个才对。但是。。。。。。,似乎找不到对应的值。究竟是什么情况?

      再次使用dumpbin工具来验证一下我们的猜想(使用/HEADERS参数):
      ok,输出的结果对比Value值和Description,已经对应上了:
    | Constant                     | Value  | Description                                                  |
    | IMAGE_FILE_MACHINE_I386      | 0x14c  | Intel 386 or later processors and compatible processors      |
    

      ?为什么会产生一个“4C 01”和“14C”(等于014C)的“视觉上”的差异
      这和一个概念:字节序Endianness有关。
      摘要:In computing, endianness refers to the order of bytes (or sometimes bits) within a binary representation of a number. It can also be used more generally to refer to the internal ordering of any representation, such as the digits in a numeral system or the sections of a date.
      摘要:In its most common usage, endianness indicates the ordering of bytes within a multi-byte number. A big-endian ordering places the most significant byte first and the least significant byte last, while a little-endian ordering does the opposite. For example, consider the unsigned hexadecimal number 0x1234, which requires at least two bytes to represent. In a big-endian ordering they would be [ 0x12, 0x34 ], while in a little-endian ordering, the bytes would be arranged [ 0x34, 0x12 ].
      big-endian
      ▶most significant byte (字面意思为)重要的字节 first 前
      ▶least significant byte (字面意思为)次要的字节 last 后
      little-endian
      ▶most significant byte (字面意思为)重要的字节 last 后
      ▶least significant byte (字面意思为)次要的字节 first 前
      便于记忆,可以想成:“大重(马走在)前,小重(马走在)后”

      那所谓“重要”字节何解?根据摘要的解释,一个数的高位=重;低位=次。
      同理记之为:“位高(权)重”

      ✍综合记忆:“位高重。大重前,小重后”

      摘要:The Intel x86 and AMD64 / x86-64 series of processors use the little-endian format.
      intel使用的是little-endian。

      综上所述:0x1 4c在PE文件中具体表现出来的形式,就是应该参照上面口诀“位高重,小重后”,而表现为

    地址 00 01
    数据 4c 01
      1-2-2. 目标文件概述—PE文件格式—MS-DOS Stub (Image Only)

      The MS-DOS stub is a valid application that runs under MS-DOS. It is placed at the front of the EXE image. The linker places a default stub here, which prints out the message "This program cannot be run in DOS mode" when the image is run in MS-DOS. The user can specify a different stub by using the /STUB linker option.
      这个官方文档并未详述这个stub的字段构成。但是根据MS-DOS_EXE_Files能有所了解,其中为stub构建了一个具体的c语言的structure:

     struct DOS_Header 
     {
    // short is 2 bytes, long is 4 bytes
         char signature[2] = { 'M', 'Z' };
         short lastsize;
         short nblocks;
         short nreloc;
         short hdrsize;
         short minalloc;
         short maxalloc;
         void *ss; // 2 byte value
         void *sp; // 2 byte value
         short checksum;
         void *ip; // 2 byte value
         void *cs; // 2 byte value
         short relocpos;
         short noverlay;
         short reserved1[4];
         short oem_id;
         short oem_info;
         short reserved2[10];
         long  e_lfanew; // Offset to the 'PE\0\0' signature relative to the beginning of the file
     }
    
      结合main.oo的文件内容来看:   把上图数据放到excel中来,方便注解:

      At location 0x3c, the stub has the file offset to the PE signature. This information enables Windows to properly execute the image file, even though it has an MS-DOS stub. This file offset is placed at location 0x3c during linking.
      根据微软的文档指出,在0x3c的位置,存放的是PE signature的偏移量。下面具体来看看:


      根据上文所述,0x3c位置对应“long e_lfanew”,是一个4字节的数据块,那么根据winhex显示,结合windows的little-endian字节序,这个偏移量的值就为0x00000080。按照绿色箭头所示,这个偏移量的地址的前4个字节内容,正好就是Signature。
      This signature is "PE\0\0" (the letters "P" and "E" followed by two null bytes).
      根据文档描述,signature之后紧接的就是COFF header了。

      具体比对COFF header 各个字段和值:
    C:\Users\lo\Desktop\New Folder\1\1>dumpbin /HEADERS main.oo
    Microsoft (R) COFF/PE Dumper Version 10.00.30319.01
    Copyright (C) Microsoft Corporation.  All rights reserved.
    Dump of file main.oo
    PE signature found
    File Type: EXECUTABLE IMAGE
    FILE HEADER VALUES
                 14C machine (x86)
                  10 number of sections
                   0 time date stamp Thu Jan 01 08:00:00 1970
               CD200 file pointer to symbol table
                3A0C number of symbols
                  E0 size of optional header
                 107 characteristics
                       Relocations stripped
                       Executable
                       Line numbers stripped
                       32 bit word machine
    

      前6个字段能够直接对应数值,现在着重看第七个字段characteristics:

    The Characteristics field contains flags that indicate attributes of the object or image file. The following flags are currently defined:
    
    | Flag                                | Value  | Description                                                  |
    | IMAGE_FILE_RELOCS_STRIPPED          | 0x0001 | Image only, Windows CE, and Microsoft Windows NT and later. This indicates that the file does not contain base relocations and must therefore be loaded at its preferred base address. If the base address is not available, the loader reports an error. The default behavior of the linker is to strip base relocations from executable (EXE) files. |
    | IMAGE_FILE_EXECUTABLE_IMAGE         | 0x0002 | Image only. This indicates that the image file is valid and can be run. If this flag is not set, it indicates a linker error. |
    | IMAGE_FILE_LINE_NUMS_STRIPPED       | 0x0004 | COFF line numbers have been removed. This flag is deprecated and should be zero. |
    | IMAGE_FILE_LOCAL_SYMS_STRIPPED      | 0x0008 | COFF symbol table entries for local symbols have been removed. This flag is deprecated and should be zero. |
    | IMAGE_FILE_AGGRESSIVE_WS_TRIM       | 0x0010 | Obsolete. Aggressively trim working set. This flag is deprecated for Windows 2000 and later and must be zero. |
    | IMAGE_FILE_LARGE_ADDRESS_ AWARE     | 0x0020 | Application can handle > 2-GB addresses.                     |
    |                                     | 0x0040 | This flag is reserved for future use.                        |
    | IMAGE_FILE_BYTES_REVERSED_LO        | 0x0080 | Little endian: the least significant bit (LSB) precedes the most significant bit (MSB) in memory. This flag is deprecated and should be zero. |
    | IMAGE_FILE_32BIT_MACHINE            | 0x0100 | Machine is based on a 32-bit-word architecture.              |
    | IMAGE_FILE_DEBUG_STRIPPED           | 0x0200 | Debugging information is removed from the image file.        |
    | IMAGE_FILE_REMOVABLE_RUN_ FROM_SWAP | 0x0400 | If the image is on removable media, fully load it and copy it to the swap file. |
    | IMAGE_FILE_NET_RUN_FROM_SWAP        | 0x0800 | If the image is on network media, fully load it and copy it to the swap file. |
    | IMAGE_FILE_SYSTEM                   | 0x1000 | The image file is a system file, not a user program.         |
    | IMAGE_FILE_DLL                      | 0x2000 | The image file is a dynamic-link library (DLL). Such files are considered executable files for almost all purposes, although they cannot be directly run. |
    | IMAGE_FILE_UP_SYSTEM_ONLY           | 0x4000 | The file should be run only on a uniprocessor machine.       |
    | IMAGE_FILE_BYTES_REVERSED_HI        | 0x8000 | Big endian: the MSB precedes the LSB in memory. This flag is deprecated and should be zero. |
    

      根据表内容和文档的表述,可以看出这是一种flags的表示法,即用一个不同位置的二进制的1来却别各种不同的属性。107对应二进制的000100000111,即对应了表中标绿的属性。这和使用dumpbin后显示出的结果是对应一致的。

      1-2-3. 目标文件概述—PE文件格式—Optional Header (Image Only)

      ◉紧跟着COFF header出现的就是Optional Header。
      Optional Header主要分为3个大部分,不同的文件类型各大部分有所区别:

    | Offset (PE32/PE32+) | Size (PE32/PE32+) | Header part             | Description                                                  |
    
    | 0                   | 28/24             | Standard fields         | Fields that are defined for all implementations of COFF, including UNIX. |
    | 28/24               | 68/88             | Windows-specific fields | Additional fields to support specific features of Windows (for example, subsystems). |
    | 96/112              | Variable          | Data directories        | Address/size pairs for special tables that are found in the image file and are used by the operating system (for example, the import table and the export table). |
    
      上表中出现的PE32/PE32+类型,由紧跟着COFF header之后的2个字节内容决定:

      具体定义如下:

    | Magic number | PE format |
    | 0x10b        | PE32      |
    | 0x20b        | PE32+     |
    

      根据上表定义和上图所示,mian.oo显然属于PE32。
      现在的问题,知道了Optional Header的开头了,如何确定结尾?
      现在轮到了COFF Header上场了:

    C:\Users\lo\Desktop\New Folder\1\1>dumpbin /HEADERS main.oo
    .
    .
    .
                  E0 size of optional header
    .
    .
    .//略去无关部分
    
      是的,COFF Header的一个字段值,就标识了optional header的长度。这里0xE0等于10进制的224。其中224除以16正好是14个整行。除去开头的半行和结尾的半行,中间为13个整行,加起来正好14整行。

      下面给出了不同的Optional Header的C语言结构定义,注意这里的signature和magic是等价的。

    64 bit PE Optional Header presented as a C data structure:            |32 bit version of the PE Optional Header presented as a C data structure:
    
    | 1    | short signature;  /*等于上述的magic */                        | short signature; //decimal number 267 for  32 bit, 523 for 64 bit, and 263 for a ROM image. |
    | 2    | char  MajorLinkerVersion;                                    | char MajorLinkerVersion;                                     |
    | 3    | char  MinorLinkerVersion;                                    | char MinorLinkerVersion;                                     |
    | 4    | long SizeOfCode;                                             | long SizeOfCode;                                             |
    | 5    | long  SizeOfInitializedData;                                 | long SizeOfInitializedData;                                  |
    | 6    | long  SizeOfUninitializedData;                               | long SizeOfUninitializedData;                                |
    | 7    | long  AddressOfEntryPoint;                                   | long AddressOfEntryPoint; //The RVA of the code entry point  |
    | 8    | long BaseOfCode;                                             | long BaseOfCode;                                             |
    | 9    | /*The next 21 fields are an extension to the COFF   */       | long BaseOfData;                                             |
    | 10   | long long ImageBase;                                         | /*The next 21 fields  are an extension to the COFF optional header format*/ |
    | 11   | long SectionAlignment;                                       | long ImageBase;                                              |
    | 12   | long FileAlignment;                                          | long SectionAlignment;                                       |
    | 13   | short MajorOSVersion;                                        | long FileAlignment;                                          |
    | 14   | short MinorOSVersion;                                        | short MajorOSVersion;                                        |
    | 15   | short  MajorImageVersion;                                    | short MinorOSVersion;                                        |
    | 16   | short  MinorImageVersion;                                    | short MajorImageVersion;                                     |
    | 17   | short  MajorSubsystemVersion;                                | short MinorImageVersion;                                     |
    | 18   | short  MinorSubsystemVersion;                                | short MajorSubsystemVersion;                                 |
    | 19   | long Win32VersionValue;                                      | short MinorSubsystemVersion;                                 |
    | 20   | long SizeOfImage;                                            | long Win32VersionValue;                                      |
    | 21   | long SizeOfHeaders;                                          | long SizeOfImage;                                            |
    | 22   | long Checksum;                                               | long SizeOfHeaders;                                          |
    | 23   | short Subsystem;                                             | long Checksum;                                               |
    | 24   | short  DLLCharacteristics;                                   | short Subsystem;                                             |
    | 25   | long long SizeOfStackReserve;                                | short DLLCharacteristics;                                    |
    | 26   | long long SizeOfStackCommit;                                 | long SizeOfStackReserve;                                     |
    | 27   | long long SizeOfHeapReserve;                                 | long SizeOfStackCommit;                                      |
    | 28   | long long SizeOfHeapCommit;                                  | long SizeOfHeapReserve;                                      |
    | 29   | long LoaderFlags;                                            | long SizeOfHeapCommit;                                       |
    | 30   | long  NumberOfRvaAndSizes;                                   | long LoaderFlags;                                            |
    | 31   | data_directory DataDirectory[NumberOfRvaAndSizes];           | long NumberOfRvaAndSizes;                                    |
    | 32   |                                                              | data_directory DataDirectory[NumberOfRvaAndSizes];   //Can have any  number of elements, matching the number in NumberOfRvaAndSizes. |
    

      上表中的data_directory数据结构意定义如下:

    /*
    long is 4 bytes
    */
     struct data_directory
     { 
        long VirtualAddress;
        long Size;
     }
    
      把数据填入excel表格具体分析:

      因NumberOfRvaAndSizes值为0x10,等于二进制16;又因data_directory为一个整体8字节的结构,所以NumberOfRvaAndSizes之后应该有16个8字节。具体见上图↑。
      上述16个8字节,与如下16个描述对应,根据下面的描述,可以把excel表格作进一步完善:

    | Constant Name                            | Value | Description                                      | Offset PE(32 bit) | Offset PE32+(64 bit) |
    | **IMAGE_DIRECTORY_ENTRY_EXPORT**         | 0     | Export Directory                                 | 96                | 112                  |
    | **IMAGE_DIRECTORY_ENTRY_IMPORT**         | 1     | Import Directory                                 | 104               | 120                  |
    | **IMAGE_DIRECTORY_ENTRY_RESOURCE**       | 2     | Resource Directory                               | 112               | 128                  |
    | **IMAGE_DIRECTORY_ENTRY_EXCEPTION**      | 3     | Exception Directory                              | 120               | 136                  |
    | **IMAGE_DIRECTORY_ENTRY_SECURITY**       | 4     | Security Directory                               | 128               | 144                  |
    | **IMAGE_DIRECTORY_ENTRY_BASERELOC**      | 5     | Base Relocation Table                            | 136               | 152                  |
    | **IMAGE_DIRECTORY_ENTRY_DEBUG**          | 6     | Debug Directory                                  | 144               | 160                  |
    | **IMAGE_DIRECTORY_ENTRY_ARCHITECTURE**   | 7     | Architecture specific data                       | 152               | 168                  |
    | **IMAGE_DIRECTORY_ENTRY_GLOBALPTR**      | 8     | Global pointer register relative virtual address | 160               | 176                  |
    | **IMAGE_DIRECTORY_ENTRY_TLS**            | 9     | Thread Local Storage directory                   | 168               | 184                  |
    | **IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG**    | 10    | Load Configuration directory                     | 176               | 192                  |
    | **IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT**   | 11    | Bound Import directory                           | 184               | 200                  |
    | **IMAGE_DIRECTORY_ENTRY_IAT**            | 12    | Import Address Table                             | 192               | 208                  |
    | **IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT**   | 13    | Delay Import table                               | 200               | 216                  |
    | **IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR** | 14    | COM descriptor table                             | 208               | 224                  |
    | No constant name                         | 15    | Reserved                                         | 216               | 232                  |
    
      1-2-4. 目标文件概述—PE文件格式—Section Table (Section Headers)

      Immediately after the PE Optional Header we find a section table.
       The number of structures that we find in the file are determined by the member NumberOfSections in the COFF Header.
      Optional Header后紧接的就是section table,它由多个 IMAGE_SECTION_HEADER structures构成,每一个都有40字节大小。structures的数量在COFF header中有指明,本例中共有16个。具体定义如下:

    struct IMAGE_SECTION_HEADER 
     {
    // short is 2 bytes
    // long is 4 bytes
      char  Name[IMAGE_SIZEOF_SHORT_NAME]; // IMAGE_SIZEOF_SHORT_NAME is 8 bytes
      union {
        long PhysicalAddress;
        long VirtualSize;
      } Misc;// union is 4 bytes
      long  VirtualAddress;
      long  SizeOfRawData;
      long  PointerToRawData;
      long  PointerToRelocations;
      long  PointerToLinenumbers;
      short NumberOfRelocations;
      short NumberOfLinenumbers;
      long  Characteristics;
     }
    

      微软官方说明如下:

    | Offset | Size | Field                | Description                                                  |
    
    | 0      | 8    | Name                 | An 8-byte, null-padded UTF-8 encoded string. If the string is exactly 8 characters long, there is no terminating null. For longer names, this field contains a slash (/) that is followed by an ASCII representation of a decimal number that is an offset into the string table. Executable images do not use a string table and do not support section names longer than 8 characters. Long names in object files are truncated if they are emitted to an executable file. |
    | 8      | 4    | VirtualSize          | The total size of the section when loaded into memory. If this value is greater than SizeOfRawData, the section is zero-padded. This field is valid only for executable images and should be set to zero for object files. |
    | 12     | 4    | VirtualAddress       | For executable images, the address of the first byte of the section relative to the image base when the section is loaded into memory. For object files, this field is the address of the first byte before relocation is applied; for simplicity, compilers should set this to zero. Otherwise, it is an arbitrary value that is subtracted from offsets during relocation. |
    | 16     | 4    | SizeOfRawData        | The size of the section (for object files) or the size of the initialized data on disk (for image files). For executable images, this must be a multiple of FileAlignment from the optional header. If this is less than VirtualSize, the remainder of the section is zero-filled. Because the SizeOfRawData field is rounded but the VirtualSize field is not, it is possible for SizeOfRawData to be greater than VirtualSize as well. When a section contains only uninitialized data, this field should be zero. |
    | 20     | 4    | PointerToRawData     | The file pointer to the first page of the section within the COFF file. For executable images, this must be a multiple of FileAlignment from the optional header. For object files, the value should be aligned on a 4-byte boundary for best performance. When a section contains only uninitialized data, this field should be zero. |
    | 24     | 4    | PointerToRelocations | The file pointer to the beginning of relocation entries for the section. This is set to zero for executable images or if there are no relocations. |
    | 28     | 4    | PointerToLinenumbers | The file pointer to the beginning of line-number entries for the section. This is set to zero if there are no COFF line numbers. This value should be zero for an image because COFF debugging information is deprecated. |
    | 32     | 2    | NumberOfRelocations  | The number of relocation entries for the section. This is set to zero for executable images. |
    | 34     | 2    | NumberOfLinenumbers  | The number of line-number entries for the section. This value should be zero for an image because COFF debugging information is deprecated. |
    | 36     | 4    | Characteristics      | The flags that describe the characteristics of the section. For more information, see [Section Flags](https://docs.microsoft.com/en-us/windows/win32/debug/pe-format#section-flags). |
    

      Characteristics.The table below defines the possible 32-bit mask values for this member:
      Characteristics取值范围如下表:

    | Flag                              | Value      | Description                                                  |
    |                                   | 0x00000000 | Reserved for future use.                                     |
    |                                   | 0x00000001 | Reserved for future use.                                     |
    |                                   | 0x00000002 | Reserved for future use.                                     |
    |                                   | 0x00000004 | Reserved for future use.                                     |
    | IMAGE_SCN_TYPE_NO_PAD             | 0x00000008 | The section should not be padded to the next boundary. This flag is obsolete and is replaced by IMAGE_SCN_ALIGN_1BYTES. This is valid only for object files. |
    |                                   | 0x00000010 | Reserved for future use.                                     |
    | IMAGE_SCN_CNT_CODE                | 0x00000020 | The section contains executable code.                        |
    | IMAGE_SCN_CNT_INITIALIZED_DATA    | 0x00000040 | The section contains initialized data.                       |
    | IMAGE_SCN_CNT_UNINITIALIZED_ DATA | 0x00000080 | The section contains uninitialized data.                     |
    | IMAGE_SCN_LNK_OTHER               | 0x00000100 | Reserved for future use.                                     |
    | IMAGE_SCN_LNK_INFO                | 0x00000200 | The section contains comments or other information. The .drectve section has this type. This is valid for object files only. |
    |                                   | 0x00000400 | Reserved for future use.                                     |
    | IMAGE_SCN_LNK_REMOVE              | 0x00000800 | The section will not become part of the image. This is valid only for object files. |
    | IMAGE_SCN_LNK_COMDAT              | 0x00001000 | The section contains COMDAT data. For more information, see [COMDAT Sections (Object Only)](https://docs.microsoft.com/en-us/windows/win32/debug/pe-format#comdat-sections-object-only). This is valid only for object files. |
    | IMAGE_SCN_GPREL                   | 0x00008000 | The section contains data referenced through the global pointer (GP). |
    | IMAGE_SCN_MEM_PURGEABLE           | 0x00020000 | Reserved for future use.                                     |
    | IMAGE_SCN_MEM_16BIT               | 0x00020000 | Reserved for future use.                                     |
    | IMAGE_SCN_MEM_LOCKED              | 0x00040000 | Reserved for future use.                                     |
    | IMAGE_SCN_MEM_PRELOAD             | 0x00080000 | Reserved for future use.                                     |
    | IMAGE_SCN_ALIGN_1BYTES            | 0x00100000 | Align data on a 1-byte boundary. Valid only for object files. |
    | IMAGE_SCN_ALIGN_2BYTES            | 0x00200000 | Align data on a 2-byte boundary. Valid only for object files. |
    | IMAGE_SCN_ALIGN_4BYTES            | 0x00300000 | Align data on a 4-byte boundary. Valid only for object files. |
    | IMAGE_SCN_ALIGN_8BYTES            | 0x00400000 | Align data on an 8-byte boundary. Valid only for object files. |
    | IMAGE_SCN_ALIGN_16BYTES           | 0x00500000 | Align data on a 16-byte boundary. Valid only for object files. |
    | IMAGE_SCN_ALIGN_32BYTES           | 0x00600000 | Align data on a 32-byte boundary. Valid only for object files. |
    | IMAGE_SCN_ALIGN_64BYTES           | 0x00700000 | Align data on a 64-byte boundary. Valid only for object files. |
    | IMAGE_SCN_ALIGN_128BYTES          | 0x00800000 | Align data on a 128-byte boundary. Valid only for object files. |
    | IMAGE_SCN_ALIGN_256BYTES          | 0x00900000 | Align data on a 256-byte boundary. Valid only for object files. |
    | IMAGE_SCN_ALIGN_512BYTES          | 0x00A00000 | Align data on a 512-byte boundary. Valid only for object files. |
    | IMAGE_SCN_ALIGN_1024BYTES         | 0x00B00000 | Align data on a 1024-byte boundary. Valid only for object files. |
    | IMAGE_SCN_ALIGN_2048BYTES         | 0x00C00000 | Align data on a 2048-byte boundary. Valid only for object files. |
    | IMAGE_SCN_ALIGN_4096BYTES         | 0x00D00000 | Align data on a 4096-byte boundary. Valid only for object files. |
    | IMAGE_SCN_ALIGN_8192BYTES         | 0x00E00000 | Align data on an 8192-byte boundary. Valid only for object files. |
    | IMAGE_SCN_LNK_NRELOC_OVFL         | 0x01000000 | The section contains extended relocations.                   |
    | IMAGE_SCN_MEM_DISCARDABLE         | 0x02000000 | The section can be discarded as needed.                      |
    | IMAGE_SCN_MEM_NOT_CACHED          | 0x04000000 | The section cannot be cached.                                |
    | IMAGE_SCN_MEM_NOT_PAGED           | 0x08000000 | The section is not pageable.                                 |
    | IMAGE_SCN_MEM_SHARED              | 0x10000000 | The section can be shared in memory.                         |
    | IMAGE_SCN_MEM_EXECUTE             | 0x20000000 | The section can be executed as code.                         |
    | IMAGE_SCN_MEM_READ                | 0x40000000 | The section can be read.                                     |
    | IMAGE_SCN_MEM_WRITE               | 0x80000000 | The section can be written to.                               |
    

      根据上述的信息,简要分析Optional Header后第一个40字节内容:



      对照dumpbin输出的信息,可以看到数值上是完全一致的:

    SECTION HEADER #1
       .text name
       B6BA0 virtual size
        1000 virtual address (00401000 to 004B7B9F)
       B6C00 size of raw data
         400 file pointer to raw data (00000400 to 000B6FFF)
           0 file pointer to relocation table
           0 file pointer to line numbers
           0 number of relocations
           0 number of line numbers
    60500060 flags
             Code
             Initialized Data
             RESERVED - UNKNOWN
             RESERVED - UNKNOWN
             Execute Read
    

      A PE loader will place the sections of the executable image at the locations specified by these section descriptors (relative to the base address) and usually the alignment is 0x1000, which matches the size of pages on the x86.
      待续:PE加载器会将可执行映像的节放在这些节描述符指定的位置(相对于基址)。
      常见的节分类如下:
      ◆.text/.code/CODE/TEXT ⏤ Contains executable code (machine instructions)
      ◆.textbss/TEXTBSS ⏤ Present if Incremental Linking is enabled
      ◆.data/.idata/DATA/IDATA ⏤ Contains initialised data
      ◆.bss/BSS ⏤ Contains uninitialised data
      ◆.rsrc ⏤ Contains resource data

      最后一个section table所示如下:

      dumpbin内容:

    SECTION HEADER #10
        /102 name (.debug_ranges)
         3B0 virtual size
       D9000 virtual address (004D9000 to 004D93AF)
         400 size of raw data
       CCE00 file pointer to raw data (000CCE00 to 000CD1FF)
           0 file pointer to relocation table
           0 file pointer to line numbers
           0 number of relocations
           0 number of line numbers
    42100040 flags
             Initialized Data
             RESERVED - UNKNOWN
             Discardable
             Read Only
    













    • 1-2 类的初步—定义一个类并创建对象实例

      1-2-1. 导言—用户管理—用户的分类及介绍

    第2章节 

    • 2-1 类的初步—定义一个类并创建对象实例

      2-1-1. 导言—用户管理—用户的分类及介绍
    • 2-2 类的初步—定义一个类并创建对象实例

      2-2-1. 导言—用户管理—用户的分类及介绍

    第3章节 

    • 3-1 类的初步—定义一个类并创建对象实例

      3-1-1. 导言—用户管理—用户的分类及介绍
    • 3-2 类的初步—定义一个类并创建对象实例

      3-2-1. 导言—用户管理—用户的分类及介绍

    相关文章

      网友评论

          本文标题:基础C++教学⮱⮱002【目标文件简介】2019-11-17

          本文链接:https://www.haomeiwen.com/subject/sekpictx.html