Skip to content

Commit 08d665d

Browse files
[3.13] gh-112127: Fix possible use-after-free in atexit.unregister() (GH-114092) (GH-142880)
(cherry picked from commit 2b466c4) Co-authored-by: Benjamin Johnson <[email protected]>
1 parent 5e1a9c8 commit 08d665d

File tree

4 files changed

+19
-1
lines changed

4 files changed

+19
-1
lines changed

Lib/test/_test_atexit.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -135,6 +135,19 @@ def func():
135135
finally:
136136
atexit.unregister(func)
137137

138+
def test_eq_unregister_clear(self):
139+
# Issue #112127: callback's __eq__ may call unregister or _clear
140+
class Evil:
141+
def __eq__(self, other):
142+
action(other)
143+
return NotImplemented
144+
145+
for action in atexit.unregister, lambda o: atexit._clear():
146+
with self.subTest(action=action):
147+
atexit.register(lambda: None)
148+
atexit.unregister(Evil())
149+
atexit._clear()
150+
138151

139152
if __name__ == "__main__":
140153
unittest.main()

Misc/ACKS

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -892,6 +892,7 @@ Jim Jewett
892892
Pedro Diaz Jimenez
893893
Orjan Johansen
894894
Fredrik Johansson
895+
Benjamin Johnson
895896
Gregory K. Johnson
896897
Kent Johnson
897898
Michael Johnson
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Fix possible use-after-free in :func:`atexit.unregister` when the callback
2+
is unregistered during comparison.

Modules/atexitmodule.c

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -287,7 +287,9 @@ atexit_unregister(PyObject *module, PyObject *func)
287287
continue;
288288
}
289289

290-
int eq = PyObject_RichCompareBool(cb->func, func, Py_EQ);
290+
PyObject *to_compare = Py_NewRef(cb->func);
291+
int eq = PyObject_RichCompareBool(to_compare, func, Py_EQ);
292+
Py_DECREF(to_compare);
291293
if (eq < 0) {
292294
return NULL;
293295
}

0 commit comments

Comments
 (0)