Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions Lib/test/test_builtin.py
Original file line number Diff line number Diff line change
Expand Up @@ -1432,6 +1432,14 @@ def badfunc(x):
raise RuntimeError
self.assertRaises(RuntimeError, list, map(badfunc, range(5)))

it = []
for _ in range(100_000):
it = map(int, it)
with self.assertRaisesRegex(
RecursionError, r"Stack overflow .* while iterating"
):
list(it)

def test_map_pickle(self):
for proto in range(pickle.HIGHEST_PROTOCOL + 1):
m1 = map(map_char, "Is this the real life?")
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Deeply nested ``map()`` iterators now raise ``RecursionError`` instead of
causing a stack overflow.
14 changes: 9 additions & 5 deletions Python/bltinmodule.c
Original file line number Diff line number Diff line change
Expand Up @@ -1572,11 +1572,16 @@ map_next(PyObject *self)
{
mapobject *lz = _mapobject_CAST(self);
Py_ssize_t i;
Py_ssize_t nargs = 0;
PyObject *small_stack[_PY_FASTCALL_SMALL_STACK];
PyObject **stack;
PyObject **stack = NULL;
PyObject *result = NULL;
PyThreadState *tstate = _PyThreadState_GET();

if (_Py_EnterRecursiveCallTstate(tstate, " while calling map()")) {
return NULL;
}

const Py_ssize_t niters = PyTuple_GET_SIZE(lz->iters);
if (niters <= (Py_ssize_t)Py_ARRAY_LENGTH(small_stack)) {
stack = small_stack;
Expand All @@ -1585,11 +1590,9 @@ map_next(PyObject *self)
stack = PyMem_Malloc(niters * sizeof(stack[0]));
if (stack == NULL) {
_PyErr_NoMemory(tstate);
return NULL;
goto exit;
}
}

Py_ssize_t nargs = 0;
for (i = 0; i < niters; i++) {
PyObject *it = PyTuple_GET_ITEM(lz->iters, i);
PyObject *val = Py_TYPE(it)->tp_iternext(it);
Expand Down Expand Up @@ -1652,9 +1655,10 @@ map_next(PyObject *self)
for (i = 0; i < nargs; i++) {
Py_DECREF(stack[i]);
}
if (stack != small_stack) {
if (stack != NULL && stack != small_stack) {
PyMem_Free(stack);
}
_Py_LeaveRecursiveCallTstate(tstate);
return result;
}

Expand Down
Loading