Skip to content

Instantly share code, notes, and snippets.

@obfusk
Last active April 29, 2024 01:52
Show Gist options
  • Save obfusk/b2f501023b56a9e6de6a0bb5e2a4dd37 to your computer and use it in GitHub Desktop.
Save obfusk/b2f501023b56a9e6de6a0bb5e2a4dd37 to your computer and use it in GitHub Desktop.
Get ELF build-id w/ pyelftools
#!/usr/bin/python3
# encoding: utf-8
# SPDX-FileCopyrightText: 2024 FC (Fay) Stegerman <flx@obfusk.net>
# SPDX-License-Identifier: GPL-3.0-or-later
from elftools.elf.elffile import ELFFile # type: ignore[import-untyped]
from elftools.elf.sections import NoteSection # type: ignore[import-untyped]
class Error(Exception):
pass
def elf_build_id(elffile: str) -> str:
with open(elffile, "rb") as fh:
for section in ELFFile(fh).iter_sections():
if isinstance(section, NoteSection):
for note in section.iter_notes():
if note["n_type"] == "NT_GNU_BUILD_ID":
return note["n_desc"] # type: ignore[no-any-return]
raise Error("Could not find build-id")
def main() -> None:
import argparse
parser = argparse.ArgumentParser(prog="elf-build-id.py", description="Get ELF build-id.")
parser.add_argument("elffiles", metavar="ELF", nargs="+")
args = parser.parse_args()
for elffile in args.elffiles:
build_id = elf_build_id(elffile)
print(f"{elffile!r}:\n 0x{build_id}")
if __name__ == "__main__":
main()
# vim: set tw=80 sw=4 sts=4 et fdm=marker :
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment