Skip to content

Fix segfault creating view objects - #1163

Merged
bdraco merged 5 commits into
masterfrom
segfault_protected_view_objects
May 19, 2025
Merged

bdraco merged 5 commits into
masterfrom
segfault_protected_view_objects

Conversation

@bdraco

@bdraco bdraco commented May 16, 2025

Copy link
Copy Markdown
Member

fixes #1161

@pyba-chronographer pyba-chronographer Bot added the bot:chronographer:provided There is a change note present in this PR label May 16, 2025
@bdraco
bdraco marked this pull request as ready for review May 16, 2025 20:11
@bdraco
bdraco requested review from asvetlov and webknjaz as code owners May 16, 2025 20:11
@codspeed

codspeed Bot commented May 16, 2025 •

Copy link
Copy Markdown

CodSpeed Performance Report

Merging #1163 will not alter performance

Comparing segfault_protected_view_objects (01ef6ab) with master (fea968f)

Summary

✅ 244 untouched benchmarks

@codecov

codecov Bot commented May 16, 2025 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 98.62%. Comparing base (fea968f) to head (01ef6ab).
⚠️ Report is 72 commits behind head on master.

Additional details and impacted files
@@           Coverage Diff           @@
##           master    #1163   +/-   ##
=======================================
  Coverage   98.62%   98.62%           
=======================================
  Files          27       27           
  Lines        3558     3566    +8     
  Branches      561      561           
=======================================
+ Hits         3509     3517    +8     
  Misses         17       17           
  Partials       32       32           
Flag Coverage Δ
CI-GHA 98.62% <100.00%> (+<0.01%) ⬆️
MyPy 83.18% <62.50%> (-0.05%) ⬇️
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 Sentry.
📢 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.

@bdraco bdraco closed this May 18, 2025
@bdraco bdraco reopened this May 18, 2025
@bdraco
bdraco merged commit b5a24b7 into master May 19, 2025
@bdraco
bdraco deleted the segfault_protected_view_objects branch May 19, 2025 13:07
asvetlov added a commit that referenced this pull request Sep 5, 2026
<!-- Thank you for your contribution! -->

## What do these changes do?

`type(iter(md.keys())).__new__(t)` built an uninitialised iterator whose
internal `md` pointer was NULL;
calling `next()` on it dereferenced NULL and segfaulted. The view types
were given a forbidden `tp_new`
for exactly this reason in #1163; the iterator types share the hole.
This adds the same forbidden
`tp_new` to the items/keys/values iterator specs. This is a
C-extension-only concern (the pure-Python
iterators are ordinary Python objects); no pure-Python change is needed.

## Are there changes in behavior for the user?

Yes: directly constructing an internal iterator type now raises
`TypeError: cannot create '..._keysiter' instances directly` instead of
crashing. Normal iteration is
unaffected.

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

No. It mirrors the existing view-type fix (#1163).

## Related issue number

Direct analog of #1163 (view types); same crash class as #1161. Surfaced
by the analysis report #1306.

## Checklist

- [x] I think the code is well written
- [x] Unit tests for the changes exist
(`test_iter_direct_instantiation_segfault`)
- [x] Documentation reflects the changes (no public API change)
- [ ] N/A — no `CONTRIBUTORS.txt` in this repo
- [x] Add a new news fragment into the `CHANGES/` folder

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: Andrew Svetlov <[email protected]>
asvetlov added a commit that referenced this pull request Sep 5, 2026
…`__new__` (#1378)

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

## What do these changes do?

`MultiDict.__new__(MultiDict)` (or a subclass that skips
`super().__init__()`) left `md->state` and
`md->keys` as NULL, and the first method call dereferenced them and
segfaulted. The container now has a
`tp_new` that initialises the object to a valid empty state (`state`
set, `keys` = the shared
`&empty_htkeys` sentinel), with `is_ci` derived from the type so
`CIMultiDict` stays case-insensitive.
The sentinel is not heap-allocated, so the `md_init()` that `tp_init`
runs on normal construction does
not leak.

Scope: this fixes the container types. The proxy types
(`MultiDictProxy`/`CIMultiDictProxy`) have the
same latent issue (`self->md` left NULL by `__new__`) but need a
different fix (moving argument
validation into `tp_new`); I'll send that as a follow-up rather than
fold a construction-protocol change
in here. The pure-Python backend raises `AttributeError` for the same
`__new__`-without-`__init__` case
(no crash); aligning it to also yield a valid empty mapping can be a
small follow-up if you'd prefer
exact parity.

## Are there changes in behavior for the user?

Yes (mild): `MultiDict.__new__(MultiDict)` and subclasses that skip
`super().__init__()` now behave as a
valid empty mapping instead of crashing.

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

No. One `tp_new` function shared by both container types.

## Related issue number

Generalises the point fixes #1159 (`setdefault`) and #1161/#1163 (view
types) to the containers.
Surfaced by the analysis report #1306.

## Checklist

- [x] I think the code is well written
- [x] Unit tests for the changes exist
(`test_new_without_init_is_valid_empty`, both container types + a
subclass)
- [x] Documentation reflects the changes (no public API change)
- [ ] N/A — no `CONTRIBUTORS.txt` in this repo
- [x] Add a new news fragment into the `CHANGES/` folder

---------

Co-authored-by: Andrew Svetlov <[email protected]>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
asvetlov added a commit that referenced this pull request Sep 25, 2026
…TANTIATION (#1595)

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

## What do these changes do?

The C view types (`_ItemsView`, `_KeysView`, `_ValuesView`) and the
three iterator types blocked direct instantiation with hand-written
`tp_new` slots that just raised `TypeError`. CPython has provided
`Py_TPFLAGS_DISALLOW_INSTANTIATION` for exactly this since 3.10, the
project minimum, so the slots and their helpers are replaced by the
flag. The dead `PY_VERSION_HEX >= 3.10` guards around
`Py_TPFLAGS_IMMUTABLETYPE` in the same specs are dropped too.

The types were already final (no `Py_TPFLAGS_BASETYPE`); a new test
locks that in. The pure-Python backend has no equivalent types, so it is
unaffected.

## Are there changes in behavior for the user?

Only the error text: `cannot create '..._KeysView' instances directly`
became CPython's `cannot create '..._KeysView' instances`. On 3.10,
`T.__new__(T)` is refused by `object.__new__`'s safety check with
`object.__new__(T) is not safe` instead.

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

No, it removes code.

## Related issue number

Follow-up to #1163 and #1377.

## Checklist

- [x] I think the code is well written
- [x] Unit tests for the changes exist
- [x] Documentation reflects the changes (N/A, private types)
- [ ] 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); reviewed by @asvetlov.

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

Tests, rebased on 27fec2d:
- C extension, CPython 3.10.17: 2771 passed, 170 skipped
- C extension, CPython 3.14.7t: 2758 passed, 183 skipped
- Pure Python (`MULTIDICT_NO_EXTENSIONS=1 --no-c-extensions`), 3.10.17,
clean tree copy: 1301 passed, 17 skipped

Lint: pre-commit on the changed files passed. `make doc-spelling`
passed.
Not verified locally: PyPy (whether cpyext honours
`Py_TPFLAGS_DISALLOW_INSTANTIATION`).
</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.

Segfault on repr of instances of _ItemsView, _KeysView or _ValuesView

1 participant