atexitmodule.c 7.53 KB
Newer Older
1 2 3 4 5 6 7 8 9 10
/*
 *  atexit - allow programmer to define multiple exit functions to be executed
 *  upon normal program termination.
 *
 *   Translated from atexit.py by Collin Winter.
 +   Copyright 2007 Python Software Foundation.
 */

#include "Python.h"

11
/* Forward declaration (for atexit_cleanup) */
12
static PyObject *atexit_clear(PyObject*, PyObject*);
13
/* Forward declaration (for atexit_callfuncs) */
14 15 16
static void atexit_cleanup(PyObject*);
/* Forward declaration of module object */
static struct PyModuleDef atexitmodule;
17

18 19 20 21 22 23 24 25 26
/* ===================================================================== */
/* Callback machinery. */

typedef struct {
    PyObject *func;
    PyObject *args;
    PyObject *kwargs;
} atexit_callback;

27 28 29 30 31 32 33 34
typedef struct {
    atexit_callback **atexit_callbacks;
    int ncallbacks;
    int callback_len;
} atexitmodule_state;

#define GET_ATEXIT_STATE(mod) ((atexitmodule_state*)PyModule_GetState(mod))

35 36 37

/* Installed into pythonrun.c's atexit mechanism */

38
static void
39 40 41 42
atexit_callfuncs(void)
{
    PyObject *exc_type = NULL, *exc_value, *exc_tb, *r;
    atexit_callback *cb;
43 44
    PyObject *module;
    atexitmodule_state *modstate;
45
    int i;
46 47 48

    module = PyState_FindModule(&atexitmodule);
    if (module == NULL)
49
        return;
50 51 52 53 54 55 56
    modstate = GET_ATEXIT_STATE(module);

    if (modstate->ncallbacks == 0)
        return;


    for (i = modstate->ncallbacks - 1; i >= 0; i--)
57
    {
58
        cb = modstate->atexit_callbacks[i];
59 60 61 62 63 64
        if (cb == NULL)
            continue;

        r = PyObject_Call(cb->func, cb->args, cb->kwargs);
        Py_XDECREF(r);
        if (r == NULL) {
Neal Norwitz's avatar
Neal Norwitz committed
65 66
            /* Maintain the last exception, but don't leak if there are
               multiple exceptions. */
67 68
            if (exc_type) {
                Py_DECREF(exc_type);
Neal Norwitz's avatar
Neal Norwitz committed
69 70
                Py_XDECREF(exc_value);
                Py_XDECREF(exc_tb);    
71 72 73 74 75 76 77 78
            }
            PyErr_Fetch(&exc_type, &exc_value, &exc_tb);
            if (!PyErr_ExceptionMatches(PyExc_SystemExit)) {
                PySys_WriteStderr("Error in atexit._run_exitfuncs:\n");
                PyErr_Display(exc_type, exc_value, exc_tb);
            }
        }
    }
79 80

    atexit_cleanup(module);
81

82 83 84 85
    if (exc_type)
        PyErr_Restore(exc_type, exc_value, exc_tb);
}

86
static void
87
atexit_delete_cb(PyObject *self, int i)
88
{
89 90 91 92 93 94
    atexitmodule_state *modstate;
    atexit_callback *cb;

    modstate = GET_ATEXIT_STATE(self);
    cb = modstate->atexit_callbacks[i];
    modstate->atexit_callbacks[i] = NULL;
95 96 97
    Py_DECREF(cb->func);
    Py_DECREF(cb->args);
    Py_XDECREF(cb->kwargs);
98
    PyMem_Free(cb);
99 100
}

101
static void
102
atexit_cleanup(PyObject *self)
103
{
104
    PyObject *r = atexit_clear(self, NULL);
105 106 107
    Py_DECREF(r);
}

108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124
/* ===================================================================== */
/* Module methods. */

PyDoc_STRVAR(atexit_register__doc__,
"register(func, *args, **kwargs) -> func\n\
\n\
Register a function to be executed upon normal program termination\n\
\n\
    func - function to be called at exit\n\
    args - optional arguments to pass to func\n\
    kwargs - optional keyword arguments to pass to func\n\
\n\
    func is returned to facilitate usage as a decorator.");

static PyObject *
atexit_register(PyObject *self, PyObject *args, PyObject *kwargs)
{
125
    atexitmodule_state *modstate;
126 127
    atexit_callback *new_callback;
    PyObject *func = NULL;
128 129 130 131

    modstate = GET_ATEXIT_STATE(self);

    if (modstate->ncallbacks >= modstate->callback_len) {
132
        atexit_callback **r;
133 134 135
        modstate->callback_len += 16;
        r = (atexit_callback**)PyMem_Realloc(modstate->atexit_callbacks,
                                      sizeof(atexit_callback*) * modstate->callback_len);
136 137
        if (r == NULL)
            return PyErr_NoMemory();
138
        modstate->atexit_callbacks = r;
139
    }
140

141 142 143 144 145
    if (PyTuple_GET_SIZE(args) == 0) {
        PyErr_SetString(PyExc_TypeError,
                "register() takes at least 1 argument (0 given)");
        return NULL; 
    }
146

147 148 149 150 151 152
    func = PyTuple_GET_ITEM(args, 0);
    if (!PyCallable_Check(func)) {
        PyErr_SetString(PyExc_TypeError,
                "the first argument must be callable");
        return NULL;
    }
153

154 155 156 157 158 159 160 161 162 163 164 165 166
    new_callback = PyMem_Malloc(sizeof(atexit_callback));
    if (new_callback == NULL)
        return PyErr_NoMemory();   

    new_callback->args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
    if (new_callback->args == NULL) {
        PyMem_Free(new_callback);
        return NULL;
    }
    new_callback->func = func;
    new_callback->kwargs = kwargs;
    Py_INCREF(func);
    Py_XINCREF(kwargs);
167 168 169

    modstate->atexit_callbacks[modstate->ncallbacks++] = new_callback;

170 171 172 173
    Py_INCREF(func);
    return func;
}

Skip Montanaro's avatar
Skip Montanaro committed
174 175 176 177 178
PyDoc_STRVAR(atexit_run_exitfuncs__doc__,
"_run_exitfuncs() -> None\n\
\n\
Run all registered exit functions.");

179
static PyObject *
180
atexit_run_exitfuncs(PyObject *self, PyObject *unused)
181 182 183 184 185 186 187
{
    atexit_callfuncs();
    if (PyErr_Occurred())
        return NULL;
    Py_RETURN_NONE;
}

Skip Montanaro's avatar
Skip Montanaro committed
188 189 190 191 192
PyDoc_STRVAR(atexit_clear__doc__,
"_clear() -> None\n\
\n\
Clear the list of previously registered exit functions.");

193
static PyObject *
194
atexit_clear(PyObject *self, PyObject *unused)
195
{
196
    atexitmodule_state *modstate;
197 198
    atexit_callback *cb;
    int i;
199 200 201 202 203

    modstate = GET_ATEXIT_STATE(self);

    for (i = 0; i < modstate->ncallbacks; i++) {
        cb = modstate->atexit_callbacks[i];
204 205
        if (cb == NULL)
            continue;
206 207

        atexit_delete_cb(self, i);
208
    }
209
    modstate->ncallbacks = 0;
210 211 212
    Py_RETURN_NONE;
}

Skip Montanaro's avatar
Skip Montanaro committed
213 214 215 216 217 218 219 220
PyDoc_STRVAR(atexit_unregister__doc__,
"unregister(func) -> None\n\
\n\
Unregister a exit function which was previously registered using\n\
atexit.register\n\
\n\
    func - function to be unregistered");

221 222 223
static PyObject *
atexit_unregister(PyObject *self, PyObject *func)
{
224
    atexitmodule_state *modstate;
225 226
    atexit_callback *cb;
    int i, eq;
227 228 229 230

    modstate = GET_ATEXIT_STATE(self);

    for (i = 0; i < modstate->ncallbacks; i++)
231
    {
232
        cb = modstate->atexit_callbacks[i];
233 234
        if (cb == NULL)
            continue;
235

236 237 238 239
        eq = PyObject_RichCompareBool(cb->func, func, Py_EQ);
        if (eq < 0)
            return NULL;
        if (eq)
240
            atexit_delete_cb(self, i);
241 242 243 244 245 246 247 248
    }
    Py_RETURN_NONE;
}

static PyMethodDef atexit_methods[] = {
    {"register", (PyCFunction) atexit_register, METH_VARARGS|METH_KEYWORDS,
        atexit_register__doc__},
    {"_clear", (PyCFunction) atexit_clear, METH_NOARGS,
Skip Montanaro's avatar
Skip Montanaro committed
249
        atexit_clear__doc__},
250
    {"unregister", (PyCFunction) atexit_unregister, METH_O,
Skip Montanaro's avatar
Skip Montanaro committed
251
        atexit_unregister__doc__},
252
    {"_run_exitfuncs", (PyCFunction) atexit_run_exitfuncs, METH_NOARGS,
Skip Montanaro's avatar
Skip Montanaro committed
253
        atexit_run_exitfuncs__doc__},
254 255 256 257 258 259 260
    {NULL, NULL}        /* sentinel */
};

/* ===================================================================== */
/* Initialization function. */

PyDoc_STRVAR(atexit__doc__,
Skip Montanaro's avatar
Skip Montanaro committed
261
"allow programmer to define multiple exit functions to be executed\
262 263
upon normal program termination.\n\
\n\
Skip Montanaro's avatar
Skip Montanaro committed
264
Two public functions, register and unregister, are defined.\n\
265 266
");

267 268 269 270 271

static struct PyModuleDef atexitmodule = {
	PyModuleDef_HEAD_INIT,
	"atexit",
	atexit__doc__,
272
	sizeof(atexitmodule_state),
273 274 275 276 277 278 279
	atexit_methods,
	NULL,
	NULL,
	NULL,
	NULL
};

280
PyMODINIT_FUNC
281
PyInit_atexit(void)
282 283
{
    PyObject *m;
284
    atexitmodule_state *modstate;
285

286
    m = PyModule_Create(&atexitmodule);
287
    if (m == NULL)
288
        return NULL;
289 290 291 292 293 294 295 296 297

    modstate = GET_ATEXIT_STATE(m);
    modstate->callback_len = 32;
    modstate->ncallbacks = 0;
    modstate->atexit_callbacks = PyMem_New(atexit_callback*, 
                                           modstate->callback_len);
    if (modstate->atexit_callbacks == NULL)
        return NULL;

298
    _Py_PyAtExit(atexit_callfuncs);
299
    return m;
300
}