在macOS上的链接时获取__TEXT节的大小

问题描述 投票:0回答:1

[使用gold和其他链接器,可以使链接器使用链接器脚本将.text节的开始/结尾作为常量写入二进制文件,例如

PROVIDE_HIDDEN(linker_script_start_of_text = ADDR(.text));
PROVIDE_HIDDEN(linker_script_end_of_text = ADDR(.text) + SIZEOF(.text));

ld -Tmy_linker_script.lds ...链接。

我知道可以调用getsectdata或类似方法来获取有关.text节的信息,或者从mach-o标头中对其进行解析,但是有没有办法使链接程序将此数据作为常量插入?

c macos linker darwin
1个回答
0
投票

您可以使用__asm让Darwin链接器以一些技巧插入此数据:

#include <stdio.h>

extern int start_text __asm("section$start$__TEXT$__text");
extern int end_text __asm("section$end$__TEXT$__text");

int main() {
  size_t text_section_size_bytes =
    (intptr_t)&end_text - (intptr_t)&start_text;

  printf("__TEXT.__text section size: 0x%lx\n", text_section_size_bytes);

  return 0;
}

在我的机器上,此打印:

$ clang -o test ./test.c
$ ./test
__TEXT.__text section size: 0x43

objdump的报告相符:

$ objdump -h ./test
./foo2: file format Mach-O 64-bit x86-64

Sections:
Idx Name          Size      Address          Type
  0 __text        00000043 0000000100000f30 TEXT
  [...]

您也可以通过使用语法segment$start$__TEXT / segment$end$__TEXT来获得整个segments(与部分相对)的大小,同样的技巧。

© www.soinside.com 2019 - 2024. All rights reserved.