Skip to content

Instantly share code, notes, and snippets.

@omajid
Created June 1, 2016 21:02
Show Gist options
  • Save omajid/788c804e844aa9d8e6a11b11e6c0aa56 to your computer and use it in GitHub Desktop.
Save omajid/788c804e844aa9d8e6a11b11e6c0aa56 to your computer and use it in GitHub Desktop.
Author: Mark Wielaard <mjw@redhat.com>
/* Requires elfutils-devel >= 0.159
gcc -g -O2 -Wall -lelf -ldw -o getbuildid getbuildid.c */
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <libelf.h>
#include <elfutils/libdwelf.h>
int
main (int argc, char **argv)
{
int c, rc = 0;
elf_version (EV_CURRENT);
for (c = 1; c < argc; c++)
{
int fd = open (argv[c], O_RDONLY);
if (fd >= 0)
{
Elf *elf = elf_begin (fd, ELF_C_READ, NULL);
if (elf != NULL)
{
if (elf_kind(elf) == ELF_K_ELF)
{
const void *build_id;
ssize_t len = dwelf_elf_gnu_build_id (elf, &build_id);
if (len < 0)
{
fprintf (stderr, "error getting buildid for '%s': %s\n",
argv[c], elf_errmsg (-1));
rc = 1;
}
else if (len == 0)
{
fprintf (stderr, "'%s' has no build-id\n", argv[c]);
rc = 1;
}
else
{
const unsigned char *p = build_id;
const unsigned char *end = p + len;
printf ("%s: ", argv[c]);
while (p < end)
printf ("%02x", (unsigned)*p++);
printf ("\n");
}
}
else
{
fprintf(stderr, "Not an ELF file '%s'\n", argv[c]);
rc = 1;
}
elf_end (elf);
}
else
{
fprintf(stderr, "Couldn't create ELF for '%s': %s\n",
argv[c], elf_errmsg (-1));
rc = 1;
}
close (fd);
}
else
{
fprintf(stderr, "Couldn't open '%s': %m\n", argv[c]);
rc = 1;
}
}
return rc;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment