Skip to content

Hold refs across lower() when copying keys from another source - #1582

Merged
asvetlov merged 2 commits into
aio-libs:masterfrom
asvetlov:fix-bulk-update-lower-uaf
Sep 25, 2026
Merged

asvetlov merged 2 commits into
aio-libs:masterfrom
asvetlov:fix-bulk-update-lower-uaf

Conversation

@asvetlov

@asvetlov asvetlov commented Sep 25, 2026 •

Copy link
Copy Markdown
Member

What do these changes do?

A str subclass key's lower() runs Python code that can clear or grow the source while a CIMultiDict copies keys out of it. On the cross-type path, md_update_from_ht() kept pointers into the source's entry table across that call, and md_update_from_dict() held only a borrowed reference to the value, so both read freed memory.

The cross-type loop now holds its own references to the key and value while computing the identity, then reloads the entry table and clamps the entry count. The dict loop increfs the value alongside the key and passes that reference on to md_add_with_hash_steal_refs() instead of taking a second one. The same-type path runs no Python code and is unchanged. The pure-Python implementation is not affected.

Are there changes in behavior for the user?

No, apart from the crash being gone.

Is it a substantial burden for the maintainers to support this?

No.

Related issue number

Fixes #1581

Checklist

  • I think the code is well written
  • Unit tests for the changes exist
  • Documentation reflects the changes (N/A)
  • If you provide code modification, please add yourself to CONTRIBUTORS.txt (N/A)
  • Add a new news fragment into the CHANGES/ folder
  • make doc-spelling passes and any new technical words are added to docs/spelling_wordlist.txt

Drafted with Claude Code (Claude Opus 5.5); reviewed by @asvetlov.

Agent run details (optional, for reviewers)

Tests:

  • ASan GIL 3.14.7 (MULTIDICT_DEBUG_BUILD=1 MULTIDICT_ASAN_BUILD=1 MULTIDICT_NO_FREELIST=1, PYTHONMALLOC=malloc, -k "not test_leak and not test_freed_blocks_are_reused"): 2733 passed, 167 skipped. Without the fix, all 8 test_key_lower_mutates_source c- cases report heap-use-after-free (md_update_from_ht at bulk_update.h:364 for multidict sources; md_update_from_dict / md_add_for_upd for dict sources), and test_value_finalizer_mutates_source[c-multidict] does on the first commit alone (bulk_update.h:352).
  • 3.14.7t C extension: 2732 passed, 180 skipped.
  • 3.14.7t pure Python (MULTIDICT_NO_EXTENSIONS=1 --no-c-extensions): 1298 passed, 11 skipped.
  • 3.10.17 C extension: 2745 passed, 167 skipped.
  • make doc-spelling and pre-commit on the changed files: pass.

Callgrind, release build, PYTHONHASHSEED=0, 16 string keys, instructions per operation (2000-iteration run minus an empty run):

operation GIL before GIL after FT before FT after
MultiDict(md) (same type) 2624 2624 3494 3494
CIMultiDict(ci) (same type) 2752 2752 3553 3555
CIMultiDict(md) 13001 13445 (+3.4%) 14923 15705 (+5.2%)
MultiDict(ci) 20832 21372 (+2.6%) 24023 24660 (+2.7%)
ci.update(md) 15517 15986 (+3.0%) 16742 17545 (+4.8%)
MultiDict(dict) 4682 4698 6391 6375
CIMultiDict(dict) 13320 13336 14851 14802
md.extend(dict) 6028 6044 7933 7921
ci.extend(dict) 14666 14683 16395 16347
md.update(dict) 6637 6812 (+2.6%) 8292 8468 (+2.1%)
ci.update(dict) 16303 16472 (+1.0%) 17662 17807 (+0.8%)

The cross-type cost is one extra incref/decref pair per entry (about 28 Ir per entry on GIL, 49 on free-threaded). The extend and constructor dict paths are flat because the value reference is now moved into the table instead of taken twice.

A str subclass key's lower() runs Python code that can clear or grow
the source.  md_update_from_ht() kept pointers into the source's entry
table across it on the cross-type path, and md_update_from_dict() held
only a borrowed reference to the value, so both read freed memory.

Fixes aio-libs#1581
@asvetlov
asvetlov marked this pull request as ready for review September 25, 2026 12:03
@asvetlov
asvetlov requested a review from webknjaz as a code owner September 25, 2026 12:03
@codspeed

codspeed Bot commented Sep 25, 2026 •

Copy link
Copy Markdown

Merging this PR will not alter performance

✅ 310 untouched benchmarks


Comparing asvetlov:fix-bulk-update-lower-uaf (41104c5) with master (3e0105a)

Open in CodSpeed

@codecov

codecov Bot commented Sep 25, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (e5e4391) to head (41104c5).
⚠️ Report is 1 commits behind head on master.

Additional details and impacted files
@@            Coverage Diff            @@
##            master     #1582   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           41        41           
  Lines         7689      7739   +50     
  Branches       643       648    +5     
=========================================
+ Hits          7689      7739   +50     
Flag Coverage Δ
CI-GHA 100.00% <100.00%> (ø)
pytest 100.00% <100.00%> (ø)

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.

@greptile-apps

greptile-apps Bot commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerConfidence Score: 5/5

[Critical risk] Fixes use-after-free bug in C extension memory handling.

No outstanding findings block merging.

Reviews (2) · Last reviewed commit: "Reload the source table after dropping t..."

Comment thread multidict/_multilib/bulk_update.h Resolved
@greptile-apps

This comment has been minimized.

merge() drops the key and value for a key the target already has, so
releasing them can run a finalizer that replaces the source's table.
Reload the entry pointer after the releases instead of after lower().
@pyba-chronographer pyba-chronographer Bot added the bot:chronographer:provided There is a change note present in this PR label Sep 25, 2026
@asvetlov
asvetlov merged commit cd03110 into aio-libs:master Sep 25, 2026
62 checks passed
@asvetlov
asvetlov deleted the fix-bulk-update-lower-uaf branch September 25, 2026 13:58
asvetlov added a commit that referenced this pull request Sep 26, 2026
#1598)

<!-- Thank you for your contribution! -->

## What do these changes do?

Since #1582, `md_update_from_dict()` takes its own reference to every
key and value, because a `str` subclass key's `lower()` can run Python
code that clears the source dict. That can only happen when the target
is a `CIMultiDict` and the key is a `str` subclass other than `istr`.
Every other key goes through code that runs no Python, so the dict keeps
both alive and the borrowed references are enough. The loop now takes
references only in that one case; `extend()` still takes them, since it
moves them into the table.

The `lower()` call itself, together with the `TypeError` for a non-`str`
key, moves out of `_ci_str_to_identity()` into a `COLD` helper. The
ASCII exact-`str` path stays inline, and every `CIMultiDict` lookup gets
a little cheaper.

Instructions per operation (Callgrind,
`benchmarks/callgrind_driver.py`):

| operation | build | `MultiDict` | `CIMultiDict` |
|---|---|---:|---:|
| `update` | GIL | 39,230 -> 36,613 (-6.7%) | 45,154 -> 42,661 (-5.5%) |
| `update` | free-threaded | 49,260 -> 44,748 (-9.2%) | 55,060 -> 50,640
(-8.0%) |
| `getitem_hit` | GIL | 148 (flat) | 209 -> 201 (-3.8%) |
| `contains_hit` | GIL | 134 (flat) | 196 -> 188 (-4.1%) |
| `ctor_items` | GIL | 46,832 (flat) | 59,324 -> 57,733 (-2.7%) |

The pure-Python implementation holds references by construction and
needs no change.

## Are there changes in behavior for the user?

No, only faster `update()`, `merge()` and `CIMultiDict` key lookups.

## Is it a substantial burden for the maintainers to support this?

No. The condition is one line, next to the comment explaining it.

## Related issue number

N/A

## Checklist

- [x] I think the code is well written
- [x] Unit tests for the changes exist (the existing
`test_key_lower_mutates_source` cases from #1582 cover the path that
still takes references)
- [x] Documentation reflects the changes (N/A, internal only)
- [ ] If you provide code modification, please add yourself to
`CONTRIBUTORS.txt` (N/A)
- [x] Add a new news fragment into the `CHANGES/` folder
- [x] `make doc-spelling` passes and any new technical words are added
to `docs/spelling_wordlist.txt`

Drafted with Claude Code (Claude Opus 5.5); pending review by @asvetlov
before leaving draft.

<details>
<summary>Agent run details (optional, for reviewers)</summary>

Tests:
- C extension, 3.14.7: 2790 passed, 170 skipped
- C extension, 3.14.7t: 2777 passed, 183 skipped
- C extension, 3.10.17: 2790 passed, 170 skipped
- Pure Python, 3.14.7 (`MULTIDICT_NO_EXTENSIONS=1 --no-c-extensions`):
1320 passed, 17 skipped
- ASan + UBSan, 3.14.7 (`MULTIDICT_DEBUG_BUILD=1 MULTIDICT_ASAN_BUILD=1
MULTIDICT_NO_FREELIST=1`, `PYTHONMALLOC=malloc`, `-k "not test_leak and
not test_freed_blocks_are_reused"`): 2778 passed, 170 skipped

Lint: pre-commit hooks pass. `make doc-spelling` passes.

Callgrind rows not listed moved less than 1%. Wall clock was measured
only together with two sibling PRs (the version counter and the inlining
annotations): an interleaved pyperf A/B, 3 rounds, pinned P-cores,
`dict` as a flat control, gave `update` -5.4% GIL and -17.2%
free-threaded on `MultiDict`, and -4.8% / -22.1% on `CIMultiDict`.

Not tested: musl, macOS, Windows and Android builds.
</details>
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.

Use after free when a str subclass key's lower() mutates the source of a CIMultiDict update

1 participant