为什么链接的二进制文件的_size符号不能正常工作? [英] Why doesn't a linked binary file's _size symbol work correctly?

查看:111
本文介绍了为什么链接的二进制文件的_size符号不能正常工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用'ld -r -b binary -o binary.o foo.jpeg'将资源嵌入程序中.很棒.我只是想知道为什么int _binary_size符号永远无法正确读取,负数或太大,而在程序运行之间却保持不变. 我总是必须做_binary_end-_binary_start,它可以完美地工作.似乎没有人可以使用... 像这里 .. ..为什么呢?

I use 'ld -r -b binary -o binary.o foo.jpeg' to embed resources in my program. Works awesomely. I just wonder why the int _binary_size symbol never reads correctly, negative or too large a number, but stays the same between program runs. I always gotta do _binary_end - _binary_start, which works flawlessly. It's seems it works for no one... like here .... why is that?

没有理由不使用end-start,因为它代替了大小符号,但仍然让我感到好奇.

There is no reason not to use end-start as it replaces the size symbol, but it still leaves me curious.

代码示例.

extern const unsigned char _binary_scna4_jpg_start;
extern const unsigned char _binary_scna4_jpg_end;
extern const int _binary_scna4_jpg_size;

int size = &_binary_scna4_jpg_end - &_binary_scna4_jpg_start;
printf("Size is %d vs %d \n", size, _binary_scna4_jpg_size);

此打印:

Size is 1192071 vs -385906356 

第一个数字是二进制文件的正确大小,并且我所有的图像都可以完美读取.

First number is the correct size of the binary and all my images read flawlessly.

良好的nm输出:

0000000000123087 D _binary_scna4_jpg_end
0000000000123087 A _binary_scna4_jpg_size
0000000000000000 D _binary_scna4_jpg_start

推荐答案

出现问题的原因是地址空间布局随机化.这样做的副作用是,将大小符号定义为绝对地址(_binary_scna4_jpg_size不是 一个整数值,它是指针",就像_start和_end一样)也会在加载时重新定位

The problem arises because of Position-Independent Executables (PIE). Earlier executables were loaded at the same memory addresses (which were determined at compile/link time) which led to possible attacks because the attacker knew at which address specific parts of programs were. Therefore Address Space Layout Randomization was implemented. This has the side effect that the size symbols being defined as absolute addresses (the _binary_scna4_jpg_size is not an integer value, it's a "pointer" just like _start and _end) also get relocated when they are loaded.

如果使用选项-no-pie编译代码,则可以禁用位置独立性,并且_binary_scna4_jpg_size将输出正确的值,因为它不会被重定位.由于这些天默认情况下PIE处于打开状态,因此指针的值基本上是垃圾.如果您知道重定位内存的开始,也可以使用它,但是由于您已经拥有_binary_scna4_jpg_start_binary_scna4_jpg_end,因此使用它们是同一回事.

If you compile your code with option -no-pie you can disable position-independence and the _binary_scna4_jpg_size will output the correct value since it will not be relocated. Since PIE is on by default these days the value of the pointer is basically garbage. You could also use it if you knew the beginning of the relocated memory, but since you already have _binary_scna4_jpg_start and _binary_scna4_jpg_end it's the same thing to use them.

这篇关于为什么链接的二进制文件的_size符号不能正常工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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