I am trying to figure out how to access the build-id generated by the linker at runtime.
From this page, https://linux.die.net/man/1/ld
When I build a test program like:
% gcc test.c -o test -Wl,--build-id=sha1
I can see that the build ID is present in the binary:
% 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
I would like to print this at run-time.
EDIT: Assume you can't access the elf file from which the running process was loaded (permissions, embedded/no filesystem, etc).
EDIT: the accepted answer works, but the linker does not necessarily have to place the variable at the end of the section. If there were a way to get a pointer to the start of the section, that would be more reliable.
Figured it out. Here is a working example,
#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;
}
When I run this, I get output that matches 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 <
One possibility is to use linker scripts to get the address of the .note.gnu.build-id
section:
#include <stdio.h>
// These will be set by the linker script
extern char build_id_start;
extern char build_id_end;
int main(int argc, char **argv) {
const char *s;
s = &build_id_start;
// skip over header (16 bytes)
s += 16;
printf(" > Build ID: ");
for (; s < &build_id_end; s++) {
printf("%02hhx", *s);
}
printf(" <\n");
return 0;
}
In the linker script, the symbols build_id_start
and build_id_end
are defined:
build_id_start = ADDR(.note.gnu.build-id);
build_id_end = ADDR(.note.gnu.build-id) + SIZEOF(.note.gnu.build-id);
The code then can be compiled and run:
gcc build-id.c linker-script.ld -o test && readelf -n test | grep NT_GNU_BUILD_ID -A1 && ./test
GNU 0x00000014 NT_GNU_BUILD_ID (unique build ID bitstring)
Build ID: 7e87ff227443c8f2d5c8e2340638a2ec77d008a1
> Build ID: 7e87ff227443c8f2d5c8e2340638a2ec77d008a1 <
User contributions licensed under CC BY-SA 3.0