Skip to content

Commit 1f369ad

Browse files
authored
gh-98354: Add unicode check for 'name' attribute in _imp_create_builtin (GH-98412)
Fixes #98354
1 parent a8fe4bb commit 1f369ad

File tree

3 files changed

+43
-0
lines changed

3 files changed

+43
-0
lines changed

Lib/test/test_imp.py

+34
Original file line numberDiff line numberDiff line change
@@ -378,6 +378,40 @@ def test_find_and_load_checked_pyc(self):
378378
mod = imp.load_module('mymod', file, path, description)
379379
self.assertEqual(mod.x, 42)
380380

381+
def test_issue98354(self):
382+
# _imp.create_builtin should raise TypeError
383+
# if 'name' attribute of 'spec' argument is not a 'str' instance
384+
385+
create_builtin = support.get_attribute(_imp, "create_builtin")
386+
387+
class FakeSpec:
388+
def __init__(self, name):
389+
self.name = self
390+
spec = FakeSpec("time")
391+
with self.assertRaises(TypeError):
392+
create_builtin(spec)
393+
394+
class FakeSpec2:
395+
name = [1, 2, 3, 4]
396+
spec = FakeSpec2()
397+
with self.assertRaises(TypeError):
398+
create_builtin(spec)
399+
400+
import builtins
401+
class UnicodeSubclass(str):
402+
pass
403+
class GoodSpec:
404+
name = UnicodeSubclass("builtins")
405+
spec = GoodSpec()
406+
bltin = create_builtin(spec)
407+
self.assertEqual(bltin, builtins)
408+
409+
class UnicodeSubclassFakeSpec(str):
410+
def __init__(self, name):
411+
self.name = self
412+
spec = UnicodeSubclassFakeSpec("builtins")
413+
bltin = create_builtin(spec)
414+
self.assertEqual(bltin, builtins)
381415

382416
class ReloadTests(unittest.TestCase):
383417

Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Added unicode check for ``name`` attribute of ``spec`` argument passed in :func:`_imp.create_builtin` function.

Python/import.c

+8
Original file line numberDiff line numberDiff line change
@@ -1021,6 +1021,14 @@ _imp_create_builtin(PyObject *module, PyObject *spec)
10211021
return NULL;
10221022
}
10231023

1024+
if (!PyUnicode_Check(name)) {
1025+
PyErr_Format(PyExc_TypeError,
1026+
"name must be string, not %.200s",
1027+
Py_TYPE(name)->tp_name);
1028+
Py_DECREF(name);
1029+
return NULL;
1030+
}
1031+
10241032
PyObject *mod = create_builtin(tstate, name, spec);
10251033
Py_DECREF(name);
10261034
return mod;

0 commit comments

Comments
 (0)