1 /*
2 * atexit - allow programmer to define multiple exit functions to be executed
3 * upon normal program termination.
4 *
5 * Translated from atexit.py by Collin Winter.
6 + Copyright 2007 Python Software Foundation.
7 */
8
9 #include "Python.h"
10 #include "pycore_atexit.h" // export _Py_AtExit()
11 #include "pycore_initconfig.h" // _PyStatus_NO_MEMORY
12 #include "pycore_interp.h" // PyInterpreterState.atexit
13 #include "pycore_pystate.h" // _PyInterpreterState_GET
14
15 /* ===================================================================== */
16 /* Callback machinery. */
17
18 static inline struct atexit_state*
get_atexit_state(void)19 get_atexit_state(void)
20 {
21 PyInterpreterState *interp = _PyInterpreterState_GET();
22 return &interp->atexit;
23 }
24
25
26 int
PyUnstable_AtExit(PyInterpreterState * interp,atexit_datacallbackfunc func,void * data)27 PyUnstable_AtExit(PyInterpreterState *interp,
28 atexit_datacallbackfunc func, void *data)
29 {
30 assert(interp == _PyInterpreterState_GET());
31 atexit_callback *callback = PyMem_Malloc(sizeof(atexit_callback));
32 if (callback == NULL) {
33 PyErr_NoMemory();
34 return -1;
35 }
36 callback->func = func;
37 callback->data = data;
38 callback->next = NULL;
39
40 struct atexit_state *state = &interp->atexit;
41 if (state->ll_callbacks == NULL) {
42 state->ll_callbacks = callback;
43 state->last_ll_callback = callback;
44 }
45 else {
46 state->last_ll_callback->next = callback;
47 }
48 return 0;
49 }
50
51
52 static void
atexit_delete_cb(struct atexit_state * state,int i)53 atexit_delete_cb(struct atexit_state *state, int i)
54 {
55 atexit_py_callback *cb = state->callbacks[i];
56 state->callbacks[i] = NULL;
57
58 Py_DECREF(cb->func);
59 Py_DECREF(cb->args);
60 Py_XDECREF(cb->kwargs);
61 PyMem_Free(cb);
62 }
63
64
65 /* Clear all callbacks without calling them */
66 static void
atexit_cleanup(struct atexit_state * state)67 atexit_cleanup(struct atexit_state *state)
68 {
69 atexit_py_callback *cb;
70 for (int i = 0; i < state->ncallbacks; i++) {
71 cb = state->callbacks[i];
72 if (cb == NULL)
73 continue;
74
75 atexit_delete_cb(state, i);
76 }
77 state->ncallbacks = 0;
78 }
79
80
81 PyStatus
_PyAtExit_Init(PyInterpreterState * interp)82 _PyAtExit_Init(PyInterpreterState *interp)
83 {
84 struct atexit_state *state = &interp->atexit;
85 // _PyAtExit_Init() must only be called once
86 assert(state->callbacks == NULL);
87
88 state->callback_len = 32;
89 state->ncallbacks = 0;
90 state->callbacks = PyMem_New(atexit_py_callback*, state->callback_len);
91 if (state->callbacks == NULL) {
92 return _PyStatus_NO_MEMORY();
93 }
94 return _PyStatus_OK();
95 }
96
97
98 void
_PyAtExit_Fini(PyInterpreterState * interp)99 _PyAtExit_Fini(PyInterpreterState *interp)
100 {
101 struct atexit_state *state = &interp->atexit;
102 atexit_cleanup(state);
103 PyMem_Free(state->callbacks);
104 state->callbacks = NULL;
105
106 atexit_callback *next = state->ll_callbacks;
107 state->ll_callbacks = NULL;
108 while (next != NULL) {
109 atexit_callback *callback = next;
110 next = callback->next;
111 atexit_datacallbackfunc exitfunc = callback->func;
112 void *data = callback->data;
113 // It was allocated in _PyAtExit_AddCallback().
114 PyMem_Free(callback);
115 exitfunc(data);
116 }
117 }
118
119
120 static void
atexit_callfuncs(struct atexit_state * state)121 atexit_callfuncs(struct atexit_state *state)
122 {
123 assert(!PyErr_Occurred());
124
125 if (state->ncallbacks == 0) {
126 return;
127 }
128
129 for (int i = state->ncallbacks - 1; i >= 0; i--) {
130 atexit_py_callback *cb = state->callbacks[i];
131 if (cb == NULL) {
132 continue;
133 }
134
135 // bpo-46025: Increment the refcount of cb->func as the call itself may unregister it
136 PyObject* the_func = Py_NewRef(cb->func);
137 PyObject *res = PyObject_Call(cb->func, cb->args, cb->kwargs);
138 if (res == NULL) {
139 PyErr_FormatUnraisable(
140 "Exception ignored in atexit callback %R", the_func);
141 }
142 else {
143 Py_DECREF(res);
144 }
145 Py_DECREF(the_func);
146 }
147
148 atexit_cleanup(state);
149
150 assert(!PyErr_Occurred());
151 }
152
153
154 void
_PyAtExit_Call(PyInterpreterState * interp)155 _PyAtExit_Call(PyInterpreterState *interp)
156 {
157 struct atexit_state *state = &interp->atexit;
158 atexit_callfuncs(state);
159 }
160
161
162 /* ===================================================================== */
163 /* Module methods. */
164
165
166 PyDoc_STRVAR(atexit_register__doc__,
167 "register($module, func, /, *args, **kwargs)\n\
168 --\n\
169 \n\
170 Register a function to be executed upon normal program termination\n\
171 \n\
172 func - function to be called at exit\n\
173 args - optional arguments to pass to func\n\
174 kwargs - optional keyword arguments to pass to func\n\
175 \n\
176 func is returned to facilitate usage as a decorator.");
177
178 static PyObject *
atexit_register(PyObject * module,PyObject * args,PyObject * kwargs)179 atexit_register(PyObject *module, PyObject *args, PyObject *kwargs)
180 {
181 if (PyTuple_GET_SIZE(args) == 0) {
182 PyErr_SetString(PyExc_TypeError,
183 "register() takes at least 1 argument (0 given)");
184 return NULL;
185 }
186
187 PyObject *func = PyTuple_GET_ITEM(args, 0);
188 if (!PyCallable_Check(func)) {
189 PyErr_SetString(PyExc_TypeError,
190 "the first argument must be callable");
191 return NULL;
192 }
193
194 struct atexit_state *state = get_atexit_state();
195 if (state->ncallbacks >= state->callback_len) {
196 atexit_py_callback **r;
197 state->callback_len += 16;
198 size_t size = sizeof(atexit_py_callback*) * (size_t)state->callback_len;
199 r = (atexit_py_callback**)PyMem_Realloc(state->callbacks, size);
200 if (r == NULL) {
201 return PyErr_NoMemory();
202 }
203 state->callbacks = r;
204 }
205
206 atexit_py_callback *callback = PyMem_Malloc(sizeof(atexit_py_callback));
207 if (callback == NULL) {
208 return PyErr_NoMemory();
209 }
210
211 callback->args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
212 if (callback->args == NULL) {
213 PyMem_Free(callback);
214 return NULL;
215 }
216 callback->func = Py_NewRef(func);
217 callback->kwargs = Py_XNewRef(kwargs);
218
219 state->callbacks[state->ncallbacks++] = callback;
220
221 return Py_NewRef(func);
222 }
223
224 PyDoc_STRVAR(atexit_run_exitfuncs__doc__,
225 "_run_exitfuncs($module, /)\n\
226 --\n\
227 \n\
228 Run all registered exit functions.\n\
229 \n\
230 If a callback raises an exception, it is logged with sys.unraisablehook.");
231
232 static PyObject *
atexit_run_exitfuncs(PyObject * module,PyObject * unused)233 atexit_run_exitfuncs(PyObject *module, PyObject *unused)
234 {
235 struct atexit_state *state = get_atexit_state();
236 atexit_callfuncs(state);
237 Py_RETURN_NONE;
238 }
239
240 PyDoc_STRVAR(atexit_clear__doc__,
241 "_clear($module, /)\n\
242 --\n\
243 \n\
244 Clear the list of previously registered exit functions.");
245
246 static PyObject *
atexit_clear(PyObject * module,PyObject * unused)247 atexit_clear(PyObject *module, PyObject *unused)
248 {
249 atexit_cleanup(get_atexit_state());
250 Py_RETURN_NONE;
251 }
252
253 PyDoc_STRVAR(atexit_ncallbacks__doc__,
254 "_ncallbacks($module, /)\n\
255 --\n\
256 \n\
257 Return the number of registered exit functions.");
258
259 static PyObject *
atexit_ncallbacks(PyObject * module,PyObject * unused)260 atexit_ncallbacks(PyObject *module, PyObject *unused)
261 {
262 struct atexit_state *state = get_atexit_state();
263 return PyLong_FromSsize_t(state->ncallbacks);
264 }
265
266 PyDoc_STRVAR(atexit_unregister__doc__,
267 "unregister($module, func, /)\n\
268 --\n\
269 \n\
270 Unregister an exit function which was previously registered using\n\
271 atexit.register\n\
272 \n\
273 func - function to be unregistered");
274
275 static PyObject *
atexit_unregister(PyObject * module,PyObject * func)276 atexit_unregister(PyObject *module, PyObject *func)
277 {
278 struct atexit_state *state = get_atexit_state();
279 for (int i = 0; i < state->ncallbacks; i++)
280 {
281 atexit_py_callback *cb = state->callbacks[i];
282 if (cb == NULL) {
283 continue;
284 }
285
286 int eq = PyObject_RichCompareBool(cb->func, func, Py_EQ);
287 if (eq < 0) {
288 return NULL;
289 }
290 if (eq) {
291 atexit_delete_cb(state, i);
292 }
293 }
294 Py_RETURN_NONE;
295 }
296
297
298 static PyMethodDef atexit_methods[] = {
299 {"register", _PyCFunction_CAST(atexit_register), METH_VARARGS|METH_KEYWORDS,
300 atexit_register__doc__},
301 {"_clear", (PyCFunction) atexit_clear, METH_NOARGS,
302 atexit_clear__doc__},
303 {"unregister", (PyCFunction) atexit_unregister, METH_O,
304 atexit_unregister__doc__},
305 {"_run_exitfuncs", (PyCFunction) atexit_run_exitfuncs, METH_NOARGS,
306 atexit_run_exitfuncs__doc__},
307 {"_ncallbacks", (PyCFunction) atexit_ncallbacks, METH_NOARGS,
308 atexit_ncallbacks__doc__},
309 {NULL, NULL} /* sentinel */
310 };
311
312
313 /* ===================================================================== */
314 /* Initialization function. */
315
316 PyDoc_STRVAR(atexit__doc__,
317 "allow programmer to define multiple exit functions to be executed\n\
318 upon normal program termination.\n\
319 \n\
320 Two public functions, register and unregister, are defined.\n\
321 ");
322
323 static PyModuleDef_Slot atexitmodule_slots[] = {
324 {Py_mod_multiple_interpreters, Py_MOD_PER_INTERPRETER_GIL_SUPPORTED},
325 {Py_mod_gil, Py_MOD_GIL_NOT_USED},
326 {0, NULL}
327 };
328
329 static struct PyModuleDef atexitmodule = {
330 PyModuleDef_HEAD_INIT,
331 .m_name = "atexit",
332 .m_doc = atexit__doc__,
333 .m_size = 0,
334 .m_methods = atexit_methods,
335 .m_slots = atexitmodule_slots,
336 };
337
338 PyMODINIT_FUNC
PyInit_atexit(void)339 PyInit_atexit(void)
340 {
341 return PyModuleDef_Init(&atexitmodule);
342 }
343