Skip to content

Commit 9c1ff40

Browse files
[3.15] gh-155247: Use raw string content for the extensions cache key (GH-155249) (GH-162686)
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. (cherry picked from commit 6a18ae4) Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
1 parent cfd15b2 commit 9c1ff40

4 files changed

Lines changed: 89 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
@@ -1286,6 +1286,37 @@ class Spec2:
12861286
origin = "a\x00b"
12871287
_imp.create_dynamic(Spec2())
12881288

1289+
@unittest.skipUnless(_testsinglephase is not None,
1290+
'requires _testsinglephase')
1291+
@unittest.skipUnless(os_helper.TESTFN_UNDECODABLE,
1292+
'requires undecodable file names')
1293+
def test_import_from_undecodable_path(self):
1294+
# gh-155247: the path of the extension module is not encodable
1295+
# in UTF-8.
1296+
origin = _testsinglephase.__file__
1297+
with os_helper.temp_dir() as tempdir:
1298+
subdir = os.path.join(os.fsencode(tempdir),
1299+
os_helper.TESTFN_UNDECODABLE)
1300+
try:
1301+
os.mkdir(subdir)
1302+
except OSError:
1303+
self.skipTest('undecodable paths are not supported')
1304+
path = os.path.join(subdir, os.fsencode(os.path.basename(origin)))
1305+
shutil.copyfile(origin, path)
1306+
# Import it in a subprocess: the extension module stays loaded,
1307+
# and on Windows its file cannot be removed.
1308+
script = textwrap.dedent(f"""
1309+
import importlib.util
1310+
path = {os.fsdecode(path)!a}
1311+
spec = importlib.util.spec_from_file_location(
1312+
'_testsinglephase', path)
1313+
module = importlib.util.module_from_spec(spec)
1314+
spec.loader.exec_module(module)
1315+
assert module.__name__ == '_testsinglephase', module.__name__
1316+
assert module.__file__ == path, module.__file__
1317+
""")
1318+
script_helper.assert_python_ok('-c', script)
1319+
12891320
def test_create_builtin(self):
12901321
class Spec:
12911322
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
@@ -1303,50 +1303,68 @@ del_extensions_cache_value(void *raw)
13031303
}
13041304
}
13051305

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

1317-
/* Make sure sep and the NULL byte won't cause an overflow. */
1318-
assert(SIZE_MAX - str1_len - str2_len > 2);
1319-
size_t size = str1_len + 1 + str2_len + 1;
1328+
assert(SIZE_MAX - sizeof(struct hashtable_key) - size1 > size2);
1329+
size_t size = sizeof(struct hashtable_key) + size1 + size2;
13201330

13211331
// XXX Use a buffer if it's a temp value (every case but "set").
1322-
char *key = PyMem_RawMalloc(size);
1332+
struct hashtable_key *key = PyMem_RawMalloc(size);
13231333
if (key == NULL) {
13241334
PyErr_NoMemory();
13251335
return NULL;
13261336
}
13271337

1328-
memcpy(key, str1_data, str1_len);
1329-
key[str1_len] = sep;
1330-
memcpy(key + str1_len + 1, str2_data, str2_len);
1331-
key[size - 1] = '\0';
1332-
assert(strlen(key) == size - 1);
1338+
/* Clear the padding: the key is hashed and compared as raw bytes. */
1339+
memset(key, 0, sizeof(struct hashtable_key));
1340+
key->size = size;
1341+
key->kind1 = (unsigned char)kind1;
1342+
key->kind2 = (unsigned char)kind2;
1343+
key->len1 = len1;
1344+
char *data = (char *)(key + 1);
1345+
memcpy(data, PyUnicode_DATA(str1), size1);
1346+
memcpy(data + size1, PyUnicode_DATA(str2), size2);
13331347
return key;
13341348
}
13351349

13361350
static Py_uhash_t
1337-
hashtable_hash_str(const void *key)
1351+
hashtable_hash_key(const void *key)
13381352
{
1339-
return Py_HashBuffer(key, strlen((const char *)key));
1353+
return Py_HashBuffer(key, ((const struct hashtable_key *)key)->size);
13401354
}
13411355

13421356
static int
1343-
hashtable_compare_str(const void *key1, const void *key2)
1357+
hashtable_compare_key(const void *key1, const void *key2)
13441358
{
1345-
return strcmp((const char *)key1, (const char *)key2) == 0;
1359+
size_t size = ((const struct hashtable_key *)key1)->size;
1360+
if (size != ((const struct hashtable_key *)key2)->size) {
1361+
return 0;
1362+
}
1363+
return memcmp(key1, key2, size) == 0;
13461364
}
13471365

13481366
static void
1349-
hashtable_destroy_str(void *ptr)
1367+
hashtable_destroy_key(void *ptr)
13501368
{
13511369
PyMem_RawFree(ptr);
13521370
}
@@ -1386,16 +1404,15 @@ _find_cached_def(PyModuleDef *def)
13861404
}
13871405
#endif
13881406

1389-
#define HTSEP ':'
13901407

13911408
static int
13921409
_extensions_cache_init(void)
13931410
{
13941411
_Py_hashtable_allocator_t alloc = {PyMem_RawMalloc, PyMem_RawFree};
13951412
EXTENSIONS.hashtable = _Py_hashtable_new_full(
1396-
hashtable_hash_str,
1397-
hashtable_compare_str,
1398-
hashtable_destroy_str, // key
1413+
hashtable_hash_key,
1414+
hashtable_compare_key,
1415+
hashtable_destroy_key, // key
13991416
del_extensions_cache_value, // value
14001417
&alloc
14011418
);
@@ -1413,7 +1430,7 @@ _extensions_cache_find_unlocked(PyObject *path, PyObject *name,
14131430
if (EXTENSIONS.hashtable == NULL) {
14141431
return NULL;
14151432
}
1416-
void *key = hashtable_key_from_2_strings(path, name, HTSEP);
1433+
void *key = hashtable_key_from_2_strings(path, name);
14171434
if (key == NULL) {
14181435
return NULL;
14191436
}
@@ -1423,7 +1440,7 @@ _extensions_cache_find_unlocked(PyObject *path, PyObject *name,
14231440
*p_key = key;
14241441
}
14251442
else {
1426-
hashtable_destroy_str(key);
1443+
hashtable_destroy_key(key);
14271444
}
14281445
return entry;
14291446
}
@@ -1561,7 +1578,7 @@ _extensions_cache_set(PyObject *path, PyObject *name,
15611578
finally_oldvalue:
15621579
extensions_lock_release();
15631580
if (key != NULL) {
1564-
hashtable_destroy_str(key);
1581+
hashtable_destroy_key(key);
15651582
}
15661583

15671584
return value;
@@ -1605,7 +1622,6 @@ _extensions_cache_clear_all(void)
16051622
EXTENSIONS.hashtable = NULL;
16061623
}
16071624

1608-
#undef HTSEP
16091625

16101626

16111627
static bool

‎Python/importdl.c‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
#include "pycore_moduleobject.h" // _PyModule_GetDefOrNull()
99
#include "pycore_pyerrors.h" // _PyErr_FormatFromCause()
1010
#include "pycore_runtime.h" // _Py_ID()
11+
#include "pycore_unicodeobject.h" // _PyUnicode_AsUTF8NoNUL()
1112

1213

1314
/***********************************/
@@ -117,7 +118,7 @@ _Py_ext_module_loader_info_init(struct _Py_ext_module_loader_info *p_info,
117118
return -1;
118119
}
119120

120-
info.newcontext = PyUnicode_AsUTF8(info.name);
121+
info.newcontext = _PyUnicode_AsUTF8NoNUL(info.name);
121122
if (info.newcontext == NULL) {
122123
_Py_ext_module_loader_info_clear(&info);
123124
return -1;
@@ -130,6 +131,12 @@ _Py_ext_module_loader_info_init(struct _Py_ext_module_loader_info *p_info,
130131
_Py_ext_module_loader_info_clear(&info);
131132
return -1;
132133
}
134+
if (PyUnicode_FindChar(filename, 0, 0,
135+
PyUnicode_GET_LENGTH(filename), 1) != -1) {
136+
PyErr_SetString(PyExc_ValueError, "embedded null character");
137+
_Py_ext_module_loader_info_clear(&info);
138+
return -1;
139+
}
133140
info.filename = Py_NewRef(filename);
134141

135142
#ifndef MS_WINDOWS

0 commit comments

Comments
 (0)