找回密码
 立即注册
首页 业界区 业界 如何实现在Windows上运行Linux程序,附示例代码 ...

如何实现在Windows上运行Linux程序,附示例代码

田雅宁 2025-5-28 23:48:27
微软在去年发布了Bash On Windows, 这项技术允许在Windows上运行Linux程序, 我相信已经有很多文章解释过Bash On Windows的原理,
而今天的这篇文章将会讲解如何自己实现一个简单的原生Linux程序运行器, 这个运行器在用户层实现, 原理和Bash On Windows不完全一样,比较接近Linux上的Wine.
示例程序完整的代码在github上, 地址是 https://github.com/303248153/HelloElfLoader
初步了解ELF格式

首先让我们先了解什么是原生Linux程序, 以下说明摘自维基百科
  1. In computing, the Executable and Linkable Format (ELF, formerly named Extensible Linking Format), is a common standard file format for executable files, object code, shared libraries, and core dumps. First published in the specification for the application binary interface (ABI) of the Unix operating system version named System V Release 4 (SVR4),[2] and later in the Tool Interface Standard,[1] it was quickly accepted among different vendors of Unix systems. In 1999, it was chosen as the standard binary file format for Unix and Unix-like systems on x86 processors by the 86open project.
  2. By design, ELF is flexible, extensible, and cross-platform, not bound to any given central processing unit (CPU) or instruction set architecture. This has allowed it to be adopted by many different operating systems on many different hardware platforms.
复制代码
Linux的可执行文件格式采用了ELF格式, 而Windows采用了PE格式, 也就是我们经常使用的exe文件的格式.
ELF格式的结构如下

大致上可以分为这些部分

  • ELF头,在文件的最开头,储存了类型和版本等信息
  • 程序头, 供程序运行时解释器(interpreter)使用
  • 节头, 供程序编译时链接器(linker)使用, 运行时不需要读节头
  • 节内容, 不同的节作用都不一样

    • .text 代码节,保存了主要的程序代码
    • .rodata 保存了只读的数据,例如字符串(const char*)
    • .data 保存了可读写的数据,例如全局变量
    • 还有其他各种各样的节

让我们来实际看一下Linux可执行程序的样子
以下的编译环境是Ubuntu 16.04 x64 + gcc 5.4.0, 编译环境不一样可能会得出不同的结果
首先创建hello.c,写入以下的代码
  1. #include <stdio.h>
  2. int max(int x, int y) {
  3.         return x > y ? x : y;
  4. }
  5. int main() {
  6.         printf("max is %d\n", max(123, 321));
  7.         printf("test many arguments %d %d %d %s %s %s %s %s %s\n", 1, 2, 3, "a", "b", "c", "d", "e", "f");
  8.         return 100;
  9. }
复制代码
然后使用gcc编译这份代码
  1. gcc hello.c
复制代码
编译完成后你可以看到hello.c旁边多了一个a.out, 这就是linux的可执行文件了, 现在可以在linux上运行它
  1. ./a.out
复制代码
你可以看到以下输出
  1. max is 321
  2. test many arguments 1 2 3 a b c d e f
复制代码
我们来看看a.out包含了什么,解析ELF文件可以使用readelf命令
  1. readelf -a ./a.out
复制代码
可以看到输出了以下的信息
  1. ELF 头:
  2.   Magic:   7f 45 4c 46 02 01 01 00 00 00 00 00 00 00 00 00
  3.   类别:                              ELF64
  4.   数据:                              2 补码,小端序 (little endian)
  5.   版本:                              1 (current)
  6.   OS/ABI:                            UNIX - System V
  7.   ABI 版本:                          0
  8.   类型:                              EXEC (可执行文件)
  9.   系统架构:                          Advanced Micro Devices X86-64
  10.   版本:                              0x1
  11.   入口点地址:               0x400430
  12.   程序头起点:          64 (bytes into file)
  13.   Start of section headers:          6648 (bytes into file)
  14.   标志:             0x0
  15.   本头的大小:       64 (字节)
  16.   程序头大小:       56 (字节)
  17.   Number of program headers:         9
  18.   节头大小:         64 (字节)
  19.   节头数量:         31
  20.   字符串表索引节头: 28
  21. 节头:
  22.   [号] 名称              类型             地址              偏移量
  23.        大小              全体大小          旗标   链接   信息   对齐
  24.   [ 0]                   NULL             0000000000000000  00000000
  25.        0000000000000000  0000000000000000           0     0     0
  26.   [ 1] .interp           PROGBITS         0000000000400238  00000238
  27.        000000000000001c  0000000000000000   A       0     0     1
  28.   [ 2] .note.ABI-tag     NOTE             0000000000400254  00000254
  29.        0000000000000020  0000000000000000   A       0     0     4
  30.   [ 3] .note.gnu.build-i NOTE             0000000000400274  00000274
  31.        0000000000000024  0000000000000000   A       0     0     4
  32.   [ 4] .gnu.hash         GNU_HASH         0000000000400298  00000298
  33.        000000000000001c  0000000000000000   A       5     0     8
  34.   [ 5] .dynsym           DYNSYM           00000000004002b8  000002b8
  35.        0000000000000060  0000000000000018   A       6     1     8
  36.   [ 6] .dynstr           STRTAB           0000000000400318  00000318
  37.        000000000000003f  0000000000000000   A       0     0     1
  38.   [ 7] .gnu.version      VERSYM           0000000000400358  00000358
  39.        0000000000000008  0000000000000002   A       5     0     2
  40.   [ 8] .gnu.version_r    VERNEED          0000000000400360  00000360
  41.        0000000000000020  0000000000000000   A       6     1     8
  42.   [ 9] .rela.dyn         RELA             0000000000400380  00000380
  43.        0000000000000018  0000000000000018   A       5     0     8
  44.   [10] .rela.plt         RELA             0000000000400398  00000398
  45.        0000000000000030  0000000000000018  AI       5    24     8
  46.   [11] .init             PROGBITS         00000000004003c8  000003c8
  47.        000000000000001a  0000000000000000  AX       0     0     4
  48.   [12] .plt              PROGBITS         00000000004003f0  000003f0
  49.        0000000000000030  0000000000000010  AX       0     0     16
  50.   [13] .plt.got          PROGBITS         0000000000400420  00000420
  51.        0000000000000008  0000000000000000  AX       0     0     8
  52.   [14] .text             PROGBITS         0000000000400430  00000430
  53.        00000000000001f2  0000000000000000  AX       0     0     16
  54.   [15] .fini             PROGBITS         0000000000400624  00000624
  55.        0000000000000009  0000000000000000  AX       0     0     4
  56.   [16] .rodata           PROGBITS         0000000000400630  00000630
  57.        0000000000000050  0000000000000000   A       0     0     8
  58.   [17] .eh_frame_hdr     PROGBITS         0000000000400680  00000680
  59.        000000000000003c  0000000000000000   A       0     0     4
  60.   [18] .eh_frame         PROGBITS         00000000004006c0  000006c0
  61.        0000000000000114  0000000000000000   A       0     0     8
  62.   [19] .init_array       INIT_ARRAY       0000000000600e10  00000e10
  63.        0000000000000008  0000000000000000  WA       0     0     8
  64.   [20] .fini_array       FINI_ARRAY       0000000000600e18  00000e18
  65.        0000000000000008  0000000000000000  WA       0     0     8
  66.   [21] .jcr              PROGBITS         0000000000600e20  00000e20
  67.        0000000000000008  0000000000000000  WA       0     0     8
  68.   [22] .dynamic          DYNAMIC          0000000000600e28  00000e28
  69.        00000000000001d0  0000000000000010  WA       6     0     8
  70.   [23] .got              PROGBITS         0000000000600ff8  00000ff8
  71.        0000000000000008  0000000000000008  WA       0     0     8
  72.   [24] .got.plt          PROGBITS         0000000000601000  00001000
  73.        0000000000000028  0000000000000008  WA       0     0     8
  74.   [25] .data             PROGBITS         0000000000601028  00001028
  75.        0000000000000010  0000000000000000  WA       0     0     8
  76.   [26] .bss              NOBITS           0000000000601038  00001038
  77.        0000000000000008  0000000000000000  WA       0     0     1
  78.   [27] .comment          PROGBITS         0000000000000000  00001038
  79.        0000000000000034  0000000000000001  MS       0     0     1
  80.   [28] .shstrtab         STRTAB           0000000000000000  000018ea
  81.        000000000000010c  0000000000000000           0     0     1
  82.   [29] .symtab           SYMTAB           0000000000000000  00001070
  83.        0000000000000660  0000000000000018          30    47     8
  84.   [30] .strtab           STRTAB           0000000000000000  000016d0
  85.        000000000000021a  0000000000000000           0     0     1
  86. Key to Flags:
  87.   W (write), A (alloc), X (execute), M (merge), S (strings), l (large)
  88.   I (info), L (link order), G (group), T (TLS), E (exclude), x (unknown)
  89.   O (extra OS processing required) o (OS specific), p (processor specific)
  90. There are no section groups in this file.
  91. 程序头:
  92.   Type           Offset             VirtAddr           PhysAddr
  93.                  FileSiz            MemSiz              Flags  Align
  94.   PHDR           0x0000000000000040 0x0000000000400040 0x0000000000400040
  95.                  0x00000000000001f8 0x00000000000001f8  R E    8
  96.   INTERP         0x0000000000000238 0x0000000000400238 0x0000000000400238
  97.                  0x000000000000001c 0x000000000000001c  R      1
  98.       [Requesting program interpreter: /lib64/ld-linux-x86-64.so.2]
  99.   LOAD           0x0000000000000000 0x0000000000400000 0x0000000000400000
  100.                  0x00000000000007d4 0x00000000000007d4  R E    200000
  101.   LOAD           0x0000000000000e10 0x0000000000600e10 0x0000000000600e10
  102.                  0x0000000000000228 0x0000000000000230  RW     200000
  103.   DYNAMIC        0x0000000000000e28 0x0000000000600e28 0x0000000000600e28
  104.                  0x00000000000001d0 0x00000000000001d0  RW     8
  105.   NOTE           0x0000000000000254 0x0000000000400254 0x0000000000400254
  106.                  0x0000000000000044 0x0000000000000044  R      4
  107.   GNU_EH_FRAME   0x0000000000000680 0x0000000000400680 0x0000000000400680
  108.                  0x000000000000003c 0x000000000000003c  R      4
  109.   GNU_STACK      0x0000000000000000 0x0000000000000000 0x0000000000000000
  110.                  0x0000000000000000 0x0000000000000000  RW     10
  111.   GNU_RELRO      0x0000000000000e10 0x0000000000600e10 0x0000000000600e10
  112.                  0x00000000000001f0 0x00000000000001f0  R      1
  113. Section to Segment mapping:
  114.   段节...
  115.    00     
  116.    01     .interp
  117.    02     .interp .note.ABI-tag .note.gnu.build-id .gnu.hash .dynsym .dynstr .gnu.version .gnu.version_r .rela.dyn .rela.plt .init .plt .plt.got .text .fini .rodata .eh_frame_hdr .eh_frame
  118.    03     .init_array .fini_array .jcr .dynamic .got .got.plt .data .bss
  119.    04     .dynamic
  120.    05     .note.ABI-tag .note.gnu.build-id
  121.    06     .eh_frame_hdr
  122.    07     
  123.    08     .init_array .fini_array .jcr .dynamic .got
  124. Dynamic section at offset 0xe28 contains 24 entries:
  125.   标记        类型                         名称/值
  126. 0x0000000000000001 (NEEDED)             共享库:[libc.so.6]
  127. 0x000000000000000c (INIT)               0x4003c8
  128. 0x000000000000000d (FINI)               0x400624
  129. 0x0000000000000019 (INIT_ARRAY)         0x600e10
  130. 0x000000000000001b (INIT_ARRAYSZ)       8 (bytes)
  131. 0x000000000000001a (FINI_ARRAY)         0x600e18
  132. 0x000000000000001c (FINI_ARRAYSZ)       8 (bytes)
  133. 0x000000006ffffef5 (GNU_HASH)           0x400298
  134. 0x0000000000000005 (STRTAB)             0x400318
  135. 0x0000000000000006 (SYMTAB)             0x4002b8
  136. 0x000000000000000a (STRSZ)              63 (bytes)
  137. 0x000000000000000b (SYMENT)             24 (bytes)
  138. 0x0000000000000015 (DEBUG)              0x0
  139. 0x0000000000000003 (PLTGOT)             0x601000
  140. 0x0000000000000002 (PLTRELSZ)           48 (bytes)
  141. 0x0000000000000014 (PLTREL)             RELA
  142. 0x0000000000000017 (JMPREL)             0x400398
  143. 0x0000000000000007 (RELA)               0x400380
  144. 0x0000000000000008 (RELASZ)             24 (bytes)
  145. 0x0000000000000009 (RELAENT)            24 (bytes)
  146. 0x000000006ffffffe (VERNEED)            0x400360
  147. 0x000000006fffffff (VERNEEDNUM)         1
  148. 0x000000006ffffff0 (VERSYM)             0x400358
  149. 0x0000000000000000 (NULL)               0x0
  150. 重定位节 '.rela.dyn' 位于偏移量 0x380 含有 1 个条目:
  151.   偏移量          信息           类型           符号值        符号名称 + 加数
  152. 000000600ff8  000300000006 R_X86_64_GLOB_DAT 0000000000000000 __gmon_start__ + 0
  153. 重定位节 '.rela.plt' 位于偏移量 0x398 含有 2 个条目:
  154.   偏移量          信息           类型           符号值        符号名称 + 加数
  155. 000000601018  000100000007 R_X86_64_JUMP_SLO 0000000000000000 printf@GLIBC_2.2.5 + 0
  156. 000000601020  000200000007 R_X86_64_JUMP_SLO 0000000000000000 __libc_start_main@GLIBC_2.2.5 + 0
  157. The decoding of unwind sections for machine type Advanced Micro Devices X86-64 is not currently supported.
  158. Symbol table '.dynsym' contains 4 entries:
  159.    Num:    Value          Size Type    Bind   Vis      Ndx Name
  160.      0: 0000000000000000     0 NOTYPE  LOCAL  DEFAULT  UND
  161.      1: 0000000000000000     0 FUNC    GLOBAL DEFAULT  UND printf@GLIBC_2.2.5 (2)
  162.      2: 0000000000000000     0 FUNC    GLOBAL DEFAULT  UND __libc_start_main@GLIBC_2.2.5 (2)
  163.      3: 0000000000000000     0 NOTYPE  WEAK   DEFAULT  UND __gmon_start__
  164. Symbol table '.symtab' contains 68 entries:
  165.    Num:    Value          Size Type    Bind   Vis      Ndx Name
  166.      0: 0000000000000000     0 NOTYPE  LOCAL  DEFAULT  UND
  167.      1: 0000000000400238     0 SECTION LOCAL  DEFAULT    1
  168.      2: 0000000000400254     0 SECTION LOCAL  DEFAULT    2
  169.      3: 0000000000400274     0 SECTION LOCAL  DEFAULT    3
  170.      4: 0000000000400298     0 SECTION LOCAL  DEFAULT    4
  171.      5: 00000000004002b8     0 SECTION LOCAL  DEFAULT    5
  172.      6: 0000000000400318     0 SECTION LOCAL  DEFAULT    6
  173.      7: 0000000000400358     0 SECTION LOCAL  DEFAULT    7
  174.      8: 0000000000400360     0 SECTION LOCAL  DEFAULT    8
  175.      9: 0000000000400380     0 SECTION LOCAL  DEFAULT    9
  176.     10: 0000000000400398     0 SECTION LOCAL  DEFAULT   10
  177.     11: 00000000004003c8     0 SECTION LOCAL  DEFAULT   11
  178.     12: 00000000004003f0     0 SECTION LOCAL  DEFAULT   12
  179.     13: 0000000000400420     0 SECTION LOCAL  DEFAULT   13
  180.     14: 0000000000400430     0 SECTION LOCAL  DEFAULT   14
  181.     15: 0000000000400624     0 SECTION LOCAL  DEFAULT   15
  182.     16: 0000000000400630     0 SECTION LOCAL  DEFAULT   16
  183.     17: 0000000000400680     0 SECTION LOCAL  DEFAULT   17
  184.     18: 00000000004006c0     0 SECTION LOCAL  DEFAULT   18
  185.     19: 0000000000600e10     0 SECTION LOCAL  DEFAULT   19
  186.     20: 0000000000600e18     0 SECTION LOCAL  DEFAULT   20
  187.     21: 0000000000600e20     0 SECTION LOCAL  DEFAULT   21
  188.     22: 0000000000600e28     0 SECTION LOCAL  DEFAULT   22
  189.     23: 0000000000600ff8     0 SECTION LOCAL  DEFAULT   23
  190.     24: 0000000000601000     0 SECTION LOCAL  DEFAULT   24
  191.     25: 0000000000601028     0 SECTION LOCAL  DEFAULT   25
  192.     26: 0000000000601038     0 SECTION LOCAL  DEFAULT   26
  193.     27: 0000000000000000     0 SECTION LOCAL  DEFAULT   27
  194.     28: 0000000000000000     0 FILE    LOCAL  DEFAULT  ABS crtstuff.c
  195.     29: 0000000000600e20     0 OBJECT  LOCAL  DEFAULT   21 __JCR_LIST__
  196.     30: 0000000000400460     0 FUNC    LOCAL  DEFAULT   14 deregister_tm_clones
  197.     31: 00000000004004a0     0 FUNC    LOCAL  DEFAULT   14 register_tm_clones
  198.     32: 00000000004004e0     0 FUNC    LOCAL  DEFAULT   14 __do_global_dtors_aux
  199.     33: 0000000000601038     1 OBJECT  LOCAL  DEFAULT   26 completed.7585
  200.     34: 0000000000600e18     0 OBJECT  LOCAL  DEFAULT   20 __do_global_dtors_aux_fin
  201.     35: 0000000000400500     0 FUNC    LOCAL  DEFAULT   14 frame_dummy
  202.     36: 0000000000600e10     0 OBJECT  LOCAL  DEFAULT   19 __frame_dummy_init_array_
  203.     37: 0000000000000000     0 FILE    LOCAL  DEFAULT  ABS hello.c
  204.     38: 0000000000000000     0 FILE    LOCAL  DEFAULT  ABS crtstuff.c
  205.     39: 00000000004007d0     0 OBJECT  LOCAL  DEFAULT   18 __FRAME_END__
  206.     40: 0000000000600e20     0 OBJECT  LOCAL  DEFAULT   21 __JCR_END__
  207.     41: 0000000000000000     0 FILE    LOCAL  DEFAULT  ABS
  208.     42: 0000000000600e18     0 NOTYPE  LOCAL  DEFAULT   19 __init_array_end
  209.     43: 0000000000600e28     0 OBJECT  LOCAL  DEFAULT   22 _DYNAMIC
  210.     44: 0000000000600e10     0 NOTYPE  LOCAL  DEFAULT   19 __init_array_start
  211.     45: 0000000000400680     0 NOTYPE  LOCAL  DEFAULT   17 __GNU_EH_FRAME_HDR
  212.     46: 0000000000601000     0 OBJECT  LOCAL  DEFAULT   24 _GLOBAL_OFFSET_TABLE_
  213.     47: 0000000000400620     2 FUNC    GLOBAL DEFAULT   14 __libc_csu_fini
  214.     48: 0000000000000000     0 NOTYPE  WEAK   DEFAULT  UND _ITM_deregisterTMCloneTab
  215.     49: 0000000000601028     0 NOTYPE  WEAK   DEFAULT   25 data_start
  216.     50: 0000000000601038     0 NOTYPE  GLOBAL DEFAULT   25 _edata
  217.     51: 0000000000400624     0 FUNC    GLOBAL DEFAULT   15 _fini
  218.     52: 0000000000000000     0 FUNC    GLOBAL DEFAULT  UND printf@@GLIBC_2.2.5
  219.     53: 0000000000400526    22 FUNC    GLOBAL DEFAULT   14 max
  220.     54: 0000000000000000     0 FUNC    GLOBAL DEFAULT  UND __libc_start_main@@GLIBC_
  221.     55: 0000000000601028     0 NOTYPE  GLOBAL DEFAULT   25 __data_start
  222.     56: 0000000000000000     0 NOTYPE  WEAK   DEFAULT  UND __gmon_start__
  223.     57: 0000000000601030     0 OBJECT  GLOBAL HIDDEN    25 __dso_handle
  224.     58: 0000000000400630     4 OBJECT  GLOBAL DEFAULT   16 _IO_stdin_used
  225.     59: 00000000004005b0   101 FUNC    GLOBAL DEFAULT   14 __libc_csu_init
  226.     60: 0000000000601040     0 NOTYPE  GLOBAL DEFAULT   26 _end
  227.     61: 0000000000400430    42 FUNC    GLOBAL DEFAULT   14 _start
  228.     62: 0000000000601038     0 NOTYPE  GLOBAL DEFAULT   26 __bss_start
  229.     63: 000000000040053c   109 FUNC    GLOBAL DEFAULT   14 main
  230.     64: 0000000000000000     0 NOTYPE  WEAK   DEFAULT  UND _Jv_RegisterClasses
  231.     65: 0000000000601038     0 OBJECT  GLOBAL HIDDEN    25 __TMC_END__
  232.     66: 0000000000000000     0 NOTYPE  WEAK   DEFAULT  UND _ITM_registerTMCloneTable
  233.     67: 00000000004003c8     0 FUNC    GLOBAL DEFAULT   11 _init
  234. Version symbols section '.gnu.version' contains 4 entries:
  235. 地址: 0000000000400358  Offset: 0x000358  Link: 5 (.dynsym)
  236.   000:   0 (*本地*)       2 (GLIBC_2.2.5)   2 (GLIBC_2.2.5)   0 (*本地*)   
  237. Version needs section '.gnu.version_r' contains 1 entries:
  238. 地址:0x0000000000400360  Offset: 0x000360  Link: 6 (.dynstr)
  239.   000000: 版本: 1  文件:libc.so.6  计数:1
  240.   0x0010:名称:GLIBC_2.2.5  标志:无  版本:2
  241. Displaying notes found at file offset 0x00000254 with length 0x00000020:
  242.   Owner                 Data size        Description
  243.   GNU                  0x00000010        NT_GNU_ABI_TAG (ABI version tag)
  244.     OS: Linux, ABI: 2.6.32
  245. Displaying notes found at file offset 0x00000274 with length 0x00000024:
  246.   Owner                 Data size        Description
  247.   GNU                  0x00000014        NT_GNU_BUILD_ID (unique build ID bitstring)
  248.     Build ID: debd3d7912be860a432b5c685a6cff7fd9418528
复制代码
从上面的信息中我们可以知道这个文件的类型是ELF64, 也就是64位的可执行程序, 并且有9个程序头和31个节头, 各个节的作用大家可以在网上找到资料, 这篇文章中只涉及到以下的节

  • .init 程序初始化的代码
  • .rela.dyn 需要重定位的变量列表
  • .rela.plt 需要重定位的函数列表
  • .plt 调用动态链接函数的代码
  • .text 保存了主要的程序代码
  • .init 保存了程序的初始化代码, 用于初始化全局变量等
  • .fini 保存了程序的终止代码, 用于析构全局变量等
  • .rodata 保存了只读的数据,例如字符串(const char*)
  • .data 保存了可读写的数据,例如全局变量
  • .dynsym 动态链接的符号表
  • .dynstr 动态链接的符号名称字符串
  • .dynamic 动态链接所需要的信息,供程序运行时使用(不需要访问节头)
什么是动态链接

上面的程序中调用了printf函数, 然而这个函数的实现并不在./a.out中, 那么printf函数在哪里, 又是怎么被调用的?
printf函数的实现在glibc库中, 也就是/lib/x86_64-linux-gnu/libc.so.6中, 在执行./a.out的时候会在glibc库中找到这个函数并进行调用, 我们来看看这段代码
执行以下命令反编译./a.out
  1. objdump -c -S ./a.out
复制代码
我们可以看到以下的代码
  1. 00000000004003f0 <printf@plt-0x10>:
  2.   4003f0:        ff 35 12 0c 20 00            pushq  0x200c12(%rip)        # 601008 <_GLOBAL_OFFSET_TABLE_+0x8>
  3.   4003f6:        ff 25 14 0c 20 00            jmpq   *0x200c14(%rip)        # 601010 <_GLOBAL_OFFSET_TABLE_+0x10>
  4.   4003fc:        0f 1f 40 00                  nopl   0x0(%rax)
  5. 0000000000400400 <printf@plt>:
  6.   400400:        ff 25 12 0c 20 00            jmpq   *0x200c12(%rip)        # 601018 <_GLOBAL_OFFSET_TABLE_+0x18>
  7.   400406:        68 00 00 00 00               pushq  $0x0
  8.   40040b:        e9 e0 ff ff ff               jmpq   4003f0 <_init+0x28>
  9. 000000000040053c <main>:
  10.   40053c:        55                           push   %rbp
  11.   40053d:        48 89 e5                     mov    %rsp,%rbp
  12.   400540:        be 41 01 00 00               mov    $0x141,%esi
  13.   400545:        bf 7b 00 00 00               mov    $0x7b,%edi
  14.   40054a:        e8 d7 ff ff ff               callq  400526 <max>
  15.   40054f:        89 c6                        mov    %eax,%esi
  16.   400551:        bf 38 06 40 00               mov    $0x400638,%edi
  17.   400556:        b8 00 00 00 00               mov    $0x0,%eax
  18.   40055b:        e8 a0 fe ff ff               callq  400400 <printf@plt>
复制代码
在这一段代码中,我们可以看到调用printf会首先调用0x400400的printf@plt
printf@plt会负责在运行时找到实际的printf函数并跳转到该函数
在这里实际的printf函数会保存在0x400406 + 0x200c12 = 0x601018中
需要注意的是0x601018一开始并不会指向实际的printf函数,而是会指向0x400406, 为什么会这样? 因为Linux的可执行程序为了考虑性能,不会在一开始就解决所有动态连接的函数,而是选择了延迟解决.
在上面第一次jmpq   *0x200c12(%rip)会跳转到下一条指令0x400406, 又会继续跳转到0x4003f0, 再跳转到0x601010指向的地址, 0x601010指向的地址就是延迟解决的实现, 第一次延迟解决成功后, 0x601018就会指向实际的printf, 以后调用就会直接跳转到实际的printf上.
程序入口点

Linux程序运行首先会从_start函数开始, 上面readelf中的入口点地址0x400430就是_start函数的地址,
  1. 0000000000400430 <_start>:
  2.   400430:        31 ed                        xor    %ebp,%ebp
  3.   400432:        49 89 d1                     mov    %rdx,%r9
  4.   400435:        5e                           pop    %rsi
  5.   400436:        48 89 e2                     mov    %rsp,%rdx
  6.   400439:        48 83 e4 f0                  and    $0xfffffffffffffff0,%rsp
  7.   40043d:        50                           push   %rax
  8.   40043e:        54                           push   %rsp
  9.   40043f:        49 c7 c0 20 06 40 00         mov    $0x400620,%r8
  10.   400446:        48 c7 c1 b0 05 40 00         mov    $0x4005b0,%rcx
  11.   40044d:        48 c7 c7 3c 05 40 00         mov    $0x40053c,%rdi
  12.   400454:        e8 b7 ff ff ff               callq  400410 <__libc_start_main@plt>
  13.   400459:        f4                           hlt   
  14.   40045a:        66 0f 1f 44 00 00            nopw   0x0(%rax,%rax,1)
复制代码
接下来_start函数会调用__libc_start_main函数, __libc_start_main是libc库中定义的初始化函数, 负责初始化全局变量和调用main函数等工作.
__libc_start_main函数还负责设置返回值和退出进程, 可以看到上面调用__libc_start_main后的指令是hlt, 这个指令永远不会被执行.
实现Linux程序运行器

在拥有以上的知识后我们可以先构想以下的运行器需要做什么.
因为x64的Windows和Linux程序使用的cpu指令集都是一样的,我们可以直接执行汇编而不需要一个指令模拟器,
而且这次我打算在用户层实现, 所以不能像Bash On Windows一样模拟syscall, 这个运行器会像下图一样模拟libc库的函数
2.jpeg

这样运行器需要做的事情有:

  • 解析ELF文件
  • 加载程序代码到指定的内存地址
  • 加载数据到指定的内存地址
  • 提供动态链接的函数实现
  • 执行加载的程序代码
这些工作会在以下的示例程序中一一实现, 完整的源代码可以看文章顶部的链接
首先我们需要把ELF文件格式对应的代码从binutils中复制过来, 它包含了ELF头, 程序头和相关的数据结构, 里面用unsigned char[]是为了防止alignment, 这样结构体可以直接从文件内容中转换过来
ELFDefine.h:
  1. #pragma once
  2. namespace HelloElfLoader {
  3.         // 以下内容复制自
  4.         // https://github.com/aeste/binutils/blob/develop/elfcpp/elfcpp.h
  5.         // https://github.com/aeste/binutils/blob/develop/include/elf/external.h
  6.         // e_ident中各项的偏移值
  7.         const int EI_MAG0 = 0;
  8.         const int EI_MAG1 = 1;
  9.         const int EI_MAG2 = 2;
  10.         const int EI_MAG3 = 3;
  11.         const int EI_CLASS = 4;
  12.         const int EI_DATA = 5;
  13.         const int EI_VERSION = 6;
  14.         const int EI_OSABI = 7;
  15.         const int EI_ABIVERSION = 8;
  16.         const int EI_PAD = 9;
  17.         const int EI_NIDENT = 16;
  18.         // ELF文件类型
  19.         enum {
  20.                 ELFCLASSNONE = 0,
  21.                 ELFCLASS32 = 1,
  22.                 ELFCLASS64 = 2
  23.         };
  24.         // ByteOrder
  25.         enum {
  26.                 ELFDATANONE = 0,
  27.                 ELFDATA2LSB = 1,
  28.                 ELFDATA2MSB = 2
  29.         };
  30.         // 程序头类型
  31.         enum PT
  32.         {
  33.                 PT_NULL = 0,
  34.                 PT_LOAD = 1,
  35.                 PT_DYNAMIC = 2,
  36.                 PT_INTERP = 3,
  37.                 PT_NOTE = 4,
  38.                 PT_SHLIB = 5,
  39.                 PT_PHDR = 6,
  40.                 PT_TLS = 7,
  41.                 PT_LOOS = 0x60000000,
  42.                 PT_HIOS = 0x6fffffff,
  43.                 PT_LOPROC = 0x70000000,
  44.                 PT_HIPROC = 0x7fffffff,
  45.                 // The remaining values are not in the standard.
  46.                 // Frame unwind information.
  47.                 PT_GNU_EH_FRAME = 0x6474e550,
  48.                 PT_SUNW_EH_FRAME = 0x6474e550,
  49.                 // Stack flags.
  50.                 PT_GNU_STACK = 0x6474e551,
  51.                 // Read only after relocation.
  52.                 PT_GNU_RELRO = 0x6474e552,
  53.                 // Platform architecture compatibility information
  54.                 PT_ARM_ARCHEXT = 0x70000000,
  55.                 // Exception unwind tables
  56.                 PT_ARM_EXIDX = 0x70000001
  57.         };
  58.         // 动态节类型
  59.         enum DT
  60.         {
  61.                 DT_NULL = 0,
  62.                 DT_NEEDED = 1,
  63.                 DT_PLTRELSZ = 2,
  64.                 DT_PLTGOT = 3,
  65.                 DT_HASH = 4,
  66.                 DT_STRTAB = 5,
  67.                 DT_SYMTAB = 6,
  68.                 DT_RELA = 7,
  69.                 DT_RELASZ = 8,
  70.                 DT_RELAENT = 9,
  71.                 DT_STRSZ = 10,
  72.                 DT_SYMENT = 11,
  73.                 DT_INIT = 12,
  74.                 DT_FINI = 13,
  75.                 DT_SONAME = 14,
  76.                 DT_RPATH = 15,
  77.                 DT_SYMBOLIC = 16,
  78.                 DT_REL = 17,
  79.                 DT_RELSZ = 18,
  80.                 DT_RELENT = 19,
  81.                 DT_PLTREL = 20,
  82.                 DT_DEBUG = 21,
  83.                 DT_TEXTREL = 22,
  84.                 DT_JMPREL = 23,
  85.                 DT_BIND_NOW = 24,
  86.                 DT_INIT_ARRAY = 25,
  87.                 DT_FINI_ARRAY = 26,
  88.                 DT_INIT_ARRAYSZ = 27,
  89.                 DT_FINI_ARRAYSZ = 28,
  90.                 DT_RUNPATH = 29,
  91.                 DT_FLAGS = 30,
  92.                 // This is used to mark a range of dynamic tags.  It is not really
  93.                 // a tag value.
  94.                 DT_ENCODING = 32,
  95.                 DT_PREINIT_ARRAY = 32,
  96.                 DT_PREINIT_ARRAYSZ = 33,
  97.                 DT_LOOS = 0x6000000d,
  98.                 DT_HIOS = 0x6ffff000,
  99.                 DT_LOPROC = 0x70000000,
  100.                 DT_HIPROC = 0x7fffffff,
  101.                 // The remaining values are extensions used by GNU or Solaris.
  102.                 DT_VALRNGLO = 0x6ffffd00,
  103.                 DT_GNU_PRELINKED = 0x6ffffdf5,
  104.                 DT_GNU_CONFLICTSZ = 0x6ffffdf6,
  105.                 DT_GNU_LIBLISTSZ = 0x6ffffdf7,
  106.                 DT_CHECKSUM = 0x6ffffdf8,
  107.                 DT_PLTPADSZ = 0x6ffffdf9,
  108.                 DT_MOVEENT = 0x6ffffdfa,
  109.                 DT_MOVESZ = 0x6ffffdfb,
  110.                 DT_FEATURE = 0x6ffffdfc,
  111.                 DT_POSFLAG_1 = 0x6ffffdfd,
  112.                 DT_SYMINSZ = 0x6ffffdfe,
  113.                 DT_SYMINENT = 0x6ffffdff,
  114.                 DT_VALRNGHI = 0x6ffffdff,
  115.                 DT_ADDRRNGLO = 0x6ffffe00,
  116.                 DT_GNU_HASH = 0x6ffffef5,
  117.                 DT_TLSDESC_PLT = 0x6ffffef6,
  118.                 DT_TLSDESC_GOT = 0x6ffffef7,
  119.                 DT_GNU_CONFLICT = 0x6ffffef8,
  120.                 DT_GNU_LIBLIST = 0x6ffffef9,
  121.                 DT_CONFIG = 0x6ffffefa,
  122.                 DT_DEPAUDIT = 0x6ffffefb,
  123.                 DT_AUDIT = 0x6ffffefc,
  124.                 DT_PLTPAD = 0x6ffffefd,
  125.                 DT_MOVETAB = 0x6ffffefe,
  126.                 DT_SYMINFO = 0x6ffffeff,
  127.                 DT_ADDRRNGHI = 0x6ffffeff,
  128.                 DT_RELACOUNT = 0x6ffffff9,
  129.                 DT_RELCOUNT = 0x6ffffffa,
  130.                 DT_FLAGS_1 = 0x6ffffffb,
  131.                 DT_VERDEF = 0x6ffffffc,
  132.                 DT_VERDEFNUM = 0x6ffffffd,
  133.                 DT_VERNEED = 0x6ffffffe,
  134.                 DT_VERNEEDNUM = 0x6fffffff,
  135.                 DT_VERSYM = 0x6ffffff0,
  136.                 // Specify the value of _GLOBAL_OFFSET_TABLE_.
  137.                 DT_PPC_GOT = 0x70000000,
  138.                 // Specify the start of the .glink section.
  139.                 DT_PPC64_GLINK = 0x70000000,
  140.                 // Specify the start and size of the .opd section.
  141.                 DT_PPC64_OPD = 0x70000001,
  142.                 DT_PPC64_OPDSZ = 0x70000002,
  143.                 // The index of an STT_SPARC_REGISTER symbol within the DT_SYMTAB
  144.                 // symbol table.  One dynamic entry exists for every STT_SPARC_REGISTER
  145.                 // symbol in the symbol table.
  146.                 DT_SPARC_REGISTER = 0x70000001,
  147.                 DT_AUXILIARY = 0x7ffffffd,
  148.                 DT_USED = 0x7ffffffe,
  149.                 DT_FILTER = 0x7fffffff
  150.         };;
  151.         // ELF头的定义
  152.         typedef struct {
  153.                 unsigned char        e_ident[16];                /* ELF "magic number" */
  154.                 unsigned char        e_type[2];                /* Identifies object file type */
  155.                 unsigned char        e_machine[2];                /* Specifies required architecture */
  156.                 unsigned char        e_version[4];                /* Identifies object file version */
  157.                 unsigned char        e_entry[8];                /* Entry point virtual address */
  158.                 unsigned char        e_phoff[8];                /* Program header table file offset */
  159.                 unsigned char        e_shoff[8];                /* Section header table file offset */
  160.                 unsigned char        e_flags[4];                /* Processor-specific flags */
  161.                 unsigned char        e_ehsize[2];                /* ELF header size in bytes */
  162.                 unsigned char        e_phentsize[2];                /* Program header table entry size */
  163.                 unsigned char        e_phnum[2];                /* Program header table entry count */
  164.                 unsigned char        e_shentsize[2];                /* Section header table entry size */
  165.                 unsigned char        e_shnum[2];                /* Section header table entry count */
  166.                 unsigned char        e_shstrndx[2];                /* Section header string table index */
  167.         } Elf64_External_Ehdr;
  168.         // 程序头的定义
  169.         typedef struct {
  170.                 unsigned char        p_type[4];                /* Identifies program segment type */
  171.                 unsigned char        p_flags[4];                /* Segment flags */
  172.                 unsigned char        p_offset[8];                /* Segment file offset */
  173.                 unsigned char        p_vaddr[8];                /* Segment virtual address */
  174.                 unsigned char        p_paddr[8];                /* Segment physical address */
  175.                 unsigned char        p_filesz[8];                /* Segment size in file */
  176.                 unsigned char        p_memsz[8];                /* Segment size in memory */
  177.                 unsigned char        p_align[8];                /* Segment alignment, file & memory */
  178.         } Elf64_External_Phdr;
  179.         // DYNAMIC类型的程序头的内容定义
  180.         typedef struct {
  181.                 unsigned char        d_tag[8];                /* entry tag value */
  182.                 union {
  183.                         unsigned char        d_val[8];
  184.                         unsigned char        d_ptr[8];
  185.                 } d_un;
  186.         } Elf64_External_Dyn;
  187.         // 动态链接的重定位记录,部分系统会用Elf64_External_Rel
  188.         typedef struct {
  189.                 unsigned char r_offset[8];        /* Location at which to apply the action */
  190.                 unsigned char        r_info[8];        /* index and type of relocation */
  191.                 unsigned char        r_addend[8];        /* Constant addend used to compute value */
  192.         } Elf64_External_Rela;
  193.         // 动态链接的符号信息
  194.         typedef struct {
  195.                 unsigned char        st_name[4];                /* Symbol name, index in string tbl */
  196.                 unsigned char        st_info[1];                /* Type and binding attributes */
  197.                 unsigned char        st_other[1];                /* No defined meaning, 0 */
  198.                 unsigned char        st_shndx[2];                /* Associated section index */
  199.                 unsigned char        st_value[8];                /* Value of the symbol */
  200.                 unsigned char        st_size[8];                /* Associated symbol size */
  201.         } Elf64_External_Sym;
  202. }
复制代码
接下来我们定义一个读取和执行ELF文件的类, 这个类会在初始化时把文件加载到fileStream_, execute函数会负责执行
HelloElfLoader.h:
  1. #pragma once
  2. #include <string>
  3. #include <fstream>
  4. namespace HelloElfLoader {
  5.         class Loader {
  6.                 std::ifstream fileStream_;
  7.         public:
  8.                 Loader(const std::string& path);
  9.                 Loader(std::ifstream&& fileStream);
  10.                 void execute();
  11.         };
  12. }
复制代码
构造函数如下, 也就是标准的c++打开文件的代码
HelloElfLoader.cpp:
  1. Loader::Loader(const std::string& path) :
  2.     Loader(std::ifstream(path, std::ios::in | std::ios::binary)) {}
  3. Loader::Loader(std::ifstream&& fileStream) :
  4.     fileStream_(std::move(fileStream)) {
  5.     if (!fileStream_) {
  6.         throw std::runtime_error("open file failed");
  7.     }
  8. }
复制代码
接下来将实现上面所说的步骤, 首先是解析ELF文件
[code]void Loader::execute() {    std::cout
您需要登录后才可以回帖 登录 | 立即注册