atexitmodule.c 8.5 KB

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