Skip to content

Commit 07a2efe

Browse files
committed
Bound lazy-import chain walks with a recursion check
pythongh-159288: lazy import a.b.c as d nests one placeholder per name component, and lazy_import_path() and lazy_import_replay_from() walked that chain without a recursion check, so a very long dotted name could overflow the C stack. Raise RecursionError instead, as the rest of lazy import resolution does.
1 parent e84b606 commit 07a2efe

3 files changed

Lines changed: 24 additions & 0 deletions

File tree

‎Lib/test/test_lazy_import/__init__.py‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -316,6 +316,19 @@ def test_lazy_import_type_attribute_error_message(self):
316316
""")
317317
assert_python_ok("-c", code)
318318

319+
@support.run_with_limited_c_stack(depth=10_000, size=256 * 1024)
320+
def test_deeply_dotted_name(self):
321+
"""A long dotted name must not overflow the C stack."""
322+
m = types.SimpleNamespace()
323+
# Every lookup in m.m.m... succeeds, so resolve() only fails if the
324+
# C stack runs out.
325+
m.m = m
326+
ns = {"__builtins__": {"__lazy_import__": __lazy_import__,
327+
"__import__": lambda *args: m}}
328+
exec("lazy import " + ".".join(["m"] * 10_000) + " as x", ns)
329+
with contextlib.suppress(RecursionError):
330+
ns["x"].resolve()
331+
319332

320333
class SyntaxRestrictionTests(LazyImportTestCase):
321334
"""Tests for syntax restrictions on lazy imports."""
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Fix a crash when walking a very long chain of lazy import placeholders, as
2+
created by an aliased dotted import such as ``lazy import a.b.c as d``.
3+
:exc:`RecursionError` is now raised instead.

‎Objects/lazyimportobject.c‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -214,7 +214,11 @@ static PyObject *
214214
lazy_import_path(PyLazyImportObject *m)
215215
{
216216
if (PyLazyImport_CheckExact(m->lz_from)) {
217+
if (_Py_EnterRecursiveCall(" while getting the name of a lazy import")) {
218+
return NULL;
219+
}
217220
PyObject *base = lazy_import_path((PyLazyImportObject *)m->lz_from);
221+
_Py_LeaveRecursiveCall();
218222
if (base == NULL) {
219223
return NULL;
220224
}
@@ -287,8 +291,12 @@ lazy_import_replay_from(PyThreadState *tstate, PyObject *mod,
287291
if (!PyLazyImport_CheckExact(lz->lz_from)) {
288292
return Py_NewRef(mod);
289293
}
294+
if (_Py_EnterRecursiveCallTstate(tstate, " while resolving a lazy import")) {
295+
return NULL;
296+
}
290297
PyObject *from = lazy_import_replay_from(
291298
tstate, mod, (PyLazyImportObject *)lz->lz_from);
299+
_Py_LeaveRecursiveCallTstate(tstate);
292300
if (from == NULL) {
293301
return NULL;
294302
}

0 commit comments

Comments
 (0)