-
-
Notifications
You must be signed in to change notification settings - Fork 36.6k
bytearray.take_bytes() bytes object may have incorrect hash #158219
Copy link
Copy link
Open
Labels
3.15pre-release feature fixes, bugs and security fixespre-release feature fixes, bugs and security fixes3.16new features, bugs and security fixesnew features, bugs and security fixesinterpreter-core(Objects, Python, Grammar, and Parser dirs)(Objects, Python, Grammar, and Parser dirs)type-bugAn unexpected behavior, bug, or errorAn unexpected behavior, bug, or error
Description
Activity
Metadata
Metadata
Assignees
Labels
3.15pre-release feature fixes, bugs and security fixespre-release feature fixes, bugs and security fixes3.16new features, bugs and security fixesnew features, bugs and security fixesinterpreter-core(Objects, Python, Grammar, and Parser dirs)(Objects, Python, Grammar, and Parser dirs)type-bugAn unexpected behavior, bug, or errorAn unexpected behavior, bug, or error
Bug report
Bug description:
bytearrayin 3.15+ tries to avoid runtime copying by "adopting"byteswhen possible. One case where this happens is constructing from a temporary produced by encoding text:bytearray("text", encoding="utf-8"). If the encoder returns a uniquely-referenced exactbytesobject thebytearray"adopts" it as storage avoiding an allocation and copy.cpython/Objects/bytearrayobject.c
Lines 991 to 998 in 2168416
The contents can then be mutated directly via the
bytearrayAPI. Those mutations do not change thebytesobject hash. That means if a uniquely referencedbyteswith a hash set is "adopted" then retrieved via.take_bytes()the bad hash will persist causing issues withdict,set, etc.For 3.15 the only case with this "adoption" is text encoding in
bytearrayconstruction. All other codepaths get new unhashed bytes. Every built-in codec constructs its output fresh and directly returns it not settingob_shash. Custom codecs could trigger this but it is unlikely so I think a latent bug that should be fixed but not a release blocker.A custom codec which reproduces the issue in 3.15:
CPython versions tested on:
3.15
Operating systems tested on:
Linux
Linked PRs