Registry / devops / pyelftools

pyelftools

JSON →
library0.33pypypi✓ verified 27d ago

pyelftools is a Python library for parsing and analyzing ELF files and DWARF debugging information. It provides a low-level interface to the structures within these binary formats, making it suitable for security research, reverse engineering, and compiler development. The current stable version is 0.32, with new features and bug fixes released periodically.

pip install pyelftools
INSTALL
IMPORT
SIG · PYELFTOOLS
P
pyelftools
devopspythonv0.33
Install
1.6s avg
Import
174ms
Disk
17MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v0.33 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.103.95 runs
installs and imports cleanly · install 0.0s · import 0.186s · 19.2MB
glibc
py 3.103.95 runs
installs and imports cleanly · install 1.6s · import 0.162s · 20MB
17MB installed
● package 17MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

ELFFile
from elftools.elf.elffile import ELFFile
DWARFInfo
from elftools.dwarf.dwarfinfo import DWARFInfo
ET_CORE
from elftools.elf.elffile import ET_CORE
Constants like ET_CORE, ET_EXEC, etc. are also exposed via elffile.

This quickstart demonstrates how to open an ELF file, extract basic header information, and iterate through its sections using `pyelftools`. It also checks for the presence of DWARF debugging information. Remember to replace `'/bin/ls'` with a valid path to an ELF executable on your system.

import os from elftools.elf.elffile import ELFFile def analyze_elf(filepath): if not os.path.exists(filepath): print(f"Error: File not found at {filepath}") return try: with open(filepath, 'rb') as f: elf_file = ELFFile(f) print(f"\nAnalyzing ELF: {filepath}") print(f" Class: {elf_file.elfclass} ({'64-bit' if elf_file.elfclass == 64 else '32-bit'})") print(f" Endianness: {'Little' if elf_file.little_endian else 'Big'}") print(f" Machine Arch: {elf_file.get_machine_arch()}") print(f" Entry Point: 0x{elf_file.header['e_entry']:x}") # Example: Iterate through sections print(" Sections:") for section in elf_file.iter_sections(): print(f" - {section.name} (type: {section['sh_type']})") if elf_file.has_dwarf_info(): print(" Contains DWARF info.") except Exception as e: print(f"Error processing ELF file: {e}") # Example usage: Replace with a path to a real ELF binary on your system # For demonstration, let's assume '/bin/ls' or a similar common binary exists. # On Windows, you might need a WSL path or a Linux VM for native ELF binaries. # For a true cross-platform example, you'd need to create a dummy ELF. # For this quickstart, assume a /bin/ls exists (common on Linux/macOS). if os.path.exists('/bin/ls'): analyze_elf('/bin/ls') elif os.name == 'posix': print("'/bin/ls' not found. Please provide a path to an ELF binary on your system to run this example.") else: print("This quickstart needs an ELF binary (like '/bin/ls') to run. Not applicable on Windows without WSL.")
Debug
Known issues
breakingThe exception hierarchy was refactored in version 0.30.0. The general `elftools.common.exceptions.ELFError` was removed and split into more specific exceptions (e.g., `ELFParseError`, `ELFEndianError`, `ELFRelocationError`). Catching the old `ELFError` will now fail.
fix
Update exception handling to catch specific exceptions like `ELFParseError` or `ELFEndianError` from `elftools.common.exceptions`.
affects: >=0.30.0
breakingFor DWARF debugging information, the `DIE.get_form_attribute()` method was removed in version 0.31.0. This method was considered old and unused.
fix
Access DWARF attribute forms directly via `DIE.attributes[attr_name].form` instead of using the deprecated method.
affects: >=0.31.0
breakingIn version 0.29.0, the `location` attribute of `DW_AT_location` is now always a `LocationExpr` object. It no longer directly holds the raw data or a simple offset.
fix
If accessing DWARF location information, use `LocationExpr.evaluate()` to interpret the location expression instead of directly using the `location` attribute's value.
affects: >=0.29.0
gotchaWhen opening ELF files, ensure they are always opened in binary read mode (`'rb'`). Opening in text mode (`'r'`) or binary write mode will lead to errors or corrupted data.
fix
Always use `with open(filepath, 'rb') as f:` for opening binary files with `pyelftools`.
affects: all
gotchaWhile `pyelftools` provides detailed DWARF parsing, interpreting the full complexity of DWARF information (e.g., location expressions, type graphs) often requires additional logic or domain-specific knowledge beyond what the library directly provides as high-level abstractions.
fix
Be prepared to write custom code to fully interpret complex DWARF structures. Refer to the DWARF standard for detailed understanding.
affects: all
Errors
Common errors & fixes
ModuleNotFoundError: No module named 'elftools'
The pyelftools library is not installed in the Python environment being used, or there is a mismatch between the installed version and the expected module structure (e.g., 'elftools.common.py3compat' might be missing in older or specific setups).
fix
Install pyelftools using pip: `pip install pyelftools`. If already installed, ensure you are running your script with the correct Python interpreter where pyelftools is installed, or try `pip install --upgrade pyelftools`.
elftools.common.exceptions.ELFError: Magic number does not match
The file provided to the ELFFile constructor is either not a valid ELF file, or the file pointer within a stream is not positioned at the absolute beginning of an ELF header (offset 0 or a known ELF header offset).
fix
Verify that the input file is a legitimate ELF executable, object file, or shared library. If reading from a stream (e.g., a memory dump), ensure the file object's `seek()` method is used to position the pointer to the exact start of the ELF header before passing it to `ELFFile(f)`.
elftools.common.exceptions.ELFParseError: expected X, found Y
The pyelftools library encountered a malformed or non-standard ELF structure within the file, expecting a specific amount of data or a particular format element, but found something different or unexpected.
fix
This often indicates that the ELF file is corrupted or non-compliant with the standard pyelftools expects. The fix involves verifying the integrity and standard compliance of the ELF file. If the file is known to be slightly malformed but still parsable by other tools, you may need to implement custom error handling or accept that pyelftools adheres strictly to the ELF specification.
TypeError: unhashable type: 'Section'
In pyelftools versions prior to 0.31 (e.g., 0.30), the `Section` class had a `__hash__` method that explicitly raised a `TypeError`, preventing `Section` objects from being used in hash-based collections like dictionaries or sets.
fix
Upgrade pyelftools to version 0.31 or newer: `pip install --upgrade pyelftools`. If upgrading is not feasible, avoid using `Section` objects directly as dictionary keys or set members; instead, use unique identifiers (like section names or addresses) if hashable objects are required.
Upgrade
Version history
0.33latest on PyPI · released May 29, 2026
Audit
Dependencies

No dependency data recorded yet.

Agent activity
10 hits · last 30 days
node
8
OpenAI (training)
1
Resources
pyelftools — pip install pyelftools · libregistry