diff --git a/Doc/library/zipimport.rst b/Doc/library/zipimport.rst index c4a0df1d0314d0c..5ed2b3278d1f1fa 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 94875d7153f9c5b..2dbf4013cfdf25d 100644 --- a/Lib/test/test_zipimport.py +++ b/Lib/test/test_zipimport.py @@ -305,6 +305,44 @@ def test_syntax_error_in_package_init_no_fallthrough(self): with self.assertRaises(SyntaxError): spec.loader.exec_module(mod) + 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) + + 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) + + 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. 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) + 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 testPyc(self): files = {TESTMOD + pyc_ext: test_pyc} self.doTest(pyc_ext, files, TESTMOD) @@ -1118,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 diff --git a/Lib/zipimport.py b/Lib/zipimport.py index 09a85f6d7f58e86..addd22bdece43fe 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 @@ -559,12 +558,13 @@ def _read_directory(archive): _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 +577,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,8 +649,52 @@ 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): + 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'' + 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: + # 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()() + 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 data_size < 0: raise ZipImportError('negative data size') @@ -674,6 +721,11 @@ 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 == 0: # 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") @@ -705,10 +757,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 +797,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 +877,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 +892,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 000000000000000..6db58088c81a28d --- /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.