From 4ecb6d1e9ff48dbec98a1cdc2a91d2e80d5dbd85 Mon Sep 17 00:00:00 2001 From: Itamar Oren Date: Fri, 9 Oct 2026 19:03:50 -0700 Subject: [PATCH 1/3] gh-161644: Avoid unmarshalling zipped .pyc files twice on import `get_filename()` (and so `find_spec()`) read, decompressed and unmarshalled the whole `.pyc` just to learn the file name, and `exec_module()` then did it all again. Only the 16-byte header matters for picking the file: a bad or stale header falls back to the sibling `.py`, while errors in the marshalled body never do. Split the header checks out of `_unmarshal_code()` and have `get_filename()` run only those, reading (and decompressing) just enough of the member to cover the header. A `.pyc` with a valid header and a corrupt body now fails in `exec_module()` instead of `find_spec()`, with the same exception. Co-Authored-By: Claude Fable 5.1 --- Doc/library/zipimport.rst | 5 + Lib/test/test_zipimport.py | 130 +++++++++++++++++ Lib/zipimport.py | 138 ++++++++++++++---- ...-10-09-19-30-00.gh-issue-161644.pYcHdR.rst | 6 + 4 files changed, 248 insertions(+), 31 deletions(-) create mode 100644 Misc/NEWS.d/next/Library/2026-10-09-19-30-00.gh-issue-161644.pYcHdR.rst diff --git a/Doc/library/zipimport.rst b/Doc/library/zipimport.rst index c4a0df1d0314d0..5ed2b3278d1f1f 100644 --- a/Doc/library/zipimport.rst +++ b/Doc/library/zipimport.rst @@ -128,6 +128,11 @@ zipimporter Objects .. versionadded:: 3.1 + .. versionchanged:: next + Only the header of a bytecode file is validated to determine the + file name; errors in the marshalled code are now raised when the + code is loaded rather than by this method. + .. method:: get_source(fullname) diff --git a/Lib/test/test_zipimport.py b/Lib/test/test_zipimport.py index 94875d7153f9c5..a62e9f81f5da42 100644 --- a/Lib/test/test_zipimport.py +++ b/Lib/test/test_zipimport.py @@ -305,6 +305,83 @@ def test_syntax_error_in_package_init_no_fallthrough(self): with self.assertRaises(SyntaxError): spec.loader.exec_module(mod) + def test_find_spec_does_not_unmarshal_pyc(self): + files = {TESTMOD + pyc_ext: test_pyc} + self.makeZip(files) + zi = zipimport.zipimporter(TEMP_ZIP) + expected_path = os.path.join(TEMP_ZIP, TESTMOD + pyc_ext) + + with unittest.mock.patch.object(zipimport, 'marshal', wraps=marshal) as m: + spec = zi.find_spec(TESTMOD) + self.assertEqual(spec.origin, expected_path) + self.assertEqual(zi.get_filename(TESTMOD), expected_path) + m.loads.assert_not_called() + + mod = importlib.util.module_from_spec(spec) + spec.loader.exec_module(mod) + m.loads.assert_called_once() + self.assertEqual(mod.get_file(), expected_path) + + def test_corrupt_pyc_body_defers_to_exec(self): + # A valid header selects the .pyc; the body is only read on exec. + header = test_pyc[:16] + cases = [ + (b'', EOFError), + (b'\xff\xff\xff', ValueError), + (marshal.dumps(42), TypeError), + ] + for body, exc in cases: + with self.subTest(body=body): + files = {TESTMOD + ".py": test_src, + TESTMOD + pyc_ext: header + body} + self.makeZip(files) + zi = zipimport.zipimporter(TEMP_ZIP) + zi.invalidate_caches() + + spec = zi.find_spec(TESTMOD) + self.assertEqual(spec.origin, + os.path.join(TEMP_ZIP, TESTMOD + pyc_ext)) + mod = importlib.util.module_from_spec(spec) + with self.assertRaises(exc): + spec.loader.exec_module(mod) + + def test_get_filename_reads_only_pyc_header(self): + # Guard against regressing to reading or decompressing the whole + # member; the exact byte count depends on the compression method, + # hence the loose bound. + big_co = compile(f"x = {os.urandom(300_000)!r}\n", "", "exec") + big_pyc = make_pyc(big_co, NOW, 0) + self.makeZip({TESTMOD + pyc_ext: big_pyc}) + zi = zipimport.zipimporter(TEMP_ZIP) + zi._get_files() + + reads = [] + class CountingReader(io.BufferedReader): + def read(self, size=-1): + data = super().read(size) + reads.append(len(data)) + return data + with unittest.mock.patch.object(zipimport, '_io', wraps=zipimport._io) as m: + m.open_code.side_effect = lambda path: CountingReader(io.FileIO(path)) + self.assertEqual(zi.get_filename(TESTMOD), + os.path.join(TEMP_ZIP, TESTMOD + pyc_ext)) + self.assertLess(sum(reads), len(big_pyc) // 2) + + def test_get_data_prefix(self): + # Random (incompressible) bytes followed by a compressible run, so + # the output/input ratio jumps mid-stream and the prefix loop must + # stop cleanly. + data = os.urandom(10000) + b'x' * 50000 + self.makeZip({'data.bin': data}) + zi = zipimport.zipimporter(TEMP_ZIP) + toc_entry = zi._get_files()['data.bin'] + self.assertEqual(zipimport._get_data(TEMP_ZIP, toc_entry), data) + for size in (0, 16, 1024, 5000, 60000, 100000): + with self.subTest(size=size): + prefix = zipimport._get_data(TEMP_ZIP, toc_entry, size) + self.assertGreaterEqual(len(prefix), min(size, len(data))) + self.assertEqual(prefix, data[:len(prefix)]) + def testPyc(self): files = {TESTMOD + pyc_ext: test_pyc} self.doTest(pyc_ext, files, TESTMOD) @@ -1097,6 +1174,45 @@ def assertDataEntry(name): class DeflateCompressedZipImportTestCase(UncompressedZipImportTestCase): compression = ZIP_DEFLATED + def test_find_spec_invalid_deflate_stream(self): + # zlib.error must not be wrapped in ZipImportError (an ImportError): + # spec_from_loader() would swallow it and return a spec with an + # unknown origin instead of failing. + import zipfile + import zlib + + class BadCompressor: + def compress(self, data): + return b"\xff" * len(data) + + def flush(self): + return b"" + + with unittest.mock.patch.object(zipfile, "_get_compressor", + return_value=BadCompressor()): + self.makeZip({TESTMOD + pyc_ext: test_pyc}) + zi = zipimport.zipimporter(TEMP_ZIP) + with self.assertRaises(zlib.error): + zi.find_spec(TESTMOD) + with self.assertRaises(zlib.error): + zi.get_code(TESTMOD) + + def test_decompress_prefix_small_chunks(self): + # A tiny chunk forces many loop iterations; the default chunk + # satisfies a header request in one. Sizes probe the first byte, + # end of data, and past it. + import zlib + data = os.urandom(5000) + co = zlib.compressobj(wbits=-15) + raw = co.compress(data) + co.flush() + with unittest.mock.patch.object(zipimport, '_PREFIX_READ_CHUNK', 7): + for size in (1, 16, 4999, 5000, 6000): + with self.subTest(size=size): + prefix = zipimport._decompress_prefix( + io.BytesIO(raw), 8, len(raw), size) + self.assertGreaterEqual(len(prefix), min(size, len(data))) + self.assertEqual(prefix, data[:len(prefix)]) + @support.requires_zstd() class ZStdCompressedZipImportTestCase(UncompressedZipImportTestCase): @@ -1158,6 +1274,20 @@ def test_truncated_frame(self): with self.assertRaises(zipimport.ZipImportError): zipimport._zstd_decompress(data) + def test_decompress_prefix_concatenated_frames(self): + # A frame ends mid-prefix; the loop must switch to a fresh + # decompressor and carry over unused_data. + from compression import zstd + + data = b'abc' + bytes(range(256)) * 10 + raw = zstd.compress(data[:3]) + zstd.compress(data[3:]) + for size in (1, 3, 4, 16, len(data), len(data) + 1): + with self.subTest(size=size): + prefix = zipimport._decompress_prefix( + io.BytesIO(raw), 93, len(raw), size) + self.assertGreaterEqual(len(prefix), min(size, len(data))) + self.assertEqual(prefix, data[:len(prefix)]) + class BadFileZipImportTestCase(unittest.TestCase): def assertZipFailure(self, filename): diff --git a/Lib/zipimport.py b/Lib/zipimport.py index 09a85f6d7f58e8..530537cad563bc 100644 --- a/Lib/zipimport.py +++ b/Lib/zipimport.py @@ -163,8 +163,7 @@ def get_filename(self, fullname): """ # Deciding the filename requires working out where the code # would come from if the module was actually loaded - _, _, modpath = _get_module_code( - self, fullname, compile_source=False) + _, _, modpath = _get_module_code(self, fullname, load_code=False) return modpath @@ -557,14 +556,22 @@ def _read_directory(archive): '\xb0\u2219\xb7\u221a\u207f\xb2\u25a0\xa0' ) +# ZIP compression methods supported by zipimport. bz2 and lzma could be +# added, but are largely obsolete. +_ZIP_STORED = 0 +_ZIP_DEFLATED = 8 +_ZIP_ZSTANDARD = 93 +_RAW_DEFLATE_WBITS = -15 + _importing_zlib = False _zlib_decompress = None +_zlib_decompressobj = None # Return the zlib.decompress function object, or NULL if zlib couldn't # be imported. The function is cached when found, so subsequent calls # don't import zlib again. def _get_zlib_decompress_func(): - global _zlib_decompress + global _zlib_decompress, _zlib_decompressobj if _zlib_decompress: return _zlib_decompress @@ -577,6 +584,9 @@ def _get_zlib_decompress_func(): _importing_zlib = True try: + # _decompress_prefix() relies on _zlib_decompressobj being set + # whenever _zlib_decompress is, so bind them in this order. + from zlib import decompressobj as _zlib_decompressobj from zlib import decompress as _zlib_decompress except Exception: _bootstrap._verbose_message('zipimport: zlib UNAVAILABLE') @@ -646,9 +656,51 @@ def _zstd_decompress(data): return b"".join(results) +# Compressed input fed to the decompressor per iteration. Deflate and zstd +# emit the Huffman tables before any output, so a chunk should cover them. +_PREFIX_READ_CHUNK = 1024 + +# Decompress only the beginning of a compressed member: read from fp, which +# is positioned at the member's data, until at least min_bytes decompressed +# bytes are available (or the member ends), and return them. +def _decompress_prefix(fp, compress, data_size, min_bytes): + if compress == _ZIP_DEFLATED: + _get_zlib_decompress_func() + decomp = _zlib_decompressobj(_RAW_DEFLATE_WBITS) + else: + decomp = _get_zstd_decompressor_class()() + result = b'' + remaining = data_size + pending = b'' + while len(result) < min_bytes and (remaining or pending): + if pending: + chunk, pending = pending, b'' + else: + chunk = fp.read(min(remaining, _PREFIX_READ_CHUNK)) + if not chunk: + raise OSError("zipimport: can't read data") + remaining -= len(chunk) + needed = min_bytes - len(result) + try: + result += decomp.decompress(chunk, needed) + except Exception: + if compress == _ZIP_DEFLATED: + raise + raise ZipImportError("could not decompress zstd data") + if compress == _ZIP_ZSTANDARD and decomp.eof: + # Concatenated zstd frames: continue with a fresh decompressor. + pending = decomp.unused_data + decomp = _get_zstd_decompressor_class()() + return result + + # Given a path to a Zip file and a toc_entry, return the (uncompressed) data. -def _get_data(archive, toc_entry): +# If min_bytes is non-negative, only the first min_bytes bytes are needed: the +# result may be longer, or shorter if the data is. +def _get_data(archive, toc_entry, min_bytes=-1): datapath, compress, data_size, file_size, file_offset, time, date, crc = toc_entry + if compress not in (_ZIP_STORED, _ZIP_DEFLATED, _ZIP_ZSTANDARD): + raise ZipImportError(f"zipimport: unsupported compression {compress}") if data_size < 0: raise ZipImportError('negative data size') @@ -674,27 +726,28 @@ def _get_data(archive, toc_entry): fp.seek(file_offset) except OSError: raise ZipImportError(f"can't read Zip file: {archive!r}", path=archive) + if min_bytes >= 0: + if compress == _ZIP_STORED: + data_size = min(min_bytes, data_size) + else: + return _decompress_prefix(fp, compress, data_size, min_bytes) raw_data = fp.read(data_size) if len(raw_data) != data_size: raise OSError("zipimport: can't read data") - match compress: - case 0: # stored - return raw_data - case 8: # deflate aka zlib - try: - decompress = _get_zlib_decompress_func() - except Exception: - raise ZipImportError("can't decompress data; zlib not available") - return decompress(raw_data, -15) - case 93: # zstd - try: - return _zstd_decompress(raw_data) - except Exception: - raise ZipImportError("could not decompress zstd data") - # bz2 and lzma could be added, but are largely obsolete. - case _: - raise ZipImportError(f"zipimport: unsupported compression {compress}") + if compress == _ZIP_STORED: + return raw_data + elif compress == _ZIP_DEFLATED: + try: + decompress = _get_zlib_decompress_func() + except Exception: + raise ZipImportError("can't decompress data; zlib not available") + return decompress(raw_data, _RAW_DEFLATE_WBITS) + else: + try: + return _zstd_decompress(raw_data) + except Exception: + raise ZipImportError("could not decompress zstd data") # Lenient date/time comparison function. The precision of the mtime @@ -705,10 +758,14 @@ def _eq_mtime(t1, t2): return abs(t1 - t2) <= 1 -# Given the contents of a .py[co] file, unmarshal the data -# and return the code object. Raises ImportError it the magic word doesn't -# match, or if the recorded .py[co] metadata does not match the source. -def _unmarshal_code(self, pathname, fullpath, fullname, data): +# Size of the .pyc header (see PEP 552). +_PYC_HEADER_SIZE = 16 + +# Given at least the first _PYC_HEADER_SIZE bytes of a .pyc file, raise +# ImportError if the magic number or flags are bad or a checked hash doesn't +# match the source, return False if a timestamp-based .pyc is stale, and +# True otherwise. The marshalled code is not examined. +def _validate_pyc_header(self, fullpath, fullname, data): exc_details = { 'name': fullname, 'path': fullpath, @@ -741,9 +798,18 @@ def _unmarshal_code(self, pathname, fullpath, fullname, data): _unpack_uint32(data[12:16]) != source_size): _bootstrap._verbose_message( f'bytecode is stale for {fullname!r}') - return None + return False + return True - code = marshal.loads(data[16:]) + +# Given the contents of a .py[co] file, unmarshal the data +# and return the code object. Raises ImportError if the magic word doesn't +# match, or if the recorded .py[co] metadata does not match the source. +# Returns None if the .pyc is stale. +def _unmarshal_code(self, pathname, fullpath, fullname, data): + if not _validate_pyc_header(self, fullpath, fullname, data): + return None + code = marshal.loads(data[_PYC_HEADER_SIZE:]) if not isinstance(code, _code_type): raise TypeError(f'compiled module {pathname!r} is not a code object') return code @@ -812,8 +878,10 @@ def _get_pyc_source(self, path): # Get the code object associated with the module specified by 'fullname'. -# If compile_source is false, return None for source code without reading or compiling it. -def _get_module_code(self, fullname, *, compile_source=True): +# If load_code is false, return None instead of the code object and only +# determine which file it would come from, without compiling source or +# unmarshalling bytecode. +def _get_module_code(self, fullname, *, load_code=True): path = _get_module_path(self, fullname) import_error = None for suffix, isbytecode, ispackage in _zip_searchorder: @@ -825,8 +893,16 @@ def _get_module_code(self, fullname, *, compile_source=True): pass else: modpath = toc_entry[0] - if not isbytecode and not compile_source: - return None, ispackage, modpath + if not load_code: + if not isbytecode: + return None, ispackage, modpath + header = _get_data(self.archive, toc_entry, _PYC_HEADER_SIZE) + try: + if _validate_pyc_header(self, fullpath, fullname, header): + return None, ispackage, modpath + except ImportError as exc: + import_error = exc + continue data = _get_data(self.archive, toc_entry) code = None if isbytecode: diff --git a/Misc/NEWS.d/next/Library/2026-10-09-19-30-00.gh-issue-161644.pYcHdR.rst b/Misc/NEWS.d/next/Library/2026-10-09-19-30-00.gh-issue-161644.pYcHdR.rst new file mode 100644 index 00000000000000..6db58088c81a28 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2026-10-09-19-30-00.gh-issue-161644.pYcHdR.rst @@ -0,0 +1,6 @@ +Modules imported from bytecode in ZIP archives are no longer unmarshalled +twice: :meth:`zipimport.zipimporter.get_filename`, and therefore +:meth:`~zipimport.zipimporter.find_spec`, now only read and validate the +header of the ``.pyc`` file, decompressing just its first bytes. A ``.pyc`` +file with a valid header but a corrupt body is now reported when the module +is executed rather than when it is found. From fbe3eb04da638353865d952836c06a1d6cb9979f Mon Sep 17 00:00:00 2001 From: Itamar Oren Date: Tue, 24 Nov 2026 18:15:17 -0800 Subject: [PATCH 2/3] Trim new zipimport tests Keep a minimal subset that covers most of what the previous set covered --- Lib/test/test_zipimport.py | 121 +++++-------------------------------- 1 file changed, 15 insertions(+), 106 deletions(-) diff --git a/Lib/test/test_zipimport.py b/Lib/test/test_zipimport.py index a62e9f81f5da42..2dbf4013cfdf25 100644 --- a/Lib/test/test_zipimport.py +++ b/Lib/test/test_zipimport.py @@ -305,51 +305,27 @@ def test_syntax_error_in_package_init_no_fallthrough(self): with self.assertRaises(SyntaxError): spec.loader.exec_module(mod) - def test_find_spec_does_not_unmarshal_pyc(self): - files = {TESTMOD + pyc_ext: test_pyc} + def test_corrupt_pyc_body_defers_to_exec(self): + # A valid header selects the .pyc; the body is only read on exec. + files = {TESTMOD + ".py": test_src, + TESTMOD + pyc_ext: test_pyc[:16] + b'\xff\xff\xff'} self.makeZip(files) zi = zipimport.zipimporter(TEMP_ZIP) - expected_path = os.path.join(TEMP_ZIP, TESTMOD + pyc_ext) - - with unittest.mock.patch.object(zipimport, 'marshal', wraps=marshal) as m: - spec = zi.find_spec(TESTMOD) - self.assertEqual(spec.origin, expected_path) - self.assertEqual(zi.get_filename(TESTMOD), expected_path) - m.loads.assert_not_called() - mod = importlib.util.module_from_spec(spec) + spec = zi.find_spec(TESTMOD) + self.assertEqual(spec.origin, + os.path.join(TEMP_ZIP, TESTMOD + pyc_ext)) + mod = importlib.util.module_from_spec(spec) + with self.assertRaises(ValueError): spec.loader.exec_module(mod) - m.loads.assert_called_once() - self.assertEqual(mod.get_file(), expected_path) - - def test_corrupt_pyc_body_defers_to_exec(self): - # A valid header selects the .pyc; the body is only read on exec. - header = test_pyc[:16] - cases = [ - (b'', EOFError), - (b'\xff\xff\xff', ValueError), - (marshal.dumps(42), TypeError), - ] - for body, exc in cases: - with self.subTest(body=body): - files = {TESTMOD + ".py": test_src, - TESTMOD + pyc_ext: header + body} - self.makeZip(files) - zi = zipimport.zipimporter(TEMP_ZIP) - zi.invalidate_caches() - - spec = zi.find_spec(TESTMOD) - self.assertEqual(spec.origin, - os.path.join(TEMP_ZIP, TESTMOD + pyc_ext)) - mod = importlib.util.module_from_spec(spec) - with self.assertRaises(exc): - spec.loader.exec_module(mod) def test_get_filename_reads_only_pyc_header(self): # Guard against regressing to reading or decompressing the whole # member; the exact byte count depends on the compression method, - # hence the loose bound. - big_co = compile(f"x = {os.urandom(300_000)!r}\n", "", "exec") + # hence the loose bound. The payload is compressible so that zstd + # needs several reads before producing any output. + big_src = f"x = {os.urandom(300_000).hex()!r}\n" + big_co = compile(big_src, "", "exec") big_pyc = make_pyc(big_co, NOW, 0) self.makeZip({TESTMOD + pyc_ext: big_pyc}) zi = zipimport.zipimporter(TEMP_ZIP) @@ -367,21 +343,6 @@ def read(self, size=-1): os.path.join(TEMP_ZIP, TESTMOD + pyc_ext)) self.assertLess(sum(reads), len(big_pyc) // 2) - def test_get_data_prefix(self): - # Random (incompressible) bytes followed by a compressible run, so - # the output/input ratio jumps mid-stream and the prefix loop must - # stop cleanly. - data = os.urandom(10000) + b'x' * 50000 - self.makeZip({'data.bin': data}) - zi = zipimport.zipimporter(TEMP_ZIP) - toc_entry = zi._get_files()['data.bin'] - self.assertEqual(zipimport._get_data(TEMP_ZIP, toc_entry), data) - for size in (0, 16, 1024, 5000, 60000, 100000): - with self.subTest(size=size): - prefix = zipimport._get_data(TEMP_ZIP, toc_entry, size) - self.assertGreaterEqual(len(prefix), min(size, len(data))) - self.assertEqual(prefix, data[:len(prefix)]) - def testPyc(self): files = {TESTMOD + pyc_ext: test_pyc} self.doTest(pyc_ext, files, TESTMOD) @@ -1174,45 +1135,6 @@ def assertDataEntry(name): class DeflateCompressedZipImportTestCase(UncompressedZipImportTestCase): compression = ZIP_DEFLATED - def test_find_spec_invalid_deflate_stream(self): - # zlib.error must not be wrapped in ZipImportError (an ImportError): - # spec_from_loader() would swallow it and return a spec with an - # unknown origin instead of failing. - import zipfile - import zlib - - class BadCompressor: - def compress(self, data): - return b"\xff" * len(data) - - def flush(self): - return b"" - - with unittest.mock.patch.object(zipfile, "_get_compressor", - return_value=BadCompressor()): - self.makeZip({TESTMOD + pyc_ext: test_pyc}) - zi = zipimport.zipimporter(TEMP_ZIP) - with self.assertRaises(zlib.error): - zi.find_spec(TESTMOD) - with self.assertRaises(zlib.error): - zi.get_code(TESTMOD) - - def test_decompress_prefix_small_chunks(self): - # A tiny chunk forces many loop iterations; the default chunk - # satisfies a header request in one. Sizes probe the first byte, - # end of data, and past it. - import zlib - data = os.urandom(5000) - co = zlib.compressobj(wbits=-15) - raw = co.compress(data) + co.flush() - with unittest.mock.patch.object(zipimport, '_PREFIX_READ_CHUNK', 7): - for size in (1, 16, 4999, 5000, 6000): - with self.subTest(size=size): - prefix = zipimport._decompress_prefix( - io.BytesIO(raw), 8, len(raw), size) - self.assertGreaterEqual(len(prefix), min(size, len(data))) - self.assertEqual(prefix, data[:len(prefix)]) - @support.requires_zstd() class ZStdCompressedZipImportTestCase(UncompressedZipImportTestCase): @@ -1234,7 +1156,8 @@ def flush(self): "_get_compressor", return_value=ConcatenatedFrameCompressor(), ): - self.doTest(".py", {TESTMOD + ".py": test_src}, TESTMOD) + self.doTest(pyc_ext, {TESTMOD + ".py": test_src, + TESTMOD + pyc_ext: test_pyc}, TESTMOD) def test_concatenated_frames_linear_input(self): from compression import zstd @@ -1274,20 +1197,6 @@ def test_truncated_frame(self): with self.assertRaises(zipimport.ZipImportError): zipimport._zstd_decompress(data) - def test_decompress_prefix_concatenated_frames(self): - # A frame ends mid-prefix; the loop must switch to a fresh - # decompressor and carry over unused_data. - from compression import zstd - - data = b'abc' + bytes(range(256)) * 10 - raw = zstd.compress(data[:3]) + zstd.compress(data[3:]) - for size in (1, 3, 4, 16, len(data), len(data) + 1): - with self.subTest(size=size): - prefix = zipimport._decompress_prefix( - io.BytesIO(raw), 93, len(raw), size) - self.assertGreaterEqual(len(prefix), min(size, len(data))) - self.assertEqual(prefix, data[:len(prefix)]) - class BadFileZipImportTestCase(unittest.TestCase): def assertZipFailure(self, filename): From b47531b09f45418b74d729e67b0135bd50de04de Mon Sep 17 00:00:00 2001 From: Itamar Oren Date: Tue, 24 Nov 2026 19:47:18 -0800 Subject: [PATCH 3/3] Restore match-based compression dispatch, drop global consts --- Lib/zipimport.py | 63 ++++++++++++++++++++++++------------------------ 1 file changed, 31 insertions(+), 32 deletions(-) diff --git a/Lib/zipimport.py b/Lib/zipimport.py index 530537cad563bc..addd22bdece43f 100644 --- a/Lib/zipimport.py +++ b/Lib/zipimport.py @@ -556,13 +556,6 @@ def _read_directory(archive): '\xb0\u2219\xb7\u221a\u207f\xb2\u25a0\xa0' ) -# ZIP compression methods supported by zipimport. bz2 and lzma could be -# added, but are largely obsolete. -_ZIP_STORED = 0 -_ZIP_DEFLATED = 8 -_ZIP_ZSTANDARD = 93 -_RAW_DEFLATE_WBITS = -15 - _importing_zlib = False _zlib_decompress = None _zlib_decompressobj = None @@ -664,11 +657,14 @@ def _zstd_decompress(data): # is positioned at the member's data, until at least min_bytes decompressed # bytes are available (or the member ends), and return them. def _decompress_prefix(fp, compress, data_size, min_bytes): - if compress == _ZIP_DEFLATED: - _get_zlib_decompress_func() - decomp = _zlib_decompressobj(_RAW_DEFLATE_WBITS) - else: - decomp = _get_zstd_decompressor_class()() + match compress: + case 8: # deflate aka zlib + _get_zlib_decompress_func() + decomp = _zlib_decompressobj(-15) + case 93: # zstd + decomp = _get_zstd_decompressor_class()() + case _: + raise ZipImportError(f"zipimport: unsupported compression {compress}") result = b'' remaining = data_size pending = b'' @@ -684,10 +680,11 @@ def _decompress_prefix(fp, compress, data_size, min_bytes): try: result += decomp.decompress(chunk, needed) except Exception: - if compress == _ZIP_DEFLATED: - raise - raise ZipImportError("could not decompress zstd data") - if compress == _ZIP_ZSTANDARD and decomp.eof: + # As in _get_data(): zlib errors propagate, zstd errors are wrapped. + if compress == 93: + raise ZipImportError("could not decompress zstd data") + raise + if compress == 93 and decomp.eof: # Concatenated zstd frames: continue with a fresh decompressor. pending = decomp.unused_data decomp = _get_zstd_decompressor_class()() @@ -699,8 +696,6 @@ def _decompress_prefix(fp, compress, data_size, min_bytes): # result may be longer, or shorter if the data is. def _get_data(archive, toc_entry, min_bytes=-1): datapath, compress, data_size, file_size, file_offset, time, date, crc = toc_entry - if compress not in (_ZIP_STORED, _ZIP_DEFLATED, _ZIP_ZSTANDARD): - raise ZipImportError(f"zipimport: unsupported compression {compress}") if data_size < 0: raise ZipImportError('negative data size') @@ -727,7 +722,7 @@ def _get_data(archive, toc_entry, min_bytes=-1): except OSError: raise ZipImportError(f"can't read Zip file: {archive!r}", path=archive) if min_bytes >= 0: - if compress == _ZIP_STORED: + if compress == 0: # stored data_size = min(min_bytes, data_size) else: return _decompress_prefix(fp, compress, data_size, min_bytes) @@ -735,19 +730,23 @@ def _get_data(archive, toc_entry, min_bytes=-1): if len(raw_data) != data_size: raise OSError("zipimport: can't read data") - if compress == _ZIP_STORED: - return raw_data - elif compress == _ZIP_DEFLATED: - try: - decompress = _get_zlib_decompress_func() - except Exception: - raise ZipImportError("can't decompress data; zlib not available") - return decompress(raw_data, _RAW_DEFLATE_WBITS) - else: - try: - return _zstd_decompress(raw_data) - except Exception: - raise ZipImportError("could not decompress zstd data") + match compress: + case 0: # stored + return raw_data + case 8: # deflate aka zlib + try: + decompress = _get_zlib_decompress_func() + except Exception: + raise ZipImportError("can't decompress data; zlib not available") + return decompress(raw_data, -15) + case 93: # zstd + try: + return _zstd_decompress(raw_data) + except Exception: + raise ZipImportError("could not decompress zstd data") + # bz2 and lzma could be added, but are largely obsolete. + case _: + raise ZipImportError(f"zipimport: unsupported compression {compress}") # Lenient date/time comparison function. The precision of the mtime