{"id":"462ab93f46beca78","repo":"pypa/pip","slug":"invalid-magic-magic-r","errorCode":null,"errorMessage":"invalid magic: {magic!r}","messagePattern":"invalid magic: (.+?)","errorType":"exception","errorClass":"ELFInvalid","httpStatus":null,"severity":"error","filePath":"src/pip/_vendor/packaging/_elffile.py","lineNumber":54,"sourceCode":"    X8664 = 62\n    AArc64 = 183\n\n\nclass ELFFile:\n    \"\"\"\n    Representation of an ELF executable.\n    \"\"\"\n\n    def __init__(self, f: IO[bytes]) -> None:\n        self._f = f\n\n        try:\n            ident = self._read(\"16B\")\n        except struct.error as e:\n            raise ELFInvalid(\"unable to parse identification\") from e\n        magic = bytes(ident[:4])\n        if magic != b\"\\x7fELF\":\n            raise ELFInvalid(f\"invalid magic: {magic!r}\")\n\n        self.capacity = ident[4]  # Format for program header (bitness).\n        self.encoding = ident[5]  # Data structure encoding (endianness).\n\n        try:\n            # e_fmt: Format for program header.\n            # p_fmt: Format for section header.\n            # p_idx: Indexes to find p_type, p_offset, and p_filesz.\n            e_fmt, self._p_fmt, self._p_idx = {\n                (1, 1): (\"<HHIIIIIHHH\", \"<IIIIIIII\", (0, 1, 4)),  # 32-bit LSB.\n                (1, 2): (\">HHIIIIIHHH\", \">IIIIIIII\", (0, 1, 4)),  # 32-bit MSB.\n                (2, 1): (\"<HHIQQQIHHH\", \"<IIQQQQQQ\", (0, 2, 5)),  # 64-bit LSB.\n                (2, 2): (\">HHIQQQIHHH\", \">IIQQQQQQ\", (0, 2, 5)),  # 64-bit MSB.\n            }[(self.capacity, self.encoding)]\n        except KeyError as e:\n            raise ELFInvalid(\n                f\"unrecognized capacity ({self.capacity}) or encoding ({self.encoding})\"\n            ) from e","sourceCodeStart":36,"sourceCodeEnd":72,"githubUrl":"https://github.com/pypa/pip/blob/d7d0d0a39494e28ec1c407bd0680e4a4d1067791/src/pip/_vendor/packaging/_elffile.py#L36-L72","documentation":"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}`.","triggerScenarios":"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.","commonSituations":"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`.","solutions":["Check `pathlib.Path(path).read_bytes()[:4] == b'\\x7fELF'` before constructing ELFFile","Branch on `sys.platform` / the wheel platform tag before invoking ELF parsing","Wrap in try/except ELFInvalid and fall back to skipping the file"],"exampleFix":"// before\nelf = ELFFile(open(path, 'rb'))\n// after\nwith open(path, 'rb') as f:\n    if f.read(4) != b'\\x7fELF':\n        raise ValueError(f'{path} is not an ELF binary')\n    f.seek(0)\n    elf = ELFFile(f)","handlingStrategy":"validation","validationCode":"def is_elf(path: str) -> bool:\n    with open(path, 'rb') as fh:\n        return fh.read(4) == b'\\x7fELF'","typeGuard":"def is_elf_magic(prefix: bytes) -> bool:\n    return isinstance(prefix, (bytes, bytearray)) and len(prefix) >= 4 and bytes(prefix[:4]) == b'\\x7fELF'","tryCatchPattern":"from packaging._elffile import ELFFile, ELFInvalid\ntry:\n    elf = ELFFile(f)\nexcept ELFInvalid as e:\n    if 'magic' in str(e):\n        log.info('%s is not ELF, skipping', path)\n        continue\n    raise","preventionTips":["Sniff the 4-byte magic before constructing ELFFile","Gate ELF parsing on platform (Linux/Android) when scanning cross-platform artifacts","Verify downloaded binaries against expected size/hash to catch HTML error pages"],"tags":["elf","packaging","binary-parsing","platform"],"analyzedSha":"d7d0d0a39494e28ec1c407bd0680e4a4d1067791","analyzedAt":"2026-08-04T20:55:04.259Z","schemaVersion":2}