Skip to content

iconv codecs write an error handler's replacement in a non-initial shift state #155004

Description

@serhiy-storchaka

Bug report

An error handler's replacement bytes are copied to the output without returning it to the initial shift state first, so in a stateful encoding they are read back as encoded data.

>>> '中😀中'.encode('iso-2022-cn', 'replace')
b'\x1b$)A\x0eVP?\x1b$)A\x0eVP\x0f'
>>> _.decode('iso-2022-cn')
UnicodeDecodeError: 'iso-2022-cn' codec can't decode byte 0x3f in position 7: invalid multibyte sequence
>>> '中😀中'.encode('iso-2022-cn', 'backslashreplace').decode('iso-2022-cn')
'中苷鞍氨娑鞍中'

The built-in codec of the same family shifts back to ASCII first:

>>> '日😀日'.encode('iso2022_jp', 'replace')            # built-in
b'\x1b$BF|\x1b(B?\x1b$BF|\x1b(B'
>>> '日😀日'.encode('iconv:ISO-2022-JP', 'replace')     # iconv
b'\x1b$BF|?\x1b$BF|\x1b(B'

_PyUnicode_EncodeIconv() does reset the shift state after each handled error, but with a NULL output buffer, so the conversion forgets the state while the stream never gets the closing sequence.

This affects the ISO-2022 family and the stateful EBCDIC code pages (CP1364, CP1371, ...). ignore is unaffected, it injects nothing.

Linked PRs

Metadata

Metadata

Assignees

No one assigned

    Labels

    3.16new features, bugs and security fixesstdlibStandard Library Python modules in the Lib/ directorytopic-unicodetype-bugAn unexpected behavior, bug, or error

    Projects

    Status
    In Progress

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions