可执行文件详解

目录

 

生成可执行文件

可执行文件的结构

可执行文件的ELF Header

可执行文件的section

可执行文件的segment


生成可执行文件

可执行文件也是ELF文件,这里同样从ELF文件的观点分析可执行文件的结构

使用如下两端代码来模拟多个文件生成一个可执行文件的过程

//add.c
extern int times;

int add(int n1, int n2) {
    times++;
    return n1 + n2;
}
//main.c
#include <stdio.h>

extern int add(int, int);
int times = 0;

int main(void)
{
    int a = 2;
    int b = 3;

    printf("%d, The sum of a and b is %d\n", times, add(a,b));
    
    return 0;
}

使用命令如下,先生成两个可重定位文件,然后对其进行链接,生成可执行文件add

gcc -c add.c -o add.o
gcc -c main.c -o main.o
gcc -o add add.o main.o

注意,假如下面查看可执行文件,发现type是共享库文件类型,可能是因为gcc默认加了--enable-default-pie选项,可以使用-no-pie禁用,如下

gcc -o add add.c main.c -no-pie

可执行文件的结构

可执行文件的ELF Header

使用readelf查看文件

$ readelf -h add 
ELF Header: 
  Magic:   7f 45 4c 46 02 01 01 00 00 00 00 00 00 00 00 00 
  Class:                             ELF64 
  Data:                              2's complement, little endian 
  Version:                           1 (current) 
  OS/ABI:                            UNIX - System V 
  ABI Version:                       0 
  Type:                              EXEC (Executable file) 
  Machine:                           Advanced Micro Devices X86-64 
  Version:                           0x1 
  Entry point address:               0x401050 
  Start of program headers:          64 (bytes into file) 
  Start of section headers:          14736 (bytes into file) 
  Flags:                             0x0 
  Size of this header:               64 (bytes) 
  Size of program headers:           56 (bytes) 
  Number of program headers:         13 
  Size of section headers:           64 (bytes) 
  Number of section headers:         31 
  Section header string table index: 30

字段分析如下

  1. Type: EXEC (Executable file): 该文件是一个可执行文件;
  2. Entry point address: 0x401050: 文件的入口地址为0x401050,该地址是代码段的起始地址;
  3. xxx of program headers: xxx: 该文件中共有13个program header,每个的大小为56字节;
  4. xxx of section headers: xxx: 该文件中共有31个section header,每个的大小为64字节。

这里可以看出,链接之后生成的可执行文件,该文件结构具有了完整的ELF文件结构。

可执行文件的section

从ELF Header中可以看出 add 有31个 section,使用readelf查看section的内容

$ readelf -S add 
There are 31 section headers, starting at offset 0x3990: 
 
Section Headers: 
  [Nr] Name              Type             Address           Offset 
       Size              EntSize          Flags  Link  Info  Align 
  [ 0]                   NULL             0000000000000000  0
  • 1
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值