Skip to content

Windows: non-canonical cpXXX names (cp01252, cp1_252) each cache a new codec #162462

Open

Description

@nova1457

Bug report

On Windows, encodings.win32_code_page_search_function() reads the code page number with int(encoding[2:]). int() also accepts leading zeros and underscores, so cp01252 and cp1_252 both resolve to code page 1252. For each new spelling create_win32_code_page_codec() builds a new CodecInfo with four new classes, the codec registry caches it, and that cache has no size limit: about 11 KB per spelling.

The name can come from parsed input, such as an XML encoding declaration or an e-mail charset parameter. The entries stay for the life of the process unless the program calls codecs.unregister().

3.13 rejects both spellings; 3.14 accepts them. Measured on 3.14.7, 3.14.10 and 3.13.12 (Windows 11). 3.15 and main have the same lines today; I did not run them.

import codecs
import sys
import tracemalloc

tracemalloc.start()
for number in range(2000):
    zeros = "".join("_0" if number >> bit & 1 else "0" for bit in range(11))
    try:
        codecs.lookup("cp0" + zeros + "1252")
    except LookupError:
        pass
held = tracemalloc.get_traced_memory()[0]
print(f"{held:,} bytes held after 2,000 lookups")
sys.exit(1 if held > 2_000_000 else 0)

On 3.14.10 it reports about 23 million bytes held and exits with 1; on 3.13.12 it exits with 0.

The limit added in #146054 covers the encodings.search_function cache. The entries here are kept by the codec registry cache instead, which has none.

A possible fix is to accept only the canonical spelling; with it the script exits with 0 on 3.14.10:

diff --git a/Lib/encodings/__init__.py b/Lib/encodings/__init__.py
index 8548bbe..c18edaf 100644
--- a/Lib/encodings/__init__.py
+++ b/Lib/encodings/__init__.py
@@ -171,6 +171,9 @@ if sys.platform == 'win32':
             cp = int(encoding[2:])
         except ValueError:
             return None
+        # int() also accepts '01252' and '1_252': one name per code page.
+        if encoding != f'cp{cp}':
+            return None
         # Test if the code page is supported
         try:
             codecs.code_page_encode(cp, 'x')

I reported this privately first and was asked to open a public issue.

I found this with the help of an AI model (Claude, through Claude Code). I ran the scripts myself.

CPython versions tested on:

3.13, 3.14

Operating systems tested on:

Windows

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

    OS-windowsstdlibStandard Library Python modules in the Lib/ directorytopic-unicodetype-bugAn unexpected behavior, bug, or error

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions