[Python-Dev] refcounting vs PyModule_AddObject
Armin Rigo
arigo at tunes.org
Wed Jun 15 15:51:10 CEST 2005
Hi Michael,
On Wed, Jun 15, 2005 at 01:35:35PM +0100, Michael Hudson wrote:
> if (ProfilerError == NULL)
> ProfilerError = PyErr_NewException("hotshot.ProfilerError",
> NULL, NULL);
> if (ProfilerError != NULL) {
> Py_INCREF(ProfilerError);
> PyModule_AddObject(module, "ProfilerError", ProfilerError);
> }
I think the Py_INCREF is needed here. The ProfilerError is a global
variable that needs the extra reference. Otherwise, a malicious user
could do "del _hotshot.ProfilerError" and have it garbage-collected
under the feet of _hotshot.c which still uses it. What I don't get is
how ProfilerError could fail to be NULL in the first 'if' above, but
that's a different matter.
While we're at strange refcounting problems, PyModule_AddObject() only
decrefs its last argument if no error occurs. This is probably wrong.
In general I've found that the C modules' init code is fragile. This
might be due to the idea that it runs only once anyway, and global
C-module objects are immortal anyway, so sloppiness sneaks in. But for
example, the following is common:
m = Py_InitModule3("xxx", NULL, module_doc);
Py_INCREF(&Xxx_Type);
PyModule_AddObject(m, "Xxx", (PyObject *)&Xxx_Type);
This generates a segfault if Py_InitModule3() returns NULL (however rare
that situation is).
A bientot,
Armin
More information about the Python-Dev
mailing list