(root)/
Python-3.12.0/
Modules/
atexitmodule.c
       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"
      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*
      19  get_atexit_state(void)
      20  {
      21      PyInterpreterState *interp = _PyInterpreterState_GET();
      22      return &interp->atexit;
      23  }
      24  
      25  
      26  int
      27  _Py_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
      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
      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
      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
      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
     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_WriteUnraisableMsg("in atexit callback", the_func);
     140          }
     141          else {
     142              Py_DECREF(res);
     143          }
     144          Py_DECREF(the_func);
     145      }
     146  
     147      atexit_cleanup(state);
     148  
     149      assert(!PyErr_Occurred());
     150  }
     151  
     152  
     153  void
     154  _PyAtExit_Call(PyInterpreterState *interp)
     155  {
     156      struct atexit_state *state = &interp->atexit;
     157      atexit_callfuncs(state);
     158  }
     159  
     160  
     161  /* ===================================================================== */
     162  /* Module methods. */
     163  
     164  
     165  PyDoc_STRVAR(atexit_register__doc__,
     166  "register(func, *args, **kwargs) -> func\n\
     167  \n\
     168  Register a function to be executed upon normal program termination\n\
     169  \n\
     170      func - function to be called at exit\n\
     171      args - optional arguments to pass to func\n\
     172      kwargs - optional keyword arguments to pass to func\n\
     173  \n\
     174      func is returned to facilitate usage as a decorator.");
     175  
     176  static PyObject *
     177  atexit_register(PyObject *module, PyObject *args, PyObject *kwargs)
     178  {
     179      if (PyTuple_GET_SIZE(args) == 0) {
     180          PyErr_SetString(PyExc_TypeError,
     181                  "register() takes at least 1 argument (0 given)");
     182          return NULL;
     183      }
     184  
     185      PyObject *func = PyTuple_GET_ITEM(args, 0);
     186      if (!PyCallable_Check(func)) {
     187          PyErr_SetString(PyExc_TypeError,
     188                  "the first argument must be callable");
     189          return NULL;
     190      }
     191  
     192      struct atexit_state *state = get_atexit_state();
     193      if (state->ncallbacks >= state->callback_len) {
     194          atexit_py_callback **r;
     195          state->callback_len += 16;
     196          size_t size = sizeof(atexit_py_callback*) * (size_t)state->callback_len;
     197          r = (atexit_py_callback**)PyMem_Realloc(state->callbacks, size);
     198          if (r == NULL) {
     199              return PyErr_NoMemory();
     200          }
     201          state->callbacks = r;
     202      }
     203  
     204      atexit_py_callback *callback = PyMem_Malloc(sizeof(atexit_py_callback));
     205      if (callback == NULL) {
     206          return PyErr_NoMemory();
     207      }
     208  
     209      callback->args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
     210      if (callback->args == NULL) {
     211          PyMem_Free(callback);
     212          return NULL;
     213      }
     214      callback->func = Py_NewRef(func);
     215      callback->kwargs = Py_XNewRef(kwargs);
     216  
     217      state->callbacks[state->ncallbacks++] = callback;
     218  
     219      return Py_NewRef(func);
     220  }
     221  
     222  PyDoc_STRVAR(atexit_run_exitfuncs__doc__,
     223  "_run_exitfuncs() -> None\n\
     224  \n\
     225  Run all registered exit functions.\n\
     226  \n\
     227  If a callback raises an exception, it is logged with sys.unraisablehook.");
     228  
     229  static PyObject *
     230  atexit_run_exitfuncs(PyObject *module, PyObject *unused)
     231  {
     232      struct atexit_state *state = get_atexit_state();
     233      atexit_callfuncs(state);
     234      Py_RETURN_NONE;
     235  }
     236  
     237  PyDoc_STRVAR(atexit_clear__doc__,
     238  "_clear() -> None\n\
     239  \n\
     240  Clear the list of previously registered exit functions.");
     241  
     242  static PyObject *
     243  atexit_clear(PyObject *module, PyObject *unused)
     244  {
     245      atexit_cleanup(get_atexit_state());
     246      Py_RETURN_NONE;
     247  }
     248  
     249  PyDoc_STRVAR(atexit_ncallbacks__doc__,
     250  "_ncallbacks() -> int\n\
     251  \n\
     252  Return the number of registered exit functions.");
     253  
     254  static PyObject *
     255  atexit_ncallbacks(PyObject *module, PyObject *unused)
     256  {
     257      struct atexit_state *state = get_atexit_state();
     258      return PyLong_FromSsize_t(state->ncallbacks);
     259  }
     260  
     261  PyDoc_STRVAR(atexit_unregister__doc__,
     262  "unregister(func) -> None\n\
     263  \n\
     264  Unregister an exit function which was previously registered using\n\
     265  atexit.register\n\
     266  \n\
     267      func - function to be unregistered");
     268  
     269  static PyObject *
     270  atexit_unregister(PyObject *module, PyObject *func)
     271  {
     272      struct atexit_state *state = get_atexit_state();
     273      for (int i = 0; i < state->ncallbacks; i++)
     274      {
     275          atexit_py_callback *cb = state->callbacks[i];
     276          if (cb == NULL) {
     277              continue;
     278          }
     279  
     280          int eq = PyObject_RichCompareBool(cb->func, func, Py_EQ);
     281          if (eq < 0) {
     282              return NULL;
     283          }
     284          if (eq) {
     285              atexit_delete_cb(state, i);
     286          }
     287      }
     288      Py_RETURN_NONE;
     289  }
     290  
     291  
     292  static PyMethodDef atexit_methods[] = {
     293      {"register", _PyCFunction_CAST(atexit_register), METH_VARARGS|METH_KEYWORDS,
     294          atexit_register__doc__},
     295      {"_clear", (PyCFunction) atexit_clear, METH_NOARGS,
     296          atexit_clear__doc__},
     297      {"unregister", (PyCFunction) atexit_unregister, METH_O,
     298          atexit_unregister__doc__},
     299      {"_run_exitfuncs", (PyCFunction) atexit_run_exitfuncs, METH_NOARGS,
     300          atexit_run_exitfuncs__doc__},
     301      {"_ncallbacks", (PyCFunction) atexit_ncallbacks, METH_NOARGS,
     302          atexit_ncallbacks__doc__},
     303      {NULL, NULL}        /* sentinel */
     304  };
     305  
     306  
     307  /* ===================================================================== */
     308  /* Initialization function. */
     309  
     310  PyDoc_STRVAR(atexit__doc__,
     311  "allow programmer to define multiple exit functions to be executed\n\
     312  upon normal program termination.\n\
     313  \n\
     314  Two public functions, register and unregister, are defined.\n\
     315  ");
     316  
     317  static PyModuleDef_Slot atexitmodule_slots[] = {
     318      {Py_mod_multiple_interpreters, Py_MOD_PER_INTERPRETER_GIL_SUPPORTED},
     319      {0, NULL}
     320  };
     321  
     322  static struct PyModuleDef atexitmodule = {
     323      PyModuleDef_HEAD_INIT,
     324      .m_name = "atexit",
     325      .m_doc = atexit__doc__,
     326      .m_size = 0,
     327      .m_methods = atexit_methods,
     328      .m_slots = atexitmodule_slots,
     329  };
     330  
     331  PyMODINIT_FUNC
     332  PyInit_atexit(void)
     333  {
     334      return PyModuleDef_Init(&atexitmodule);
     335  }