Skip to content

Commit 2d358c6

Browse files
[3.14] gh-159739: Allocate thread-local state before constructing the object (GH-160166) (#160285)
If allocating a thread-local object’s internal dictionary or watchdog set fails, a subclass finalizer can run with that state missing. Accessing a thread-local attribute then dereferences the missing state and crashes; allocate both containers before creating the object. Backport to 3.15 and 3.14. (cherry picked from commit 4a61673) Co-authored-by: Jelle Zijlstra <jelle@openai.com>
1 parent ebc578f commit 2d358c6

2 files changed

Lines changed: 17 additions & 10 deletions

File tree

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Avoid a crash when a :class:`threading.local` subclass finalizer accesses
2+
attributes after construction fails.

‎Modules/_threadmodule.c‎

Lines changed: 15 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1470,10 +1470,25 @@ local_new(PyTypeObject *type, PyObject *args, PyObject *kw)
14701470
assert(module != NULL);
14711471
thread_module_state *state = get_thread_state(module);
14721472

1473+
// A subclass finalizer may access attributes if construction fails.
1474+
PyObject *localdicts = PyDict_New();
1475+
if (localdicts == NULL) {
1476+
return NULL;
1477+
}
1478+
PyObject *thread_watchdogs = PySet_New(NULL);
1479+
if (thread_watchdogs == NULL) {
1480+
Py_DECREF(localdicts);
1481+
return NULL;
1482+
}
1483+
14731484
localobject *self = (localobject *)type->tp_alloc(type, 0);
14741485
if (self == NULL) {
1486+
Py_DECREF(localdicts);
1487+
Py_DECREF(thread_watchdogs);
14751488
return NULL;
14761489
}
1490+
self->localdicts = localdicts;
1491+
self->thread_watchdogs = thread_watchdogs;
14771492

14781493
// gh-128691: Use deferred reference counting for thread-locals to avoid
14791494
// contention on the shared object.
@@ -1482,16 +1497,6 @@ local_new(PyTypeObject *type, PyObject *args, PyObject *kw)
14821497
self->args = Py_XNewRef(args);
14831498
self->kw = Py_XNewRef(kw);
14841499

1485-
self->localdicts = PyDict_New();
1486-
if (self->localdicts == NULL) {
1487-
goto err;
1488-
}
1489-
1490-
self->thread_watchdogs = PySet_New(NULL);
1491-
if (self->thread_watchdogs == NULL) {
1492-
goto err;
1493-
}
1494-
14951500
PyObject *localsdict = NULL;
14961501
PyObject *sentinel_wr = NULL;
14971502
if (create_localsdict(self, state, &localsdict, &sentinel_wr) < 0) {

0 commit comments

Comments
 (0)