mirror of
https://github.com/python/cpython.git
synced 2025-12-09 10:37:17 +00:00
gh-130851: Don't crash when deduping unusual code constants (#130853)
The bytecode compiler only generates a few different types of constants, like str, int, tuple, slices, etc. Users can construct code objects with various unusual constants, including ones that are not hashable or not even constant. The free threaded build previously crashed with a fatal error when confronted with these constants. Instead, treat distinct objects of otherwise unhandled types as not equal for the purposes of deduplication.
This commit is contained in:
parent
78d50e91ff
commit
2905690a91
3 changed files with 32 additions and 6 deletions
|
|
@ -2587,6 +2587,7 @@ intern_one_constant(PyObject *op)
|
|||
_Py_hashtable_entry_t *entry = _Py_hashtable_get_entry(consts, op);
|
||||
if (entry == NULL) {
|
||||
if (_Py_hashtable_set(consts, op, op) != 0) {
|
||||
PyErr_NoMemory();
|
||||
return NULL;
|
||||
}
|
||||
|
||||
|
|
@ -2608,7 +2609,8 @@ intern_one_constant(PyObject *op)
|
|||
}
|
||||
|
||||
static int
|
||||
compare_constants(const void *key1, const void *key2) {
|
||||
compare_constants(const void *key1, const void *key2)
|
||||
{
|
||||
PyObject *op1 = (PyObject *)key1;
|
||||
PyObject *op2 = (PyObject *)key2;
|
||||
if (op1 == op2) {
|
||||
|
|
@ -2668,8 +2670,8 @@ compare_constants(const void *key1, const void *key2) {
|
|||
Py_complex c2 = ((PyComplexObject *)op2)->cval;
|
||||
return memcmp(&c1, &c2, sizeof(Py_complex)) == 0;
|
||||
}
|
||||
_Py_FatalErrorFormat("unexpected type in compare_constants: %s",
|
||||
Py_TYPE(op1)->tp_name);
|
||||
// gh-130851: Treat instances of unexpected types as distinct if they are
|
||||
// not the same object.
|
||||
return 0;
|
||||
}
|
||||
|
||||
|
|
@ -2689,9 +2691,13 @@ hash_const(const void *key)
|
|||
}
|
||||
Py_hash_t h = PyObject_Hash(op);
|
||||
if (h == -1) {
|
||||
// This should never happen: all the constants we support have
|
||||
// infallible hash functions.
|
||||
Py_FatalError("code: hash failed");
|
||||
// gh-130851: Other than slice objects, every constant that the
|
||||
// bytecode compiler generates is hashable. However, users can
|
||||
// provide their own constants, when constructing code objects via
|
||||
// types.CodeType(). If the user-provided constant is unhashable, we
|
||||
// use the memory address of the object as a fallback hash value.
|
||||
PyErr_Clear();
|
||||
return (Py_uhash_t)(uintptr_t)key;
|
||||
}
|
||||
return (Py_uhash_t)h;
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue