从C获取* ABS *符号的值 [英] Getting the value of *ABS* symbols from C
问题描述
从C中访问*ABS*
(绝对值,不可重定位)符号的实际值的正确方法是什么?
What is the proper way of accessing the actual value of an *ABS*
(absolute, not-to-be-relocated) symbol from C?
我正在使用ld将数据(... HTML模板)嵌入可执行文件中(...按照
I'm using ld to embed data (... a HTML template) in an executable (... following the method described in https://csl.name/post/embedding-binary-data/). As in:
ld -r -b binary [the_file_to_be_embedded] -o [some_object.o]
然后,我正在使用
const char _some_object_start;
const char _some_object_end;
const int _some_object_size;
实际代码中的
.通过使用&_some_object_start
获得char指针,实际的链接文本可以很好地工作.读取大小总是以有趣的,与平台相关的方式中断:在ARM64上,(long) &_some_object_size
实际上最终成为大小,但是在x64上,编译器试图使其相对于PC,而最终没有得到正确的结果
in the actual code. The actual linked text works nicely by getting char pointers with &_some_object_start
; reading the size keeps breaking in interesting, platform-dependent ways though: on ARM64, (long) &_some_object_size
actually ends up being the size, but on x64 the compiler is trying to make it PC-relative and doesn't end up with the right thing.
作为参考,这是实际符号表的外观:
For reference, this is how the actual symbol table looks like:
SYMBOL TABLE:
00000000 l d .data 00000000 .data
0000000d g .data 00000000 _binary_hello_world_txt_end
0000000d g *ABS* 00000000 _binary_hello_world_txt_size
00000000 g .data 00000000 _binary_hello_world_txt_start
(由objdump -x获取.)
(obtained by objdump -x.)
我假设ld
假定存在某种合理的方式来链接代码以读取它,因此添加了大小数据,因此是问题.
I presume ld
adds size data assuming that there is some reasonable way for code linked with it to read it, therefore the question.
(...更多是从理论上讲的,因为&_obj_end - &obj_start
仍会解析为实际数据长度;不过,我对_obj_size
特别好奇.)
(... which is more on the theoretical side, as &_obj_end - &obj_start
does still resolve to the actual data length; I'm curious specifically about _obj_size
though.)
推荐答案
符号的值是其地址,因此&symbol_name
应该对其进行检索.
The value of a symbol is its address, so &symbol_name
should retrieve it.
example.c
example.c
#include <stdio.h>
extern char abs_sym;
int main() { printf("%p\n", (void*)&abs_sym); }
运行示例:
$ gcc ldabs.c -no-pie -Wl,--defsym=abs_sym=0xab && ./a.out
0xab
这篇关于从C获取* ABS *符号的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!