c - 在运行时访问 build-id

标签 c gcc linker elf linker-scripts

我正在尝试弄清楚如何访问链接器在运行时生成的构建 ID。

从此页面,https://linux.die.net/man/1/ld

当我构建一个测试程序时:

% gcc test.c -o test -Wl,--build-id=sha1

我可以看到构建 ID 存在于二进制文件中:

% readelf -n test

Displaying notes found in: .note.gnu.build-id
  Owner                 Data size   Description
  GNU                  0x00000014   NT_GNU_BUILD_ID (unique build ID bitstring)
    Build ID: 85aa97bd52ddc4dc2a704949c2545a3a9c69c6db

我想在运行时打印这个。

编辑:假设您无法访问加载正在运行的进程的 elf 文件(权限、嵌入式/无文件系统等)。

编辑:已接受的答案有效,但链接器不一定必须将变量放在该部分的末尾。如果有一种方法可以获得指向该部分开头的指针,那会更可靠。

最佳答案

想通了。这是一个工作示例,

#include <stdio.h>

//
// variable must have an initializer
//  https://gcc.gnu.org/onlinedocs/gcc-3.3.1/gcc/Variable-Attributes.html
//
// the linker places this immediately after the section data
// 
char build_id __attribute__((section(".note.gnu.build-id"))) = '!';

int main(int argc, char ** argv)
{
  const char * s;

  s = &build_id;

  // section data is 20 bytes in size
  s -= 20;

  // sha1 data continues for 20 bytes
  printf("  > Build ID: ");
  int x;
  for(x = 0; x < 20; x++) {
    printf("%02hhx", s[x]);
  }

  printf(" <\n");

  return 0;
}

当我运行它时,我得到与 readelf 匹配的输出,

0 % gcc -g main.c -o test -Wl,--build-id=sha1 && readelf -n test | tail -n 5 && ./test
Displaying notes found in: .note.gnu.build-id
  Owner                 Data size       Description
  GNU                  0x00000014       NT_GNU_BUILD_ID (unique build ID bitstring)
    Build ID: c5eca2cb08f4f5a31bb695955c7ebd2722ca10e9
  > Build ID: c5eca2cb08f4f5a31bb695955c7ebd2722ca10e9 <

关于c - 在运行时访问 build-id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55641889/

相关文章:

c - sizeof(void) 在 C 中等于 1?

c - c中的windows异步串口通信

c++ - GCC 函数的 Visual C++ 版本

gcc - gcc如何找到as,ld和其他binutils可执行文件?

c - 为什么仅在将变量传递给 '-lm' 函数时才显式使用 'math.h'?

c++ - !编译器只留下一个 stub ! ,C++, 在.o文件中找到这些 "stubs"

c - 查明二进制文件是否已使用堆栈粉碎保护进行编译

c - 在 EOWNERDEAD 状态互斥锁上的 Trylock

assembly - 谁负责符号引用链接器或加载器

c++ - 同一解决方案中不同项目之间的引用(Visual Studio 2012)