oracle / graaljs

GraalJS – A high-performance, ECMAScript compliant, and embeddable JavaScript runtime for Java
https://www.graalvm.org/javascript/
Universal Permissive License v1.0
1.82k stars 191 forks source link

GraalJSScriptEngine: NPE when setting empty engine bindings #839

Closed simonis closed 2 months ago

simonis commented 2 months ago

When using the JSR-223 compliant ScriptEngine implementation, GraalJSScriptEngine will throw a NPE when setting empty bindings with ENGINE_SCOPE:

import javax.script.Bindings;
import javax.script.ScriptContext;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;

public class EngineScopeBindingsNPE {

  public static void main(String[] args) {
    ScriptEngineManager engineManager = new ScriptEngineManager();
    ScriptEngine engine = engineManager.getEngineByName("graal.js");
    if (engine == null) {
      System.out.println("graal.js engine not found");
      return;
    }
    Bindings bindings = engine.createBindings();
    engine.setBindings(bindings, ScriptContext.ENGINE_SCOPE);
    if (engine.getBindings(ScriptContext.ENGINE_SCOPE) != bindings) {
      throw new Error("Should be the same");
    }
  }
}

Executing this program will result in:

Exception in thread "main" java.lang.NullPointerException: Cannot invoke "org.graalvm.polyglot.Context.eval(org.graalvm.polyglot.Source)" because "context" is null
    at org.graalvm.js.scriptengine/com.oracle.truffle.js.scriptengine.GraalJSScriptEngine.evalInternal(GraalJSScriptEngine.java:408)
    at org.graalvm.js.scriptengine/com.oracle.truffle.js.scriptengine.GraalJSBindings.updateBinding(GraalJSBindings.java:121)
    at org.graalvm.js.scriptengine/com.oracle.truffle.js.scriptengine.GraalJSBindings.updateContextBinding(GraalJSBindings.java:111)
    at org.graalvm.js.scriptengine/com.oracle.truffle.js.scriptengine.GraalJSBindings.updateEngineScriptContext(GraalJSBindings.java:222)
    at org.graalvm.js.scriptengine/com.oracle.truffle.js.scriptengine.GraalJSScriptEngine.setBindings(GraalJSScriptEngine.java:426)
    at EngineScopeBindingsNPE.main(EngineScopeBindingsNPE.java:16)
iamstolis commented 2 months ago

Thank you for the report and for the submission of the PR that fixes the issue!