Skip to content

Commit 8acb98a

Browse files
[3.14] gh-148973: fix segfault on mismatch between consts size and oparg in compiler (GH-148974) (#148980)
gh-148973: fix segfault on mismatch between consts size and oparg in compiler (GH-148974) (cherry picked from commit c650b51) Co-authored-by: Irit Katriel <1055913+iritkatriel@users.noreply.github.com>
1 parent 89f44ac commit 8acb98a

5 files changed

Lines changed: 95 additions & 6 deletions

File tree

Lib/test/test_peepholer.py

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import ast
12
import dis
23
import gc
34
from itertools import combinations, product
@@ -1119,6 +1120,53 @@ def trace(frame, event, arg):
11191120

11201121
class DirectCfgOptimizerTests(CfgOptimizationTestCase):
11211122

1123+
def test_optimize_cfg_const_index_out_of_range(self):
1124+
insts = [
1125+
('LOAD_CONST', 2, 0),
1126+
('RETURN_VALUE', None, 0),
1127+
]
1128+
seq = self.seq_from_insts(insts)
1129+
with self.assertRaisesRegex(ValueError, "out of range"):
1130+
_testinternalcapi.optimize_cfg(seq, [0, 1], 0)
1131+
1132+
def test_optimize_cfg_consts_must_be_list(self):
1133+
insts = [
1134+
('LOAD_CONST', 0, 0),
1135+
('RETURN_VALUE', None, 0),
1136+
]
1137+
seq = self.seq_from_insts(insts)
1138+
with self.assertRaisesRegex(TypeError, "consts must be a list"):
1139+
_testinternalcapi.optimize_cfg(seq, (0,), 0)
1140+
1141+
def test_compiler_codegen_metadata_consts_roundtrips_optimize_cfg(self):
1142+
tree = ast.parse("x = (1, 2)", mode="exec", optimize=1)
1143+
insts, meta = _testinternalcapi.compiler_codegen(tree, "<s>", 0)
1144+
consts = meta["consts"]
1145+
self.assertIsInstance(consts, list)
1146+
_testinternalcapi.optimize_cfg(insts, consts, 0)
1147+
1148+
def test_compiler_codegen_consts_include_none_required_for_implicit_return(self):
1149+
# Module "pass" only needs the const table entry for None once
1150+
# _PyCodegen_AddReturnAtEnd runs. If metadata["consts"] were taken
1151+
# before that, the list would not match LOAD_CONST opargs (here: 0
1152+
# for None), and optimize_cfg would read out of range.
1153+
tree = ast.parse("pass", mode="exec", optimize=1)
1154+
insts, meta = _testinternalcapi.compiler_codegen(tree, "<s>", 0)
1155+
consts = meta["consts"]
1156+
self.assertEqual(consts, [None])
1157+
1158+
load_const = opcode.opmap["LOAD_CONST"]
1159+
self.assertEqual(
1160+
[t[1] for t in insts.get_instructions() if t[0] == load_const],
1161+
[0],
1162+
)
1163+
1164+
# As if consts were snapshotted before AddReturnAtEnd: still LOAD_CONST 0, no row.
1165+
with self.assertRaisesRegex(ValueError, "out of range"):
1166+
_testinternalcapi.optimize_cfg(insts, [], 0)
1167+
1168+
_testinternalcapi.optimize_cfg(insts, list(consts), 0)
1169+
11221170
def cfg_optimization_test(self, insts, expected_insts,
11231171
consts=None, expected_consts=None,
11241172
nlocals=0):

Modules/_testinternalcapi.c

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -732,13 +732,17 @@ _testinternalcapi.compiler_codegen -> object
732732
compile_mode: int = 0
733733
734734
Apply compiler code generation to an AST.
735+
736+
Return (instruction_sequence, metadata). metadata maps "argcount",
737+
"posonlyargcount", "kwonlyargcount" to ints and "consts" to the list of
738+
constants in LOAD_CONST index order (for use with optimize_cfg).
735739
[clinic start generated code]*/
736740

737741
static PyObject *
738742
_testinternalcapi_compiler_codegen_impl(PyObject *module, PyObject *ast,
739743
PyObject *filename, int optimize,
740744
int compile_mode)
741-
/*[clinic end generated code: output=40a68f6e13951cc8 input=a0e00784f1517cd7]*/
745+
/*[clinic end generated code: output=40a68f6e13951cc8 input=e0c65e5c80efe30e]*/
742746
{
743747
PyCompilerFlags *flags = NULL;
744748
return _PyCompile_CodeGen(ast, filename, flags, optimize, compile_mode);
@@ -754,12 +758,15 @@ _testinternalcapi.optimize_cfg -> object
754758
nlocals: int
755759
756760
Apply compiler optimizations to an instruction list.
761+
762+
consts must be a list aligned with LOAD_CONST opargs (the "consts" entry
763+
from the metadata dict returned by compiler_codegen for the same unit).
757764
[clinic start generated code]*/
758765

759766
static PyObject *
760767
_testinternalcapi_optimize_cfg_impl(PyObject *module, PyObject *instructions,
761768
PyObject *consts, int nlocals)
762-
/*[clinic end generated code: output=57c53c3a3dfd1df0 input=6a96d1926d58d7e5]*/
769+
/*[clinic end generated code: output=57c53c3a3dfd1df0 input=905c3d935e063b27]*/
763770
{
764771
return _PyCompile_OptimizeCfg(instructions, consts, nlocals);
765772
}

Modules/clinic/_testinternalcapi.c.h

Lines changed: 10 additions & 3 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Python/compile.c

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1610,6 +1610,7 @@ _PyCompile_CodeGen(PyObject *ast, PyObject *filename, PyCompilerFlags *pflags,
16101610
{
16111611
PyObject *res = NULL;
16121612
PyObject *metadata = NULL;
1613+
PyObject *consts_list = NULL;
16131614

16141615
if (!PyAST_Check(ast)) {
16151616
PyErr_SetString(PyExc_TypeError, "expected an AST");
@@ -1664,12 +1665,23 @@ _PyCompile_CodeGen(PyObject *ast, PyObject *filename, PyCompilerFlags *pflags,
16641665
}
16651666

16661667
if (_PyInstructionSequence_ApplyLabelMap(_PyCompile_InstrSequence(c)) < 0) {
1667-
return NULL;
1668+
goto finally;
1669+
}
1670+
1671+
/* After AddReturnAtEnd: co_consts indices match the final instruction stream. */
1672+
consts_list = consts_dict_keys_inorder(umd->u_consts);
1673+
if (consts_list == NULL) {
1674+
goto finally;
1675+
}
1676+
if (PyDict_SetItemString(metadata, "consts", consts_list) < 0) {
1677+
goto finally;
16681678
}
1679+
16691680
/* Allocate a copy of the instruction sequence on the heap */
16701681
res = PyTuple_Pack(2, _PyCompile_InstrSequence(c), metadata);
16711682

16721683
finally:
1684+
Py_XDECREF(consts_list);
16731685
Py_XDECREF(metadata);
16741686
_PyCompile_ExitScope(c);
16751687
compiler_free(c);

Python/flowgraph.c

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1295,6 +1295,14 @@ get_const_value(int opcode, int oparg, PyObject *co_consts)
12951295
PyObject *constant = NULL;
12961296
assert(loads_const(opcode));
12971297
if (opcode == LOAD_CONST) {
1298+
assert(PyList_Check(co_consts));
1299+
Py_ssize_t n = PyList_GET_SIZE(co_consts);
1300+
if (oparg < 0 || oparg >= n) {
1301+
PyErr_Format(PyExc_ValueError,
1302+
"LOAD_CONST index %d is out of range for consts (len=%zd)",
1303+
oparg, n);
1304+
return NULL;
1305+
}
12981306
constant = PyList_GET_ITEM(co_consts, oparg);
12991307
}
13001308
if (opcode == LOAD_SMALL_INT) {
@@ -2153,6 +2161,9 @@ basicblock_optimize_load_const(PyObject *const_cache, basicblock *bb, PyObject *
21532161
cfg_instr *inst = &bb->b_instr[i];
21542162
if (inst->i_opcode == LOAD_CONST) {
21552163
PyObject *constant = get_const_value(inst->i_opcode, inst->i_oparg, consts);
2164+
if (constant == NULL) {
2165+
return ERROR;
2166+
}
21562167
int res = maybe_instr_make_load_smallint(inst, constant, consts, const_cache);
21572168
Py_DECREF(constant);
21582169
if (res < 0) {
@@ -4073,6 +4084,10 @@ _PyCompile_OptimizeCfg(PyObject *seq, PyObject *consts, int nlocals)
40734084
PyErr_SetString(PyExc_ValueError, "expected an instruction sequence");
40744085
return NULL;
40754086
}
4087+
if (!PyList_Check(consts)) {
4088+
PyErr_SetString(PyExc_TypeError, "consts must be a list");
4089+
return NULL;
4090+
}
40764091
PyObject *const_cache = PyDict_New();
40774092
if (const_cache == NULL) {
40784093
return NULL;

0 commit comments

Comments
 (0)