elf加载程序如何初始化全局变量 [英] How do global variables get initialized by the elf loader

查看:147
本文介绍了elf加载程序如何初始化全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于C中的全局变量,例如

For global variables in C like

int aglobal = 5;

int aglobal = 5;

5何时转移装入程序将其放入aglobal中,以及如何知道将5放入aglobal中。

When does the 5 get transferred into aglobal by the loader and how does it know to put 5 in aglobal.

在函数中带有静态声明的相同情况。像

Same situation with a static declaration in a function. Like

int afunc()
{
static int astatic = 8;
返回静态值;
}

int afunc() { static int astatic = 8; return astatic; }

推荐答案

在数据节中形成一个int大小的空间,在其中编码了值5,并且名为 aglobal的全局非功能符号将添加到指向它的符号表中。对aglobal的引用将转换为重定位,在链接时解析该重定位以指向该数据块,因此在完全链接的图像指令中,指令将直接从保存5值的内存中的那个点加载。

An int-sized space is made in a data section, with the value 5 encoded in it and a global non-function symbol named 'aglobal' is added to the symbol table pointing at it. References to aglobal are turned into relocations that are resolved at link-time to point to that data block, so in a fully-linked image instructions will load directly from that spot in memory that holds the 5 value

例如,(x86)程序集可能类似于:

For example, the (x86) assembly might look something like:

.data
.globl aglobal
aglobal: .long 5

.text
main:
    mov eax, aglobal

在目标文件中,mov指令将变为 mov eax,0 ,重定位 R_386_32 aglobal + 0 ,因为目标文件不确定该数据节在内存中的位置。

In an object file, the mov instruction will turn into mov eax, 0 with a relocation R_386_32 aglobal+0, because the object file doesn't know for sure where the data section will be in memory.

完全链接的图像,可能类似于:

In a fully-linked image, it might be something like:

mov eax, 0x804a010

现在已知data节中4个字节的实际地址,因此可以直接指定

Now the actual address of the 4 bytes in the data section is known, so it's specified directly

这篇关于elf加载程序如何初始化全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆