pypa/pip · error · ELFInvalid

invalid magic: {magic!r}

Error message

invalid magic: {magic!r}

What it means

Raised by `ELFFile.__init__` when the first four bytes of the file are not the ELF magic `b'\x7fELF'`. The magic is the canonical signature of an ELF executable; anything else means this is not an ELF object regardless of file extension. The offending bytes are echoed via `{magic!r}`.

Source

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

    X8664 = 62
    AArc64 = 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 program header.
            # p_fmt: Format for section 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 d7d0d0a394)

Solutions

  1. Check `pathlib.Path(path).read_bytes()[:4] == b'\x7fELF'` before constructing ELFFile
  2. Branch on `sys.platform` / the wheel platform tag before invoking ELF parsing
  3. Wrap in try/except ELFInvalid and fall back to skipping the file

Example fix

// before
elf = ELFFile(open(path, 'rb'))
// after
with open(path, 'rb') as f:
    if f.read(4) != b'\x7fELF':
        raise ValueError(f'{path} is not an ELF binary')
    f.seek(0)
    elf = ELFFile(f)
Defensive patterns

Strategy: validation

Validate before calling

def is_elf(path: str) -> bool:
    with open(path, 'rb') as fh:
        return fh.read(4) == b'\x7fELF'

Type guard

def is_elf_magic(prefix: bytes) -> bool:
    return isinstance(prefix, (bytes, bytearray)) and len(prefix) >= 4 and bytes(prefix[:4]) == b'\x7fELF'

Try / catch

from packaging._elffile import ELFFile, ELFInvalid
try:
    elf = ELFFile(f)
except ELFInvalid as e:
    if 'magic' in str(e):
        log.info('%s is not ELF, skipping', path)
        continue
    raise

Prevention

When it happens

Trigger: Passing a Mach-O binary (macOS), PE/COFF (Windows `.exe`/`.dll`), a script, a `.pyc`, a ZIP/jar, or any random file to `ELFFile`. Commonly hit by cross-platform tooling that assumes a `.so`/executable is ELF without checking the platform.

Common situations: CI matrix that builds on macOS/Windows but runs an ELF-parsing audit unconditionally; downloading a binary from a CDN that actually returned an HTML error page; inspecting a `.dylib` thinking it's a `.so`.

Related errors


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