gh-148973: fix segfault on mismatch between consts size and oparg in compiler (#148974)

This commit is contained in:
Irit Katriel 2026-04-25 10:47:41 +01:00 committed by GitHub
parent db0ee44b93
commit c650b51c32
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
5 changed files with 95 additions and 6 deletions

View file

@ -1658,6 +1658,7 @@ _PyCompile_CodeGen(PyObject *ast, PyObject *filename, PyCompilerFlags *pflags,
{
PyObject *res = NULL;
PyObject *metadata = NULL;
PyObject *consts_list = NULL;
if (!PyAST_Check(ast)) {
PyErr_SetString(PyExc_TypeError, "expected an AST");
@ -1712,12 +1713,23 @@ _PyCompile_CodeGen(PyObject *ast, PyObject *filename, PyCompilerFlags *pflags,
}
if (_PyInstructionSequence_ApplyLabelMap(_PyCompile_InstrSequence(c)) < 0) {
return NULL;
goto finally;
}
/* After AddReturnAtEnd: co_consts indices match the final instruction stream. */
consts_list = consts_dict_keys_inorder(umd->u_consts);
if (consts_list == NULL) {
goto finally;
}
if (PyDict_SetItemString(metadata, "consts", consts_list) < 0) {
goto finally;
}
/* Allocate a copy of the instruction sequence on the heap */
res = _PyTuple_FromPair((PyObject *)_PyCompile_InstrSequence(c), metadata);
finally:
Py_XDECREF(consts_list);
Py_XDECREF(metadata);
_PyCompile_ExitScope(c);
compiler_free(c);

View file

@ -1309,6 +1309,14 @@ get_const_value(int opcode, int oparg, PyObject *co_consts)
PyObject *constant = NULL;
assert(loads_const(opcode));
if (opcode == LOAD_CONST) {
assert(PyList_Check(co_consts));
Py_ssize_t n = PyList_GET_SIZE(co_consts);
if (oparg < 0 || oparg >= n) {
PyErr_Format(PyExc_ValueError,
"LOAD_CONST index %d is out of range for consts (len=%zd)",
oparg, n);
return NULL;
}
constant = PyList_GET_ITEM(co_consts, oparg);
}
if (opcode == LOAD_SMALL_INT) {
@ -2167,6 +2175,9 @@ basicblock_optimize_load_const(PyObject *const_cache, basicblock *bb, PyObject *
cfg_instr *inst = &bb->b_instr[i];
if (inst->i_opcode == LOAD_CONST) {
PyObject *constant = get_const_value(inst->i_opcode, inst->i_oparg, consts);
if (constant == NULL) {
return ERROR;
}
int res = maybe_instr_make_load_smallint(inst, constant, consts, const_cache);
Py_DECREF(constant);
if (res < 0) {
@ -4064,6 +4075,10 @@ _PyCompile_OptimizeCfg(PyObject *seq, PyObject *consts, int nlocals)
PyErr_SetString(PyExc_ValueError, "expected an instruction sequence");
return NULL;
}
if (!PyList_Check(consts)) {
PyErr_SetString(PyExc_TypeError, "consts must be a list");
return NULL;
}
PyObject *const_cache = PyDict_New();
if (const_cache == NULL) {
return NULL;