Skip to content

Commit 6a18ae4

Browse files
gh-155247: Use raw string content for the extensions cache key (GH-155249)
The key of the extensions cache was built with _PyUnicode_AsUTF8NoNUL(), so importing an extension module failed with UnicodeEncodeError if its path contained characters unencodable in UTF-8, e.g. surrogate escapes of an undecodable file name. The raw content of the strings is now used. The rejection of embedded null characters, which was a side effect of the UTF-8 encoding, is now explicit in the extension module loader. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
1 parent cc0e59f commit 6a18ae4

4 files changed

Lines changed: 88 additions & 31 deletions

File tree

‎Lib/test/test_import/__init__.py‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1293,6 +1293,37 @@ class Spec:
12931293
name = "abc"
12941294
_imp.create_dynamic(Spec())
12951295

1296+
@unittest.skipUnless(_testsinglephase is not None,
1297+
'requires _testsinglephase')
1298+
@unittest.skipUnless(os_helper.TESTFN_UNDECODABLE,
1299+
'requires undecodable file names')
1300+
def test_import_from_undecodable_path(self):
1301+
# gh-155247: the path of the extension module is not encodable
1302+
# in UTF-8.
1303+
origin = _testsinglephase.__file__
1304+
with os_helper.temp_dir() as tempdir:
1305+
subdir = os.path.join(os.fsencode(tempdir),
1306+
os_helper.TESTFN_UNDECODABLE)
1307+
try:
1308+
os.mkdir(subdir)
1309+
except OSError:
1310+
self.skipTest('undecodable paths are not supported')
1311+
path = os.path.join(subdir, os.fsencode(os.path.basename(origin)))
1312+
shutil.copyfile(origin, path)
1313+
# Import it in a subprocess: the extension module stays loaded,
1314+
# and on Windows its file cannot be removed.
1315+
script = textwrap.dedent(f"""
1316+
import importlib.util
1317+
path = {os.fsdecode(path)!a}
1318+
spec = importlib.util.spec_from_file_location(
1319+
'_testsinglephase', path)
1320+
module = importlib.util.module_from_spec(spec)
1321+
spec.loader.exec_module(module)
1322+
assert module.__name__ == '_testsinglephase', module.__name__
1323+
assert module.__file__ == path, module.__file__
1324+
""")
1325+
script_helper.assert_python_ok('-c', script)
1326+
12961327
def test_create_builtin(self):
12971328
class Spec:
12981329
pass
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
Fix importing an extension module whose path contains characters unencodable
2+
in UTF-8, e.g. undecodable bytes of a file name. Previously it failed with
3+
:exc:`UnicodeEncodeError`, which made it impossible to build or run Python in
4+
a directory with such name.

‎Python/import.c‎

Lines changed: 46 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -1300,50 +1300,68 @@ del_extensions_cache_value(void *raw)
13001300
}
13011301
}
13021302

1303+
/* The key of the extensions cache: the raw content of two strings.
1304+
1305+
The UTF-8 encoding is not used, because the strings can contain lone
1306+
surrogates, e.g. a file name undecodable in the filesystem encoding. */
1307+
struct hashtable_key {
1308+
size_t size; /* the total size of the key */
1309+
unsigned char kind1;
1310+
unsigned char kind2;
1311+
Py_ssize_t len1;
1312+
/* followed by the raw content of both strings */
1313+
};
1314+
13031315
static void *
1304-
hashtable_key_from_2_strings(PyObject *str1, PyObject *str2, const char sep)
1316+
hashtable_key_from_2_strings(PyObject *str1, PyObject *str2)
13051317
{
1306-
const char *str1_data = _PyUnicode_AsUTF8NoNUL(str1);
1307-
const char *str2_data = _PyUnicode_AsUTF8NoNUL(str2);
1308-
if (str1_data == NULL || str2_data == NULL) {
1309-
return NULL;
1310-
}
1311-
Py_ssize_t str1_len = strlen(str1_data);
1312-
Py_ssize_t str2_len = strlen(str2_data);
1318+
Py_ssize_t len1 = PyUnicode_GET_LENGTH(str1);
1319+
Py_ssize_t len2 = PyUnicode_GET_LENGTH(str2);
1320+
int kind1 = PyUnicode_KIND(str1);
1321+
int kind2 = PyUnicode_KIND(str2);
1322+
size_t size1 = (size_t)len1 * kind1;
1323+
size_t size2 = (size_t)len2 * kind2;
13131324

1314-
/* Make sure sep and the NULL byte won't cause an overflow. */
1315-
assert(SIZE_MAX - str1_len - str2_len > 2);
1316-
size_t size = str1_len + 1 + str2_len + 1;
1325+
assert(SIZE_MAX - sizeof(struct hashtable_key) - size1 > size2);
1326+
size_t size = sizeof(struct hashtable_key) + size1 + size2;
13171327

13181328
// XXX Use a buffer if it's a temp value (every case but "set").
1319-
char *key = PyMem_RawMalloc(size);
1329+
struct hashtable_key *key = PyMem_RawMalloc(size);
13201330
if (key == NULL) {
13211331
PyErr_NoMemory();
13221332
return NULL;
13231333
}
13241334

1325-
memcpy(key, str1_data, str1_len);
1326-
key[str1_len] = sep;
1327-
memcpy(key + str1_len + 1, str2_data, str2_len);
1328-
key[size - 1] = '\0';
1329-
assert(strlen(key) == size - 1);
1335+
/* Clear the padding: the key is hashed and compared as raw bytes. */
1336+
memset(key, 0, sizeof(struct hashtable_key));
1337+
key->size = size;
1338+
key->kind1 = (unsigned char)kind1;
1339+
key->kind2 = (unsigned char)kind2;
1340+
key->len1 = len1;
1341+
char *data = (char *)(key + 1);
1342+
memcpy(data, PyUnicode_DATA(str1), size1);
1343+
memcpy(data + size1, PyUnicode_DATA(str2), size2);
13301344
return key;
13311345
}
13321346

13331347
static Py_uhash_t
1334-
hashtable_hash_str(const void *key)
1348+
hashtable_hash_key(const void *key)
13351349
{
1336-
return Py_HashBuffer(key, strlen((const char *)key));
1350+
return Py_HashBuffer(key, ((const struct hashtable_key *)key)->size);
13371351
}
13381352

13391353
static int
1340-
hashtable_compare_str(const void *key1, const void *key2)
1354+
hashtable_compare_key(const void *key1, const void *key2)
13411355
{
1342-
return strcmp((const char *)key1, (const char *)key2) == 0;
1356+
size_t size = ((const struct hashtable_key *)key1)->size;
1357+
if (size != ((const struct hashtable_key *)key2)->size) {
1358+
return 0;
1359+
}
1360+
return memcmp(key1, key2, size) == 0;
13431361
}
13441362

13451363
static void
1346-
hashtable_destroy_str(void *ptr)
1364+
hashtable_destroy_key(void *ptr)
13471365
{
13481366
PyMem_RawFree(ptr);
13491367
}
@@ -1383,16 +1401,15 @@ _find_cached_def(PyModuleDef *def)
13831401
}
13841402
#endif
13851403

1386-
#define HTSEP ':'
13871404

13881405
static int
13891406
_extensions_cache_init(void)
13901407
{
13911408
_Py_hashtable_allocator_t alloc = {PyMem_RawMalloc, PyMem_RawFree};
13921409
EXTENSIONS.hashtable = _Py_hashtable_new_full(
1393-
hashtable_hash_str,
1394-
hashtable_compare_str,
1395-
hashtable_destroy_str, // key
1410+
hashtable_hash_key,
1411+
hashtable_compare_key,
1412+
hashtable_destroy_key, // key
13961413
del_extensions_cache_value, // value
13971414
&alloc
13981415
);
@@ -1410,7 +1427,7 @@ _extensions_cache_find_unlocked(PyObject *path, PyObject *name,
14101427
if (EXTENSIONS.hashtable == NULL) {
14111428
return NULL;
14121429
}
1413-
void *key = hashtable_key_from_2_strings(path, name, HTSEP);
1430+
void *key = hashtable_key_from_2_strings(path, name);
14141431
if (key == NULL) {
14151432
return NULL;
14161433
}
@@ -1420,7 +1437,7 @@ _extensions_cache_find_unlocked(PyObject *path, PyObject *name,
14201437
*p_key = key;
14211438
}
14221439
else {
1423-
hashtable_destroy_str(key);
1440+
hashtable_destroy_key(key);
14241441
}
14251442
return entry;
14261443
}
@@ -1558,7 +1575,7 @@ _extensions_cache_set(PyObject *path, PyObject *name,
15581575
finally_oldvalue:
15591576
extensions_lock_release();
15601577
if (key != NULL) {
1561-
hashtable_destroy_str(key);
1578+
hashtable_destroy_key(key);
15621579
}
15631580

15641581
return value;
@@ -1602,7 +1619,6 @@ _extensions_cache_clear_all(void)
16021619
EXTENSIONS.hashtable = NULL;
16031620
}
16041621

1605-
#undef HTSEP
16061622

16071623

16081624
static bool

‎Python/importdl.c‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
#include "pycore_pyerrors.h" // _PyErr_FormatFromCause()
1010
#include "pycore_runtime.h" // _Py_ID()
1111
#include "pycore_global_objects.h" // _Py_SINGLETON()
12+
#include "pycore_unicodeobject.h" // _PyUnicode_AsUTF8NoNUL()
1213

1314

1415
/***********************************/
@@ -134,7 +135,7 @@ _Py_ext_module_loader_info_init(struct _Py_ext_module_loader_info *p_info,
134135
goto error;
135136
}
136137

137-
info.newcontext = PyUnicode_AsUTF8(info.name);
138+
info.newcontext = _PyUnicode_AsUTF8NoNUL(info.name);
138139
if (info.newcontext == NULL) {
139140
goto error;
140141
}
@@ -151,6 +152,11 @@ _Py_ext_module_loader_info_init(struct _Py_ext_module_loader_info *p_info,
151152
"module filename must be a string");
152153
goto error;
153154
}
155+
if (PyUnicode_FindChar(info.filename, 0, 0,
156+
PyUnicode_GET_LENGTH(info.filename), 1) != -1) {
157+
PyErr_SetString(PyExc_ValueError, "embedded null character");
158+
goto error;
159+
}
154160

155161
#ifndef MS_WINDOWS
156162
info.filename_encoded = PyUnicode_EncodeFSDefault(info.filename);

0 commit comments

Comments
 (0)