package jdk.nashorn.api.scripting;
import java.nio.ByteBuffer;
import java.security.AccessControlContext;
import java.security.AccessController;
import java.security.Permissions;
import java.security.PrivilegedAction;
import java.security.ProtectionDomain;
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.Callable;
import javax.script.Bindings;
import jdk.nashorn.internal.objects.Global;
import jdk.nashorn.internal.runtime.ConsString;
import jdk.nashorn.internal.runtime.Context;
import jdk.nashorn.internal.runtime.ECMAException;
import jdk.nashorn.internal.runtime.JSONListAdapter;
import jdk.nashorn.internal.runtime.JSType;
import jdk.nashorn.internal.runtime.ScriptFunction;
import jdk.nashorn.internal.runtime.ScriptObject;
import jdk.nashorn.internal.runtime.ScriptRuntime;
import jdk.nashorn.internal.runtime.arrays.ArrayData;
import jdk.nashorn.internal.runtime.linker.NashornCallSiteDescriptor;
public final class ScriptObjectMirror extends AbstractJSObject implements Bindings {
private static AccessControlContext getContextAccCtxt() {
final Permissions perms = new Permissions();
perms.add(new RuntimePermission(Context.NASHORN_GET_CONTEXT));
return new AccessControlContext(new ProtectionDomain[] { new ProtectionDomain(null, perms) });
}
private static final AccessControlContext GET_CONTEXT_ACC_CTXT = getContextAccCtxt();
private final ScriptObject sobj;
private final Global global;
private final boolean strict;
private final boolean jsonCompatible;
@Override
public boolean equals(final Object other) {
if (other instanceof ScriptObjectMirror) {
return sobj.equals(((ScriptObjectMirror)other).sobj);
}
return false;
}
@Override
public int hashCode() {
return sobj.hashCode();
}
@Override
public String toString() {
return inGlobal(new Callable<String>() {
@Override
public String call() {
return ScriptRuntime.safeToString(sobj);
}
});
}
@Override
public Object call(final Object thiz, final Object... args) {
final Global oldGlobal = Context.getGlobal();
final boolean globalChanged = (oldGlobal != global);
try {
if (globalChanged) {
Context.setGlobal(global);
}
if (sobj instanceof ScriptFunction) {
final Object[] modArgs = globalChanged? wrapArrayLikeMe(args, oldGlobal) : args;
final Object self = globalChanged? wrapLikeMe(thiz, oldGlobal) : thiz;
return wrapLikeMe(ScriptRuntime.apply((ScriptFunction)sobj, unwrap(self, global), unwrapArray(modArgs, global)));
}
throw new RuntimeException("not a function: " + toString());
} catch (final NashornException ne) {
throw ne.initEcmaError(global);
} catch (final RuntimeException | Error e) {
throw e;
} catch (final Throwable t) {
throw new RuntimeException(t);
} finally {
if (globalChanged) {
Context.setGlobal(oldGlobal);
}
}
}
@Override
public Object newObject(final Object... args) {
final Global oldGlobal = Context.getGlobal();
final boolean globalChanged = (oldGlobal != global);
try {
if (globalChanged) {
Context.setGlobal(global);
}
if (sobj instanceof ScriptFunction) {
final Object[] modArgs = globalChanged? wrapArrayLikeMe(args, oldGlobal) : args;
return wrapLikeMe(ScriptRuntime.construct((ScriptFunction)sobj, unwrapArray(modArgs, global)));
}
throw new RuntimeException("not a constructor: " + toString());
} catch (final NashornException ne) {
throw ne.initEcmaError(global);
} catch (final RuntimeException | Error e) {
throw e;
} catch (final Throwable t) {
throw new RuntimeException(t);
} finally {
if (globalChanged) {
Context.setGlobal(oldGlobal);
}
}
}
@Override
public Object eval(final String s) {
return inGlobal(new Callable<Object>() {
@Override
public Object call() {
final Context context = AccessController.doPrivileged(
new PrivilegedAction<Context>() {
@Override
public Context run() {
return Context.getContext();
}
}, GET_CONTEXT_ACC_CTXT);
return wrapLikeMe(context.eval(global, s, sobj, null));
}
});
}
public Object callMember(final String functionName, final Object... args) {
Objects.requireNonNull(functionName);
final Global oldGlobal = Context.getGlobal();
final boolean globalChanged = (oldGlobal != global);
try {
if (globalChanged) {
Context.setGlobal(global);
}
final Object val = sobj.get(functionName);
if (val instanceof ScriptFunction) {
final Object[] modArgs = globalChanged? wrapArrayLikeMe(args, oldGlobal) : args;
return wrapLikeMe(ScriptRuntime.apply((ScriptFunction)val, sobj, unwrapArray(modArgs, global)));
} else if (val instanceof JSObject && ((JSObject)val).isFunction()) {
return ((JSObject)val).call(sobj, args);
}
throw new NoSuchMethodException("No such function " + functionName);
} catch (final NashornException ne) {
throw ne.initEcmaError(global);
} catch (final RuntimeException | Error e) {
throw e;
} catch (final Throwable t) {
throw new RuntimeException(t);
} finally {
if (globalChanged) {
Context.setGlobal(oldGlobal);
}
}
}
@Override
public Object getMember(final String name) {
Objects.requireNonNull(name);
return inGlobal(new Callable<Object>() {
@Override public Object call() {
return wrapLikeMe(sobj.get(name));
}
});
}
@Override
public Object getSlot(final int index) {
return inGlobal(new Callable<Object>() {
@Override public Object call() {
return wrapLikeMe(sobj.get(index));
}
});
}
@Override
public boolean hasMember(final String name) {
Objects.requireNonNull(name);
return inGlobal(new Callable<Boolean>() {
@Override public Boolean call() {
return sobj.has(name);
}
});
}
@Override
public boolean hasSlot(final int slot) {
return inGlobal(new Callable<Boolean>() {
@Override public Boolean call() {
return sobj.has(slot);
}
});
}
@Override
public void removeMember(final String name) {
remove(Objects.requireNonNull(name));
}
@Override
public void setMember(final String name, final Object value) {
put(Objects.requireNonNull(name), value);
}
@Override
public void setSlot(final int index, final Object value) {
inGlobal(new Callable<Void>() {
@Override public Void call() {
sobj.set(index, unwrap(value, global), getCallSiteFlags());
return null;
}
});
}
public void setIndexedPropertiesToExternalArrayData(final ByteBuffer buf) {
inGlobal(new Callable<Void>() {
@Override public Void call() {
sobj.setArray(ArrayData.allocate(buf));
return null;
}
});
}
@Override
public boolean isInstance(final Object instance) {
if (! (instance instanceof ScriptObjectMirror)) {
return false;
}
final ScriptObjectMirror mirror = (ScriptObjectMirror)instance;
if (global != mirror.global) {
return false;
}
return inGlobal(new Callable<Boolean>() {
@Override public Boolean call() {
return sobj.isInstance(mirror.sobj);
}
});
}
@Override
public String getClassName() {
return sobj.getClassName();
}
@Override
public boolean isFunction() {
return sobj instanceof ScriptFunction;
}
@Override
public boolean isStrictFunction() {
return isFunction() && ((ScriptFunction)sobj).isStrict();
}
@Override
public boolean isArray() {
return sobj.isArray();
}
@Override
public void clear() {
inGlobal(new Callable<Object>() {
@Override public Object call() {
sobj.clear(strict);
return null;
}
});
}
@Override
public boolean containsKey(final Object key) {
checkKey(key);
return inGlobal(new Callable<Boolean>() {
@Override public Boolean call() {
return sobj.containsKey(key);
}
});
}
@Override
public boolean containsValue(final Object value) {
return inGlobal(new Callable<Boolean>() {
@Override public Boolean call() {
return sobj.containsValue(unwrap(value, global));
}
});
}
@Override
public Set<Map.Entry<String, Object>> entrySet() {
return inGlobal(new Callable<Set<Map.Entry<String, Object>>>() {
@Override public Set<Map.Entry<String, Object>> call() {
final Iterator<String> iter = sobj.propertyIterator();
final Set<Map.Entry<String, Object>> entries = new LinkedHashSet<>();
while (iter.hasNext()) {
final String key = iter.next();
final Object value = translateUndefined(wrapLikeMe(sobj.get(key)));
entries.add(new AbstractMap.SimpleImmutableEntry<>(key, value));
}
return Collections.unmodifiableSet(entries);
}
});
}
@Override
public Object get(final Object key) {
checkKey(key);
return inGlobal(new Callable<Object>() {
@Override public Object call() {
return translateUndefined(wrapLikeMe(sobj.get(key)));
}
});
}
@Override
public boolean isEmpty() {
return inGlobal(new Callable<Boolean>() {
@Override public Boolean call() {
return sobj.isEmpty();
}
});
}
@Override
public Set<String> keySet() {
return inGlobal(new Callable<Set<String>>() {
@Override public Set<String> call() {
final Iterator<String> iter = sobj.propertyIterator();
final Set<String> keySet = new LinkedHashSet<>();
while (iter.hasNext()) {
keySet.add(iter.next());
}
return Collections.unmodifiableSet(keySet);
}
});
}
@Override
public Object put(final String key, final Object value) {
checkKey(key);
final ScriptObject oldGlobal = Context.getGlobal();
final boolean globalChanged = (oldGlobal != global);
return inGlobal(new Callable<Object>() {
@Override public Object call() {
final Object modValue = globalChanged? wrapLikeMe(value, oldGlobal) : value;
return translateUndefined(wrapLikeMe(sobj.put(key, unwrap(modValue, global), strict)));
}
});
}
@Override
public void putAll(final Map<? extends String, ? extends Object> map) {
Objects.requireNonNull(map);
final ScriptObject oldGlobal = Context.getGlobal();
final boolean globalChanged = (oldGlobal != global);
inGlobal(new Callable<Object>() {
@Override public Object call() {
for (final Map.Entry<? extends String, ? extends Object> entry : map.entrySet()) {
final Object value = entry.getValue();
final Object modValue = globalChanged? wrapLikeMe(value, oldGlobal) : value;
final String key = entry.getKey();
checkKey(key);
sobj.set(key, unwrap(modValue, global), getCallSiteFlags());
}
return null;
}
});
}
@Override
public Object remove(final Object key) {
checkKey(key);
return inGlobal(new Callable<Object>() {
@Override public Object call() {
return translateUndefined(wrapLikeMe(sobj.remove(key, strict)));
}
});
}
public boolean delete(final Object key) {
return inGlobal(new Callable<Boolean>() {
@Override public Boolean call() {
return sobj.delete(unwrap(key, global), strict);
}
});
}
@Override
public int size() {
return inGlobal(new Callable<Integer>() {
@Override public Integer call() {
return sobj.size();
}
});
}
@Override
public Collection<Object> values() {
return inGlobal(new Callable<Collection<Object>>() {
@Override public Collection<Object> call() {
final List<Object> values = new ArrayList<>(size());
final Iterator<Object> iter = sobj.valueIterator();
while (iter.hasNext()) {
values.add(translateUndefined(wrapLikeMe(iter.next())));
}
return Collections.unmodifiableList(values);
}
});
}
public Object getProto() {
return inGlobal(new Callable<Object>() {
@Override public Object call() {
return wrapLikeMe(sobj.getProto());
}
});
}
public void setProto(final Object proto) {
inGlobal(new Callable<Void>() {
@Override public Void call() {
sobj.setPrototypeOf(unwrap(proto, global));
return null;
}
});
}
public Object getOwnPropertyDescriptor(final String key) {
return inGlobal(new Callable<Object>() {
@Override public Object call() {
return wrapLikeMe(sobj.getOwnPropertyDescriptor(key));
}
});
}
public String[] getOwnKeys(final boolean all) {
return inGlobal(new Callable<String[]>() {
@Override public String[] call() {
return sobj.getOwnKeys(all);
}
});
}
public ScriptObjectMirror preventExtensions() {
return inGlobal(new Callable<ScriptObjectMirror>() {
@Override public ScriptObjectMirror call() {
sobj.preventExtensions();
return ScriptObjectMirror.this;
}
});
}
public boolean isExtensible() {
return inGlobal(new Callable<Boolean>() {
@Override public Boolean call() {
return sobj.isExtensible();
}
});
}
public ScriptObjectMirror seal() {
return inGlobal(new Callable<ScriptObjectMirror>() {
@Override public ScriptObjectMirror call() {
sobj.seal();
return ScriptObjectMirror.this;
}
});
}
public boolean isSealed() {
return inGlobal(new Callable<Boolean>() {
@Override public Boolean call() {
return sobj.isSealed();
}
});
}
public ScriptObjectMirror freeze() {
return inGlobal(new Callable<ScriptObjectMirror>() {
@Override public ScriptObjectMirror call() {
sobj.freeze();
return ScriptObjectMirror.this;
}
});
}
public boolean isFrozen() {
return inGlobal(new Callable<Boolean>() {
@Override public Boolean call() {
return sobj.isFrozen();
}
});
}
public static boolean isUndefined(final Object obj) {
return obj == ScriptRuntime.UNDEFINED;
}
public <T> T to(final Class<T> type) {
return inGlobal(new Callable<T>() {
@Override
public T call() {
return type.cast(ScriptUtils.convert(sobj, type));
}
});
}
public static Object wrap(final Object obj, final Object homeGlobal) {
return wrap(obj, homeGlobal, false);
}
public static Object wrapAsJSONCompatible(final Object obj, final Object homeGlobal) {
return wrap(obj, homeGlobal, true);
}
private static Object wrap(final Object obj, final Object homeGlobal, final boolean jsonCompatible) {
if(obj instanceof ScriptObject) {
if (!(homeGlobal instanceof Global)) {
return obj;
}
final ScriptObject sobj = (ScriptObject)obj;
final Global global = (Global)homeGlobal;
final ScriptObjectMirror mirror = new ScriptObjectMirror(sobj, global, jsonCompatible);
if (jsonCompatible && sobj.isArray()) {
return new JSONListAdapter(mirror, global);
}
return mirror;
} else if(obj instanceof ConsString) {
return obj.toString();
} else if (jsonCompatible && obj instanceof ScriptObjectMirror) {
return ((ScriptObjectMirror)obj).asJSONCompatible();
}
return obj;
}
private Object wrapLikeMe(final Object obj, final Object homeGlobal) {
return wrap(obj, homeGlobal, jsonCompatible);
}
private Object wrapLikeMe(final Object obj) {
return wrapLikeMe(obj, global);
}
public static Object unwrap(final Object obj, final Object homeGlobal) {
if (obj instanceof ScriptObjectMirror) {
final ScriptObjectMirror mirror = (ScriptObjectMirror)obj;
return (mirror.global == homeGlobal)? mirror.sobj : obj;
} else if (obj instanceof JSONListAdapter) {
return ((JSONListAdapter)obj).unwrap(homeGlobal);
}
return obj;
}
public static Object[] wrapArray(final Object[] args, final Object homeGlobal) {
return wrapArray(args, homeGlobal, false);
}
private static Object[] wrapArray(final Object[] args, final Object homeGlobal, final boolean jsonCompatible) {
if (args == null || args.length == 0) {
return args;
}
final Object[] newArgs = new Object[args.length];
int index = 0;
for (final Object obj : args) {
newArgs[index] = wrap(obj, homeGlobal, jsonCompatible);
index++;
}
return newArgs;
}
private Object[] wrapArrayLikeMe(final Object[] args, final Object homeGlobal) {
return wrapArray(args, homeGlobal, jsonCompatible);
}
public static Object[] unwrapArray(final Object[] args, final Object homeGlobal) {
if (args == null || args.length == 0) {
return args;
}
final Object[] newArgs = new Object[args.length];
int index = 0;
for (final Object obj : args) {
newArgs[index] = unwrap(obj, homeGlobal);
index++;
}
return newArgs;
}
public static boolean identical(final Object obj1, final Object obj2) {
final Object o1 = (obj1 instanceof ScriptObjectMirror)?
((ScriptObjectMirror)obj1).sobj : obj1;
final Object o2 = (obj2 instanceof ScriptObjectMirror)?
((ScriptObjectMirror)obj2).sobj : obj2;
return o1 == o2;
}
ScriptObjectMirror(final ScriptObject sobj, final Global global) {
this(sobj, global, false);
}
private ScriptObjectMirror(final ScriptObject sobj, final Global global, final boolean jsonCompatible) {
assert sobj != null : "ScriptObjectMirror on null!";
assert global != null : "home Global is null";
this.sobj = sobj;
this.global = global;
this.strict = global.isStrictContext();
this.jsonCompatible = jsonCompatible;
}
ScriptObject getScriptObject() {
return sobj;
}
Global getHomeGlobal() {
return global;
}
static Object translateUndefined(final Object obj) {
return (obj == ScriptRuntime.UNDEFINED)? null : obj;
}
private int getCallSiteFlags() {
return strict ? NashornCallSiteDescriptor.CALLSITE_STRICT : 0;
}
private <V> V inGlobal(final Callable<V> callable) {
final Global oldGlobal = Context.getGlobal();
final boolean globalChanged = (oldGlobal != global);
if (globalChanged) {
Context.setGlobal(global);
}
try {
return callable.call();
} catch (final NashornException ne) {
throw ne.initEcmaError(global);
} catch (final RuntimeException e) {
throw e;
} catch (final Exception e) {
throw new AssertionError("Cannot happen", e);
} finally {
if (globalChanged) {
Context.setGlobal(oldGlobal);
}
}
}
private static void checkKey(final Object key) {
Objects.requireNonNull(key, "key can not be null");
if (!(key instanceof String)) {
throw new ClassCastException("key should be a String. It is " + key.getClass().getName() + " instead.");
} else if (((String)key).length() == 0) {
throw new IllegalArgumentException("key can not be empty");
}
}
@Override @Deprecated
public double toNumber() {
return inGlobal(new Callable<Double>() {
@Override public Double call() {
return JSType.toNumber(sobj);
}
});
}
@Override
public Object getDefaultValue(final Class<?> hint) {
return inGlobal(new Callable<Object>() {
@Override public Object call() {
try {
return sobj.getDefaultValue(hint);
} catch (final ECMAException e) {
throw new UnsupportedOperationException(e.getMessage(), e);
}
}
});
}
private ScriptObjectMirror asJSONCompatible() {
if (this.jsonCompatible) {
return this;
}
return new ScriptObjectMirror(sobj, global, true);
}
}