8000 gh-130019: Fix data race in _PyType_AllocNoTrack (gh-130058) · python/cpython@0559339 · GitHub
[go: up one dir, main page]

Skip to content

Commit 0559339

Browse files
authored
gh-130019: Fix data race in _PyType_AllocNoTrack (gh-130058)
The reference count fields, such as `ob_tid` and `ob_ref_shared`, may be accessed concurrently in the free threading build by a `_Py_TryXGetRef` or similar operation. The PyObject header fields will be initialized by `_PyObject_Init`, so only call `memset()` to zero-initialize the remainder of the allocation.
1 parent c357d69 commit 0559339

File tree

3 files changed

+9
-5
lines changed

3 files changed

+9
-5
lines changed

Objects/typeobject.c

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2251,7 +2251,9 @@ _PyType_AllocNoTrack(PyTypeObject *type, Py_ssize_t nitems)
22512251
if (PyType_IS_GC(type)) {
22522252
_PyObject_GC_Link(obj);
22532253
}
2254-
memset(obj, '\0', size);
2254+
// Zero out the object after the PyObject header. The header fields are
2255+
// initialized by _PyObject_Init[Var]().
2256+
memset((char *)obj + sizeof(PyObject), 0, size - sizeof(PyObject));
22552257

22562258
if (type->tp_itemsize == 0) {
22572259
_PyObject_Init(obj, type);

Python/gc.c

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2310,11 +2310,12 @@ PyObject *
23102310
PyUnstable_Object_GC_NewWithExtraData(PyTypeObject *tp, size_t extra_size)
23112311
{
23122312
size_t presize = _PyType_PreHeaderSize(tp);
2313-
PyObject *op = gc_alloc(tp, _PyObject_SIZE(tp) + extra_size, presize);
2313+
size_t size = _PyObject_SIZE(tp) + extra_size;
2314+
PyObject *op = gc_alloc(tp, size, presize);
23142315
if (op == NULL) {
23152316
return NULL;
23162317
}
2317-
memset(op, 0, _PyObject_SIZE(tp) + extra_size);
2318+
memset((char *)op + sizeof(PyObject), 0, size - sizeof(PyObject));
23182319
_PyObject_Init(op, tp);
23192320
return op;
23202321
}

Python/gc_free_threading.c

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2595,11 +2595,12 @@ PyObject *
25952595
PyUnstable_Object_GC_NewWithExtraData(PyTypeObject *tp, size_t extra_size)
25962596
{
25972597
size_t presize = _PyType_PreHeaderSize(tp);
2598-
PyObject *op = gc_alloc(tp, _PyObject_SIZE(tp) + extra_size, presize);
2598+
size_t size = _PyObject_SIZE(tp) + extra_size;
2599+
PyObject *op = gc_alloc(tp, size, presize);
25992600
if (op == NULL) {
26002601
return NULL;
26012602
}
2602-
memset(op, 0, _PyObject_SIZE(tp) + extra_size);
2603+
memset((char *)op + sizeof(PyObject), 0, size - sizeof(PyObject));
26032604
_PyObject_Init(op, tp);
26042605
return op;
26052606
}

0 commit comments

Comments
 (0)
0