pypa/pip · error · ELFInvalid

invalid magic

Error message

invalid magic: {magic!r}

What it means

After reading 16 identification bytes, ELFFile checks that the first 4 bytes equal b'\x7fELF' (the canonical ELF magic number). If they differ, the file is definitively not an ELF binary and ELFInvalid is raised with the actual magic bytes shown. This distinguishes a structurally intact but wrong-format file from a truncated one.

Solutions

  1. Check the first 4 bytes match b'\x7fELF' before constructing ELFFile
  2. Route binaries to the correct parser based on their magic bytes (MZ for PE, \xfe\xed\xfa for Mach-O)
  3. Catch ELFInvalid and skip non-ELF files in batch processing

Example fix

# before
elf = ELFFile(open(binary_path, "rb"))  # crashes on .exe / Mach-O files

# after
with open(binary_path, "rb") as f:
    magic = f.read(4)
    f.seek(0)
    if magic != b"\x7fELF":
        print(f"Skipping non-ELF file: {binary_path}")
        continue
    elf = ELFFile(f)
Defensive patterns

Strategy: validation

Validate before calling

def validate_elf_magic(path):
    with open(path, "rb") as f:
        magic = f.read(4)
    if magic != b"\x7fELF":
        raise ValueError(f"Not an ELF file: magic bytes are {magic!r}")

Try / catch

from packaging._elffile import ELFFile, ELFInvalid

try:
    with open(path, "rb") as f:
        elf = ELFFile(f)
except ELFInvalid as e:
    if "invalid magic" in str(e):
        # not an ELF binary; try PE, Mach-O, or skip
        elf = None

Prevention

When it happens

Trigger: Passing any file that is >=16 bytes whose first 4 bytes are not b'\x7fELF': Windows PE executables (.exe/.dll), macOS Mach-O binaries, Java class files, scripts, or arbitrary data blobs.

Common situations: Cross-platform builds where Windows or macOS binaries are mistakenly fed to ELF parsing code. Processing mixed-architecture artifact directories. Downloaded files that are actually HTML error pages or checksum files.

Related errors


AI-assisted analysis of pypa/pip@f399c37189 (2026-08-08). Data as JSON: /api/errors/462ab93f46beca78. Report an issue: GitHub.

Appendix: source

Thrown at src/pip/_vendor/packaging/_elffile.py:54

    X8664 = 62
    AArch64 = 183


class ELFFile:
    """
    Representation of an ELF executable.
    """

    def __init__(self, f: IO[bytes]) -> None:
        self._f = f

        try:
            ident = self._read("16B")
        except struct.error as e:
            raise ELFInvalid("unable to parse identification") from e
        magic = bytes(ident[:4])
        if magic != b"\x7fELF":
            raise ELFInvalid(f"invalid magic: {magic!r}")

        self.capacity = ident[4]  # Format for program header (bitness).
        self.encoding = ident[5]  # Data structure encoding (endianness).

        try:
            # e_fmt: Format for the ELF header.
            # p_fmt: Format for a program header.
            # p_idx: Indexes to find p_type, p_offset, and p_filesz.
            e_fmt, self._p_fmt, self._p_idx = {
                (1, 1): ("<HHIIIIIHHH", "<IIIIIIII", (0, 1, 4)),  # 32-bit LSB.
                (1, 2): (">HHIIIIIHHH", ">IIIIIIII", (0, 1, 4)),  # 32-bit MSB.
                (2, 1): ("<HHIQQQIHHH", "<IIQQQQQQ", (0, 2, 5)),  # 64-bit LSB.
                (2, 2): (">HHIQQQIHHH", ">IIQQQQQQ", (0, 2, 5)),  # 64-bit MSB.
            }[(self.capacity, self.encoding)]
        except KeyError as e:
            raise ELFInvalid(
                f"unrecognized capacity ({self.capacity}) or encoding ({self.encoding})"
            ) from e

View on GitHub (pinned to f399c37189)