Skip to content

Zipimport leaks zlib.error for corrupt deflate data; zstd branch raises ZipImportError #158494

Description

@Tony123-tech

Bug report

zipimport raises zipimport.ZipImportError when a zstd-compressed
zip entry is corrupt, but leaks zlib.error when a deflate-compressed
entry is corrupt. The two branches of _get_data should behave the
same way, and zipimport's documented contract is that ZipImportError
is the exception raised by zipimporter objects.

Minimal reproducer

import os, sys, zipfile, tempfile, py_compile, importlib, struct

with tempfile.TemporaryDirectory() as d:
    src = os.path.join(d, "mymod.py")
    with open(src, "w") as f:
        f.write("x = 1\n")
    pyc = os.path.join(d, "mymod.pyc")
    py_compile.compile(src, cfile=pyc, doraise=True)

    zp = os.path.join(d, "t.zip")
    with zipfile.ZipFile(zp, "w", compression=zipfile.ZIP_DEFLATED) as z:
        z.write(pyc, "mymod.pyc")     # only .pyc, no .py fallback

    with open(zp, "r+b") as f:
        data = f.read()
        idx = data.find(b"mymod.pyc")
        lh = data.rfind(b"PK\x03\x04", 0, idx)
        name_len, extra_len = struct.unpack_from("<HH", data, lh + 26)
        data_start = lh + 30 + name_len + extra_len
        f.seek(data_start)
        f.write(b"\xff" * 8)

    sys.path.insert(0, zp)
    importlib.invalidate_caches()
    try:
        import mymod
    except Exception as e:
        print(type(e).__module__ + "." + type(e).__name__, e)

Observed

zlib.error Error -3 while decompressing data: invalid block type

Expected

zipimport.ZipImportError could not decompress deflate data

CPython main, commit 77c0675

macOS 15.6 arm64, Clang 17

Linked PRs

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    stdlibStandard Library Python modules in the Lib/ directorytype-bugAn unexpected behavior, bug, or error

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions