Possible scope leak in Nashorn

Tim Fox timvolpe at gmail.com
Tue Dec 10 08:25:07 PST 2013


On 10/12/13 16:04, Attila Szegedi wrote:
> Indeed. These objects aren't native JavaScript objects; they don't 
> even implement JSObject or extend ScriptObject - they're host objects 
> (just as any POJO technically is). Nashorn's execution model is such 
> that it can handle objects of multiple kinds - native JS objects, 
> POJOs, statics, etc. without ever wrapping them internally thanks to a 
> variety of dynamic linkers it employs, so these objects don't have a 
> wrapped representation. Just as you couldn't pass the result of "new 
> java.util.ArrayList()" to a method expecting JSObject, neither can you 
> pass the objects representing statics, as they don't have a wrapped 
> JSObject representation. This is in general true for anything coming 
> from the script host environment - in this case, the JVM.
>
> If you want to opportunistically wrap in a mirror anything that can be 
> wrapped in a mirror (and get a graceful NOP otherwise), declare your 
> Java API to accept Object, and invoke ScriptUtils.wrap() explicitly - 
> that'll wrap ScriptObject instances into mirrors, and return any other 
> object unchanged.

Thanks, I adapted the code to use ScriptUtils.wrap() and encountered a 
strange situation where JSON.stringify returns undefined for a valid JS 
object. Maybe another scope problem?

Here is a reproducer: https://gist.github.com/purplefox/7893408

Basically I have two scripts:

In one I have a function which takes an argument and displays the result 
of JSON.stringify on it. The first script exports the function by 
calling a setFunction() method on a Java object which wraps the object 
using ScriptUtils as you suggested.

I then invoke another script in a different context and pass in the 
wrapped foo function and the script calls it, when it does the output is 
as follows:

Before call, conf stringified is {"f":"bar"}
config.f is bar
in foo, conf stringified is undefined

Weird!



More information about the nashorn-dev mailing list