Skip to content

Commit 6d558e1

Browse files
[3.14] gh-155247: Use raw string content for the extensions cache key (GH-155249) (GH-162687)
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 24c7bbf commit 6d558e1

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
@@ -1284,6 +1284,37 @@ class Spec2:
12841284
origin = "a\x00b"
12851285
_imp.create_dynamic(Spec2())
12861286

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

12881319
@skip_if_dont_write_bytecode
12891320
class FilePermissionTests(unittest.TestCase):
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
@@ -1245,50 +1245,68 @@ del_extensions_cache_value(void *raw)
12451245
}
12461246
}
12471247

1248+
/* The key of the extensions cache: the raw content of two strings.
1249+
1250+
The UTF-8 encoding is not used, because the strings can contain lone
1251+
surrogates, e.g. a file name undecodable in the filesystem encoding. */
1252+
struct hashtable_key {
1253+
size_t size; /* the total size of the key */
1254+
unsigned char kind1;
1255+
unsigned char kind2;
1256+
Py_ssize_t len1;
1257+
/* followed by the raw content of both strings */
1258+
};
1259+
12481260
static void *
1249-
hashtable_key_from_2_strings(PyObject *str1, PyObject *str2, const char sep)
1261+
hashtable_key_from_2_strings(PyObject *str1, PyObject *str2)
12501262
{
1251-
const char *str1_data = _PyUnicode_AsUTF8NoNUL(str1);
1252-
const char *str2_data = _PyUnicode_AsUTF8NoNUL(str2);
1253-
if (str1_data == NULL || str2_data == NULL) {
1254-
return NULL;
1255-
}
1256-
Py_ssize_t str1_len = strlen(str1_data);
1257-
Py_ssize_t str2_len = strlen(str2_data);
1263+
Py_ssize_t len1 = PyUnicode_GET_LENGTH(str1);
1264+
Py_ssize_t len2 = PyUnicode_GET_LENGTH(str2);
1265+
int kind1 = PyUnicode_KIND(str1);
1266+
int kind2 = PyUnicode_KIND(str2);
1267+
size_t size1 = (size_t)len1 * kind1;
1268+
size_t size2 = (size_t)len2 * kind2;
12581269

1259-
/* Make sure sep and the NULL byte won't cause an overflow. */
1260-
assert(SIZE_MAX - str1_len - str2_len > 2);
1261-
size_t size = str1_len + 1 + str2_len + 1;
1270+
assert(SIZE_MAX - sizeof(struct hashtable_key) - size1 > size2);
1271+
size_t size = sizeof(struct hashtable_key) + size1 + size2;
12621272

12631273
// XXX Use a buffer if it's a temp value (every case but "set").
1264-
char *key = PyMem_RawMalloc(size);
1274+
struct hashtable_key *key = PyMem_RawMalloc(size);
12651275
if (key == NULL) {
12661276
PyErr_NoMemory();
12671277
return NULL;
12681278
}
12691279

1270-
memcpy(key, str1_data, str1_len);
1271-
key[str1_len] = sep;
1272-
memcpy(key + str1_len + 1, str2_data, str2_len);
1273-
key[size - 1] = '\0';
1274-
assert(strlen(key) == size - 1);
1280+
/* Clear the padding: the key is hashed and compared as raw bytes. */
1281+
memset(key, 0, sizeof(struct hashtable_key));
1282+
key->size = size;
1283+
key->kind1 = (unsigned char)kind1;
1284+
key->kind2 = (unsigned char)kind2;
1285+
key->len1 = len1;
1286+
char *data = (char *)(key + 1);
1287+
memcpy(data, PyUnicode_DATA(str1), size1);
1288+
memcpy(data + size1, PyUnicode_DATA(str2), size2);
12751289
return key;
12761290
}
12771291

12781292
static Py_uhash_t
1279-
hashtable_hash_str(const void *key)
1293+
hashtable_hash_key(const void *key)
12801294
{
1281-
return Py_HashBuffer(key, strlen((const char *)key));
1295+
return Py_HashBuffer(key, ((const struct hashtable_key *)key)->size);
12821296
}
12831297

12841298
static int
1285-
hashtable_compare_str(const void *key1, const void *key2)
1299+
hashtable_compare_key(const void *key1, const void *key2)
12861300
{
1287-
return strcmp((const char *)key1, (const char *)key2) == 0;
1301+
size_t size = ((const struct hashtable_key *)key1)->size;
1302+
if (size != ((const struct hashtable_key *)key2)->size) {
1303+
return 0;
1304+
}
1305+
return memcmp(key1, key2, size) == 0;
12881306
}
12891307

12901308
static void
1291-
hashtable_destroy_str(void *ptr)
1309+
hashtable_destroy_key(void *ptr)
12921310
{
12931311
PyMem_RawFree(ptr);
12941312
}
@@ -1328,16 +1346,15 @@ _find_cached_def(PyModuleDef *def)
13281346
}
13291347
#endif
13301348

1331-
#define HTSEP ':'
13321349

13331350
static int
13341351
_extensions_cache_init(void)
13351352
{
13361353
_Py_hashtable_allocator_t alloc = {PyMem_RawMalloc, PyMem_RawFree};
13371354
EXTENSIONS.hashtable = _Py_hashtable_new_full(
1338-
hashtable_hash_str,
1339-
hashtable_compare_str,
1340-
hashtable_destroy_str, // key
1355+
hashtable_hash_key,
1356+
hashtable_compare_key,
1357+
hashtable_destroy_key, // key
13411358
del_extensions_cache_value, // value
13421359
&alloc
13431360
);
@@ -1355,7 +1372,7 @@ _extensions_cache_find_unlocked(PyObject *path, PyObject *name,
13551372
if (EXTENSIONS.hashtable == NULL) {
13561373
return NULL;
13571374
}
1358-
void *key = hashtable_key_from_2_strings(path, name, HTSEP);
1375+
void *key = hashtable_key_from_2_strings(path, name);
13591376
if (key == NULL) {
13601377
return NULL;
13611378
}
@@ -1365,7 +1382,7 @@ _extensions_cache_find_unlocked(PyObject *path, PyObject *name,
13651382
*p_key = key;
13661383
}
13671384
else {
1368-
hashtable_destroy_str(key);
1385+
hashtable_destroy_key(key);
13691386
}
13701387
return entry;
13711388
}
@@ -1503,7 +1520,7 @@ _extensions_cache_set(PyObject *path, PyObject *name,
15031520
finally_oldvalue:
15041521
extensions_lock_release();
15051522
if (key != NULL) {
1506-
hashtable_destroy_str(key);
1523+
hashtable_destroy_key(key);
15071524
}
15081525

15091526
return value;
@@ -1547,7 +1564,6 @@ _extensions_cache_clear_all(void)
15471564
EXTENSIONS.hashtable = NULL;
15481565
}
15491566

1550-
#undef HTSEP
15511567

15521568

15531569
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_GetDef()
99
#include "pycore_pyerrors.h" // _PyErr_FormatFromCause()
1010
#include "pycore_runtime.h" // _Py_ID()
11+
#include "pycore_unicodeobject.h" // _PyUnicode_AsUTF8NoNUL()
1112

1213

1314
/* ./configure sets HAVE_DYNAMIC_LOADING if dynamic loading of modules is
@@ -136,7 +137,7 @@ _Py_ext_module_loader_info_init(struct _Py_ext_module_loader_info *p_info,
136137
return -1;
137138
}
138139

139-
info.newcontext = PyUnicode_AsUTF8(info.name);
140+
info.newcontext = _PyUnicode_AsUTF8NoNUL(info.name);
140141
if (info.newcontext == NULL) {
141142
_Py_ext_module_loader_info_clear(&info);
142143
return -1;
@@ -149,6 +150,12 @@ _Py_ext_module_loader_info_init(struct _Py_ext_module_loader_info *p_info,
149150
_Py_ext_module_loader_info_clear(&info);
150151
return -1;
151152
}
153+
if (PyUnicode_FindChar(filename, 0, 0,
154+
PyUnicode_GET_LENGTH(filename), 1) != -1) {
155+
PyErr_SetString(PyExc_ValueError, "embedded null character");
156+
_Py_ext_module_loader_info_clear(&info);
157+
return -1;
158+
}
152159
info.filename = Py_NewRef(filename);
153160

154161
#ifndef MS_WINDOWS

0 commit comments

Comments
 (0)