Repository navigation
Fix use-after-free / out-of-bounds read from borrowed table pointers in bulk updates - #1379
Conversation
md_update_from_ht() cached htkeys_entries(other->keys) and then inserted into md; when md IS other (d.extend(d) and friends) an insert-triggered resize freed the table being iterated -> use-after-free. extend(self) now reserves capacity up front (no resize during the loop) and snapshots the entry count; update(self)/merge(self) are short-circuited as the no-ops they are. md_update_from_seq() cached PyList_GET_SIZE(seq) once; a case-insensitive key's .lower() can run arbitrary Python that shrinks seq, after which the cached size let PyList_GET_ITEM read past the end. Re-read the length each iteration. Both reproduced as SIGSEGV on ASan and debug builds; adds C-extension regression tests. (Note: the pure-Python fallback hangs on extend(self) -- a separate parity bug to fix on that side.)
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## master #1379 +/- ##
=======================================
Coverage 99.86% 99.86%
=======================================
Files 29 29
Lines 3784 3808 +24
Branches 281 282 +1
=======================================
+ Hits 3779 3803 +24
Misses 3 3
Partials 2 2
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
Vizonex
left a comment
There was a problem hiding this comment.
@devdanzin Sorry if I didn't see this sooner. This seems to be a pretty critical bug so I approve getting this PR Merged.
|
@copilot resolve the merge conflicts in this pull request |
Confidence Score: 5/5Safe to merge based on focused native-extension validation of the previously crashing paths and related error handling. No unresolved defects were found. The original crash was reproduced before the change, while the same focused checks, a debug build, and the update regression suite passed after it. Files Needing Attention: No files need further changes.
What T-Rex did
Reviews (1): Last reviewed commit: "[pre-commit.ci] auto fixes from pre-comm..." | Re-trigger Greptile |
|
Thanks, @devdanzin |
_list_getitem_ref() cleared the IndexError PyList_GetItemRef sets when
the item is gone, and each caller then made something up: update()
stopped as if the list had ended, a [key, value] item reported a bad
length and items.__contains__() answered False.
The item can only be gone because another thread shrank the list after
its length was checked, so say that: the helper turns the IndexError
into RuntimeError("list changed size during iteration"), in the family
of the multidict's own "changed during iteration" error, and all three
callers propagate it.
The per-iteration length check update() re-reads (aio-libs#1379) is untouched:
a list that is simply shorter by the next iteration still ends the
update there, as it does under the GIL and in a plain for loop.
## What do these changes do? Bulk updates from a list and `[key, value] in md.items()` borrowed items from a list the caller still owns and increfed them in a separate step. On a free-threaded build another thread can drop the item in between, or shrink the list between its length check and the reads, and the C extension reads freed memory. Each item is now taken as a new reference with `PyList_GetItemRef` on free-threaded builds, which fetches atomically and locks the list only if its lock-free attempt fails; GIL builds keep the `PyList_GET_ITEM` macro, so their hot paths are unchanged. Follows #1379, which fixed the stale length in the same loop. A critical section on the list, as #1433 takes on a dict argument, would not do: it covers neither a `[key, value]` item inside the list nor the probe handed to `in`, and it is released whenever the thread detaches, which a key's `__hash__` or `__eq__` can cause mid-loop. A strong reference per fetch is what actually holds. ## Are there changes in behavior for the user? On free-threaded builds only: a call that finds a list item gone after the list's length was checked now raises `RuntimeError("list changed size during iteration")`, from `update()`, a `[key, value]` item and `[key, value] in md.items()` alike. A list that is simply shorter by the next iteration of `update()` still ends the update there, as before (#1379) and as in a plain `for` loop. ## Is it a substantial burden for the maintainers to support this? No. One helper in `hashtable.h`, used at three sites. ## Related issue number None. ## Checklist - [x] I think the code is well written - [x] Unit tests for the changes exist - [ ] Documentation reflects the changes -- N/A, no API change - [ ] If you provide code modification, please add yourself to `CONTRIBUTORS.txt` -- N/A, no such file - [x] Add a new news fragment into the `CHANGES/` folder --------- Co-authored-by: Junhyung Lee <[email protected]>
What do these changes do?
Two C-extension crashes caused by holding a raw pointer into a hash table across an operation that
reshapes it:
md_update_from_ht()cachedhtkeys_entries(other->keys)and then inserted intomd. Whenmdisother(d.extend(d), and the update/merge variants), an insert-triggered resize freed the verytable being iterated — a use-after-free.
extend(self)now reserves capacity up front (no resizeduring the loop) and snapshots the entry count;
update(self)/merge(self)are short-circuited asthe no-ops they are.
md_update_from_seq()cachedPyList_GET_SIZE(seq)once. A case-insensitive key's.lower()can runarbitrary Python that shrinks
seq, after which the stale size letPyList_GET_ITEMread past theend. The length is now re-read each iteration.
Both reproduce as SIGSEGV on ASan and debug builds with no threads involved.
Backend parity note (per AGENTS.md): this fixes the C extension only. The pure-Python backend has a
related but different bug — it hangs on
d.extend(d)(it iterates its own list while appending).I did not fix that here because it's a separate code path in
_multidict_py.py; happy to send it as afollow-up so the two backends match (both should double the contents).
Are there changes in behavior for the user?
Yes:
d.extend(d)now doubles the contents (was a crash);d.update(d)/d.merge(d)leave the dictunchanged (were a crash); building from a list whose key mutates that list no longer reads out of bounds.
Is it a substantial burden for the maintainers to support this?
No. The changes are confined to two internal bulk-update helpers in
_multilib/hashtable.h.Related issue number
The
extend/update/==sites were flagged as data races in the free-threading report #1321; theseparticular crashes are reachable single-threaded. Surfaced by the analysis report #1306.
Checklist
test_extend_update_merge_self_reference,test_update_from_list_mutated_by_key_lookup)CONTRIBUTORS.txtin this repoCHANGES/folder