python / python/cpython

`tp_doc` switch from `PyObject_Malloc` to `PyMem_Malloc` is not backwards compatible

Open
#118,909 2 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

interpreter-core topic-free-threading type-bug
Dominant language
Python
Stars
77.2k
Forks
35.9k
PR merge metrics
PR metrics pending

Description

Bug report

In https://github.com/python/cpython/pull/114574 we switched a number of non-PyObject allocations from PyObject_Malloc to PyMem_Malloc, including tp_doc on PyHeapTypeObjects.

Unfortunately, this isn't backwards compatible because C-API extensions may allocate tp_doc contents, which are then freed by CPython in type_dealloc. For example, pybind11 allocates memory for the docstring using PyObject_MALLOC. This leads to crashes when using pybind11 in debug builds of Python 3.13: the allocation uses PyObject_MALLOC, but the memory is freed using PyMem_Free.

We should consider reverting the change to tp_doc and figure out a way to allocate the doc in a way that's both safe (in the free-threaded build) and doesn't break backwards compatibility (in the default build).

Some example extensions:
Uses PyObject_Malloc
Uses strdup

We don't document the tp_doc behavior so some extensions use strdup, which works fine in release builds (and is thread-safe in the free-threaded build), but probably crashes in debug builds of CPython.

cc @erlend-aasland

Linked PRs
  • gh-156990

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the cited allocation change from PR 114574 and the free path in Objects/typeobject.c, then review linked PR gh-156990. Reproduce the debug-build extension case using a tp_doc allocated with PyObject_Malloc; done means allocation and freeing remain compatible for existing extensions in both supported build modes.

Written by the indexing model from the issue text.

Assessment

Tech stack
c, python
Domain
backend-api-design
Issue type
Bug
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
30/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.