[Python-Dev] refcounting vs PyModule_AddObject

Michael Hudson mwh at python.net
Wed Jun 15 16:17:02 CEST 2005

Armin Rigo <arigo at tunes.org> writes:

> 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.  

Hmm.  Point.  But then how doesn't this apply to things like 'del
thread._local'? (after my recent fix)

> What I don't get is how ProfilerError could fail to be NULL in the
> first 'if' above, but that's a different matter.

Well, could it fail to be NULL in the multiple interpreters case?
Though I'm not at all sure that reusing is wise in that case...

> While we're at strange refcounting problems, PyModule_AddObject() only
> decrefs its last argument if no error occurs.  This is probably wrong.

Quite probably :-/

> 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.

Oh yes.


  It's actually a corruption of "starling".  They used to be carried.
  Since they weighed a full pound (hence the name), they had to be
  carried by two starlings in tandem, with a line between them.
                 -- Alan J Rosenthal explains "Pounds Sterling" on asr

More information about the Python-Dev mailing list