Skip to content

Commit bcc6a50

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 f552710 commit bcc6a50

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
@@ -77,7 +77,7 @@ void analyze(Locals locals) {
7777
locals = Locals.newLocalScope(locals);
7878

7979
if (initializer != null) {
80-
if (initializer instanceof AStatement) {
80+
if (initializer instanceof SDeclBlock) {
8181
initializer.analyze(locals);
8282
} else if (initializer instanceof AExpression) {
8383
AExpression initializer = (AExpression)this.initializer;
@@ -88,6 +88,9 @@ void analyze(Locals locals) {
8888
if (!initializer.statement) {
8989
throw createError(new IllegalArgumentException("Not a statement."));
9090
}
91+
92+
initializer.expected = initializer.actual;
93+
this.initializer = initializer.cast(locals);
9194
} else {
9295
throw createError(new IllegalStateException("Illegal tree structure."));
9396
}
@@ -120,6 +123,9 @@ void analyze(Locals locals) {
120123
if (!afterthought.statement) {
121124
throw createError(new IllegalArgumentException("Not a statement."));
122125
}
126+
127+
afterthought.expected = afterthought.actual;
128+
afterthought = afterthought.cast(locals);
123129
}
124130

125131
if (block != null) {
@@ -198,6 +204,7 @@ void write(MethodWriter writer, Globals globals) {
198204
if (afterthought != null) {
199205
writer.mark(begin);
200206
afterthought.write(writer, globals);
207+
writer.writePop(afterthought.expected.type.getSize());
201208
}
202209

203210
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)