Skip to content

Commit 3a2c2af

Browse files
Mike PallBuristan
Mike Pall
authored andcommitted
Fix predict_next() in parser (for real now).
Reported by Sergey Kaplun. (cherry picked from commit f602f01) Before the patch `predict_next()` uses the pc allocation limit (`fs->bclim`) instead of the real limit of the defined bytecodes (`fs->pc`). This leads to the use of undefined value and possible crash. This patch fixes the check. Sergey Kaplun: * added the description and the test for the problem Part of tarantool/tarantool#10709
1 parent ffede1b commit 3a2c2af

File tree

2 files changed

+33
-4
lines changed

2 files changed

+33
-4
lines changed

src/lj_parse.c

+2-4
Original file line numberDiff line numberDiff line change
@@ -2527,11 +2527,9 @@ static void parse_for_num(LexState *ls, GCstr *varname, BCLine line)
25272527
*/
25282528
static int predict_next(LexState *ls, FuncState *fs, BCPos pc)
25292529
{
2530-
BCIns ins;
2530+
BCIns ins = fs->bcbase[pc].ins;
25312531
GCstr *name;
25322532
cTValue *o;
2533-
if (pc >= fs->bclim) return 0;
2534-
ins = fs->bcbase[pc].ins;
25352533
switch (bc_op(ins)) {
25362534
case BC_MOV:
25372535
if (bc_d(ins) >= fs->nactvar) return 0;
@@ -2580,7 +2578,7 @@ static void parse_for_iter(LexState *ls, GCstr *indexname)
25802578
assign_adjust(ls, 3, expr_list(ls, &e), &e);
25812579
/* The iterator needs another 3 [4] slots (func [pc] | state ctl). */
25822580
bcreg_bump(fs, 3+LJ_FR2);
2583-
isnext = (nvars <= 5 && predict_next(ls, fs, exprpc));
2581+
isnext = (nvars <= 5 && fs->pc > exprpc && predict_next(ls, fs, exprpc));
25842582
var_add(ls, 3); /* Hidden control variables. */
25852583
lex_check(ls, TK_do);
25862584
loop = bcemit_AJ(fs, isnext ? BC_ISNEXT : BC_JMP, base, NO_JMP);
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
local tap = require('tap')
2+
local test = tap.test('lj-1226-fix-predict-next')
3+
4+
test:plan(3)
5+
6+
-- The resulting bytecode is the following:
7+
--
8+
-- 0001 KNIL 0 3
9+
-- 0002 JMP 4 => 0003
10+
-- 0003 => ITERC 4 2 3
11+
-- 0004 ITERL 4 => 0003
12+
--
13+
-- The parsing of the `for` iterator uses the incorrect check for
14+
-- `fs->bclim`, which allows the usage of an uninitialized value,
15+
-- so the test fails under Valgrind.
16+
local res_f = loadstring([[
17+
-- This local variable is necessary, because it emits `KPRI`
18+
-- bytecode, with which the next `KPRI` bytecode will be merged.
19+
local _
20+
for _ in nil do end
21+
]])
22+
23+
test:ok(res_f, 'chunk loaded successfully')
24+
25+
local res, err = pcall(res_f)
26+
27+
-- Check consistency with PUC Rio Lua 5.1 behaviour.
28+
test:ok(not res, 'loaded function not executed')
29+
test:like(err, 'attempt to call a nil value', 'correct error message')
30+
31+
test:done(true)

0 commit comments

Comments
 (0)