Skip to content

Errors during array module import result in double-DECREF #153210

Description

@stestagg

Crash report

What happened?

In DEBUG build:

import collections.abc

del collections.abc.MutableSequence
import array

or:

sys.setrecursionlimit(25)
import array

generates a double DECREF on the array ArrayType object due to poisoned module state:

Python/gc.c:96: gc_decref: Assertion "gc_get_refs(g) > 0" failed: refcount is too small
object type name: type
object repr     : <class 'array.array'>
Fatal Python error: _PyObject_AssertFailed: _PyObject_AssertFailed

Analysis

So, array_modexec creates the ArrayType and assigns it to array state:

CREATE_TYPE(m, state->ArrayType, &array_spec);

It then goes on to do some other setup tasks, and if any of these fail, it DECREF's state->ArrayType but leaves the type object on the state struct:

cpython/Modules/arraymodule.c

Lines 3409 to 3421 in 836b206

PyObject *mutablesequence = PyImport_ImportModuleAttrString(
"collections.abc", "MutableSequence");
if (!mutablesequence) {
Py_DECREF((PyObject *)state->ArrayType);
return -1;
}
PyObject *res = PyObject_CallMethod(mutablesequence, "register", "O",
(PyObject *)state->ArrayType);
Py_DECREF(mutablesequence);
if (!res) {
Py_DECREF((PyObject *)state->ArrayType);
return -1;
}

Returning -1 error code.

PyModule_ExecDef passes the -1 up the chain:

return -1;

which ends up with an exception in _bootstrap.py:
except:
try:
del sys.modules[spec.name]
except KeyError:
pass
raise

At this point, the array module refcount falls and it's cleaned up, and array_clear calls:

Py_CLEAR(state->ArrayType);

because the ArrayType pointer is still in the module state, this generates the double DECREF

CPython versions tested on:

CPython main branch

Operating systems tested on:

Linux

Output from running 'python -VV' on the command line:

Python 3.16.0a0 (heads/main-dirty:1034e73, Jul 6 2026, 11:11:46) [Clang 22.1.6 ]

Linked PRs

Metadata

Metadata

Assignees

Labels

extension-modulesC modules in the Modules dirtype-crashA hard crash of the interpreter, possibly with a core dump

Fields

No fields configured for issues without a type.

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions