Skip to content

Commit c650b51

Browse files
authored
gh-148973: fix segfault on mismatch between consts size and oparg in compiler (#148974)
1 parent db0ee44 commit c650b51

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
@@ -1131,6 +1132,53 @@ def f(self):
11311132

11321133
class DirectCfgOptimizerTests(CfgOptimizationTestCase):
11331134

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

Modules/_testinternalcapi.c

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1081,13 +1081,17 @@ _testinternalcapi.compiler_codegen -> object
10811081
compile_mode: int = 0
10821082
10831083
Apply compiler code generation to an AST.
1084+
1085+
Return (instruction_sequence, metadata). metadata maps "argcount",
1086+
"posonlyargcount", "kwonlyargcount" to ints and "consts" to the list of
1087+
constants in LOAD_CONST index order (for use with optimize_cfg).
10841088
[clinic start generated code]*/
10851089

10861090
static PyObject *
10871091
_testinternalcapi_compiler_codegen_impl(PyObject *module, PyObject *ast,
10881092
PyObject *filename, int optimize,
10891093
int compile_mode)
1090-
/*[clinic end generated code: output=40a68f6e13951cc8 input=a0e00784f1517cd7]*/
1094+
/*[clinic end generated code: output=40a68f6e13951cc8 input=e0c65e5c80efe30e]*/
10911095
{
10921096
PyCompilerFlags *flags = NULL;
10931097
return _PyCompile_CodeGen(ast, filename, flags, optimize, compile_mode);
@@ -1103,12 +1107,15 @@ _testinternalcapi.optimize_cfg -> object
11031107
nlocals: int
11041108
11051109
Apply compiler optimizations to an instruction list.
1110+
1111+
consts must be a list aligned with LOAD_CONST opargs (the "consts" entry
1112+
from the metadata dict returned by compiler_codegen for the same unit).
11061113
[clinic start generated code]*/
11071114

11081115
static PyObject *
11091116
_testinternalcapi_optimize_cfg_impl(PyObject *module, PyObject *instructions,
11101117
PyObject *consts, int nlocals)
1111-
/*[clinic end generated code: output=57c53c3a3dfd1df0 input=6a96d1926d58d7e5]*/
1118+
/*[clinic end generated code: output=57c53c3a3dfd1df0 input=905c3d935e063b27]*/
11121119
{
11131120
return _PyCompile_OptimizeCfg(instructions, consts, nlocals);
11141121
}

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
@@ -1658,6 +1658,7 @@ _PyCompile_CodeGen(PyObject *ast, PyObject *filename, PyCompilerFlags *pflags,
16581658
{
16591659
PyObject *res = NULL;
16601660
PyObject *metadata = NULL;
1661+
PyObject *consts_list = NULL;
16611662

16621663
if (!PyAST_Check(ast)) {
16631664
PyErr_SetString(PyExc_TypeError, "expected an AST");
@@ -1712,12 +1713,23 @@ _PyCompile_CodeGen(PyObject *ast, PyObject *filename, PyCompilerFlags *pflags,
17121713
}
17131714

17141715
if (_PyInstructionSequence_ApplyLabelMap(_PyCompile_InstrSequence(c)) < 0) {
1715-
return NULL;
1716+
goto finally;
1717+
}
1718+
1719+
/* After AddReturnAtEnd: co_consts indices match the final instruction stream. */
1720+
consts_list = consts_dict_keys_inorder(umd->u_consts);
1721+
if (consts_list == NULL) {
1722+
goto finally;
1723+
}
1724+
if (PyDict_SetItemString(metadata, "consts", consts_list) < 0) {
1725+
goto finally;
17161726
}
1727+
17171728
/* Allocate a copy of the instruction sequence on the heap */
17181729
res = _PyTuple_FromPair((PyObject *)_PyCompile_InstrSequence(c), metadata);
17191730

17201731
finally:
1732+
Py_XDECREF(consts_list);
17211733
Py_XDECREF(metadata);
17221734
_PyCompile_ExitScope(c);
17231735
compiler_free(c);

Python/flowgraph.c

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1309,6 +1309,14 @@ get_const_value(int opcode, int oparg, PyObject *co_consts)
13091309
PyObject *constant = NULL;
13101310
assert(loads_const(opcode));
13111311
if (opcode == LOAD_CONST) {
1312+
assert(PyList_Check(co_consts));
1313+
Py_ssize_t n = PyList_GET_SIZE(co_consts);
1314+
if (oparg < 0 || oparg >= n) {
1315+
PyErr_Format(PyExc_ValueError,
1316+
"LOAD_CONST index %d is out of range for consts (len=%zd)",
1317+
oparg, n);
1318+
return NULL;
1319+
}
13121320
constant = PyList_GET_ITEM(co_consts, oparg);
13131321
}
13141322
if (opcode == LOAD_SMALL_INT) {
@@ -2167,6 +2175,9 @@ basicblock_optimize_load_const(PyObject *const_cache, basicblock *bb, PyObject *
21672175
cfg_instr *inst = &bb->b_instr[i];
21682176
if (inst->i_opcode == LOAD_CONST) {
21692177
PyObject *constant = get_const_value(inst->i_opcode, inst->i_oparg, consts);
2178+
if (constant == NULL) {
2179+
return ERROR;
2180+
}
21702181
int res = maybe_instr_make_load_smallint(inst, constant, consts, const_cache);
21712182
Py_DECREF(constant);
21722183
if (res < 0) {
@@ -4064,6 +4075,10 @@ _PyCompile_OptimizeCfg(PyObject *seq, PyObject *consts, int nlocals)
40644075
PyErr_SetString(PyExc_ValueError, "expected an instruction sequence");
40654076
return NULL;
40664077
}
4078+
if (!PyList_Check(consts)) {
4079+
PyErr_SetString(PyExc_TypeError, "consts must be a list");
4080+
return NULL;
4081+
}
40674082
PyObject *const_cache = PyDict_New();
40684083
if (const_cache == NULL) {
40694084
return NULL;

0 commit comments

Comments
 (0)