Skip to content

Commit 3ba449a

Browse files
committed
Painless: Fixes a null pointer exception in certain cases of for loop usage (#28506)
The initializer and afterthought were not having their types appropriately cast which is necessary with expressions which in turn caused values to be popped off the stack that were null.
1 parent 6a8adee commit 3ba449a

File tree

2 files changed

+12
-1
lines changed

2 files changed

+12
-1
lines changed

modules/lang-painless/src/main/java/org/elasticsearch/painless/node/SFor.java

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -76,7 +76,7 @@ void analyze(Locals locals) {
7676
locals = Locals.newLocalScope(locals);
7777

7878
if (initializer != null) {
79-
if (initializer instanceof AStatement) {
79+
if (initializer instanceof SDeclBlock) {
8080
initializer.analyze(locals);
8181
} else if (initializer instanceof AExpression) {
8282
AExpression initializer = (AExpression)this.initializer;
@@ -87,6 +87,9 @@ void analyze(Locals locals) {
8787
if (!initializer.statement) {
8888
throw createError(new IllegalArgumentException("Not a statement."));
8989
}
90+
91+
initializer.expected = initializer.actual;
92+
this.initializer = initializer.cast(locals);
9093
} else {
9194
throw createError(new IllegalStateException("Illegal tree structure."));
9295
}
@@ -119,6 +122,9 @@ void analyze(Locals locals) {
119122
if (!afterthought.statement) {
120123
throw createError(new IllegalArgumentException("Not a statement."));
121124
}
125+
126+
afterthought.expected = afterthought.actual;
127+
afterthought = afterthought.cast(locals);
122128
}
123129

124130
if (block != null) {
@@ -197,6 +203,7 @@ void write(MethodWriter writer, Globals globals) {
197203
if (afterthought != null) {
198204
writer.mark(begin);
199205
afterthought.write(writer, globals);
206+
writer.writePop(MethodWriter.getType(afterthought.expected).getSize());
200207
}
201208

202209
if (afterthought != null || !allEscape) {

modules/lang-painless/src/test/java/org/elasticsearch/painless/BasicStatementTests.java

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -108,8 +108,12 @@ public void testDoWhileStatement() {
108108
}
109109

110110
public void testForStatement() {
111+
assertEquals(6, exec("int x, y; for (x = 0; x < 4; ++x) {y += x;} return y;"));
111112
assertEquals("aaaaaa", exec("String c = \"a\"; for (int x = 0; x < 5; ++x) c += \"a\"; return c;"));
112113

114+
assertEquals(6, exec("double test() { return 0.0; }" +
115+
"int x, y; for (test(); x < 4; test()) {y += x; ++x;} return y;"));
116+
113117
Object value = exec(
114118
" int[][] b = new int[5][5]; \n" +
115119
" for (int x = 0; x < 5; ++x) { \n" +

0 commit comments

Comments
 (0)