Skip to content

Commit e160e5c

Browse files
Add input validation to _PyImport_LazyImportModuleLevelObject
1 parent 175ab31 commit e160e5c

3 files changed

Lines changed: 25 additions & 0 deletions

File tree

Lib/test/test_import/test_lazy_imports.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -393,6 +393,15 @@ def test_dunder_lazy_import_used(self):
393393
import test.test_import.data.lazy_imports.dunder_lazy_import_used
394394
self.assertIn("test.test_import.data.lazy_imports.basic2", sys.modules)
395395

396+
def test_dunder_lazy_import_non_string_name(self):
397+
"""__lazy_import__ should reject non-string name arguments."""
398+
with self.assertRaises(TypeError):
399+
__lazy_import__(b"")
400+
with self.assertRaises(TypeError):
401+
__lazy_import__(123)
402+
with self.assertRaises(TypeError):
403+
__lazy_import__(None)
404+
396405
def test_dunder_lazy_import_builtins(self):
397406
"""__lazy_import__ should use module's __builtins__ for __import__."""
398407
from test.test_import.data.lazy_imports import dunder_lazy_import_builtins
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Fix a crash when :func:`!__lazy_import__` is passed a non-string argument,
2+
by raising an :exc:`TypeError` instead.

Python/import.c

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4468,6 +4468,20 @@ _PyImport_LazyImportModuleLevelObject(PyThreadState *tstate,
44684468
PyObject *globals, PyObject *locals,
44694469
PyObject *fromlist, int level)
44704470
{
4471+
if (name == NULL) {
4472+
_PyErr_SetString(tstate, PyExc_ValueError, "Empty module name");
4473+
return NULL;
4474+
}
4475+
if (!PyUnicode_Check(name)) {
4476+
_PyErr_SetString(tstate, PyExc_TypeError,
4477+
"module name must be a string");
4478+
return NULL;
4479+
}
4480+
if (level < 0) {
4481+
_PyErr_SetString(tstate, PyExc_ValueError, "level must be >= 0");
4482+
return NULL;
4483+
}
4484+
44714485
PyObject *abs_name = get_abs_name(tstate, name, globals, level);
44724486
if (abs_name == NULL) {
44734487
return NULL;

0 commit comments

Comments
 (0)