Skip to content

Fix use-after-free / out-of-bounds read from borrowed table pointers in bulk updates - #1379

Merged
asvetlov merged 4 commits into
aio-libs:masterfrom
devdanzin:fix/borrowed-entry-uaf
Sep 6, 2026
Merged

asvetlov merged 4 commits into
aio-libs:masterfrom
devdanzin:fix/borrowed-entry-uaf

Conversation

@devdanzin

Copy link
Copy Markdown
Contributor

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:

  1. md_update_from_ht() cached htkeys_entries(other->keys) and then inserted into md. When md is
    other (d.extend(d), and the update/merge variants), an insert-triggered resize freed the very
    table being iterated — a 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.
  2. 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 stale size let PyList_GET_ITEM read past the
    end. 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 a
follow-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 dict
unchanged (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; these
particular crashes are reachable single-threaded. Surfaced by the analysis report #1306.

Checklist

  • I think the code is well written
  • Unit tests for the changes exist (test_extend_update_merge_self_reference, test_update_from_list_mutated_by_key_lookup)
  • Documentation reflects the changes (no public API change)
  • N/A — no CONTRIBUTORS.txt in this repo
  • Add a new news fragment into the CHANGES/ folder

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.)
@pyba-chronographer pyba-chronographer Bot added the bot:chronographer:provided There is a change note present in this PR label Jul 24, 2026
@codspeed

codspeed Bot commented Jul 24, 2026 •

Copy link
Copy Markdown

Merging this PR will not alter performance

✅ 248 untouched benchmarks


Comparing devdanzin:fix/borrowed-entry-uaf (65aa71c) with master (b36706a)

Open in CodSpeed

@codecov

codecov Bot commented Jul 24, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 99.86%. Comparing base (b36706a) to head (65aa71c).

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           
Flag Coverage Δ
CI-GHA 99.86% <100.00%> (+<0.01%) ⬆️
pytest 99.86% <100.00%> (+<0.01%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@Vizonex Vizonex left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@devdanzin Sorry if I didn't see this sooner. This seems to be a pretty critical bug so I approve getting this PR Merged.

@asvetlov

asvetlov commented Sep 5, 2026

Copy link
Copy Markdown
Member

@copilot resolve the merge conflicts in this pull request

@greptile-apps

greptile-apps Bot commented Sep 5, 2026

Copy link
Copy Markdown
Contributor

Confidence Score: 5/5

Safe 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. multidict/_multilib/hashtable.h and its regression coverage in tests/test_multidict.py were exercised directly.

T-Rex T-Rex Logs

What T-Rex did

  • The pre-patch run against the parent a3810c4^ produced a segmentation fault in the C-extension harness.
  • After applying the patch HEAD, the harness completed all four mutation and error operations and resize/bulk scenarios without errors (exit 0).
  • A debug build with MULTIDICT_DEBUG_BUILD=1 (-O0 -g3 -UNDEBUG) was created and the harness ran again, followed by tests/test_update.py with two new regression tests, and all 31 focused tests passed.

View all artifacts

T-Rex Ran code and verified through T-Rex

Reviews (1): Last reviewed commit: "[pre-commit.ci] auto fixes from pre-comm..." | Re-trigger Greptile

@asvetlov
asvetlov merged commit 0a4d62d into aio-libs:master Sep 6, 2026
56 of 57 checks passed
@asvetlov

asvetlov commented Sep 6, 2026

Copy link
Copy Markdown
Member

Thanks, @devdanzin

rodrigobnogueira added a commit to rodrigobnogueira/multidict that referenced this pull request Sep 14, 2026
_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.
asvetlov pushed a commit that referenced this pull request Sep 20, 2026
## 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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bot:chronographer:provided There is a change note present in this PR

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants