diff --git a/nashorn/buildtools/nasgen/build.xml b/nashorn/buildtools/nasgen/build.xml
index bf56c1111df..6243bb2f02c 100644
--- a/nashorn/buildtools/nasgen/build.xml
+++ b/nashorn/buildtools/nasgen/build.xml
@@ -42,7 +42,8 @@
destdir="${build.classes.dir}"
classpath="${javac.classpath}"
debug="${javac.debug}"
- includeantruntime="false">
+ includeantruntime="false" fork="true">
+
diff --git a/nashorn/buildtools/nasgen/src/jdk/nashorn/internal/tools/nasgen/ClassGenerator.java b/nashorn/buildtools/nasgen/src/jdk/nashorn/internal/tools/nasgen/ClassGenerator.java
index bc6bb4b2db2..3425e9fd0c0 100644
--- a/nashorn/buildtools/nasgen/src/jdk/nashorn/internal/tools/nasgen/ClassGenerator.java
+++ b/nashorn/buildtools/nasgen/src/jdk/nashorn/internal/tools/nasgen/ClassGenerator.java
@@ -25,6 +25,7 @@
package jdk.nashorn.internal.tools.nasgen;
+import static jdk.internal.org.objectweb.asm.Opcodes.ACC_FINAL;
import static jdk.internal.org.objectweb.asm.Opcodes.ACC_PRIVATE;
import static jdk.internal.org.objectweb.asm.Opcodes.ACC_PUBLIC;
import static jdk.internal.org.objectweb.asm.Opcodes.ACC_STATIC;
@@ -36,14 +37,24 @@ import static jdk.nashorn.internal.tools.nasgen.StringConstants.GETTER_PREFIX;
import static jdk.nashorn.internal.tools.nasgen.StringConstants.GET_CLASS_NAME;
import static jdk.nashorn.internal.tools.nasgen.StringConstants.GET_CLASS_NAME_DESC;
import static jdk.nashorn.internal.tools.nasgen.StringConstants.INIT;
-import static jdk.nashorn.internal.tools.nasgen.StringConstants.LOOKUP_NEWPROPERTY;
-import static jdk.nashorn.internal.tools.nasgen.StringConstants.LOOKUP_NEWPROPERTY_DESC;
-import static jdk.nashorn.internal.tools.nasgen.StringConstants.LOOKUP_TYPE;
-import static jdk.nashorn.internal.tools.nasgen.StringConstants.MAP_DESC;
-import static jdk.nashorn.internal.tools.nasgen.StringConstants.MAP_FIELD_NAME;
-import static jdk.nashorn.internal.tools.nasgen.StringConstants.MAP_NEWMAP;
-import static jdk.nashorn.internal.tools.nasgen.StringConstants.MAP_NEWMAP_DESC;
-import static jdk.nashorn.internal.tools.nasgen.StringConstants.MAP_TYPE;
+import static jdk.nashorn.internal.tools.nasgen.StringConstants.ACCESSORPROPERTY_CREATE;
+import static jdk.nashorn.internal.tools.nasgen.StringConstants.ACCESSORPROPERTY_CREATE_DESC;
+import static jdk.nashorn.internal.tools.nasgen.StringConstants.ACCESSORPROPERTY_TYPE;
+import static jdk.nashorn.internal.tools.nasgen.StringConstants.LIST_DESC;
+import static jdk.nashorn.internal.tools.nasgen.StringConstants.ARRAYLIST_TYPE;
+import static jdk.nashorn.internal.tools.nasgen.StringConstants.ARRAYLIST_INIT_DESC;
+import static jdk.nashorn.internal.tools.nasgen.StringConstants.COLLECTION_TYPE;
+import static jdk.nashorn.internal.tools.nasgen.StringConstants.COLLECTION_ADD;
+import static jdk.nashorn.internal.tools.nasgen.StringConstants.COLLECTION_ADD_DESC;
+import static jdk.nashorn.internal.tools.nasgen.StringConstants.COLLECTIONS_TYPE;
+import static jdk.nashorn.internal.tools.nasgen.StringConstants.COLLECTIONS_EMPTY_LIST;
+import static jdk.nashorn.internal.tools.nasgen.StringConstants.PROPERTYMAP_DESC;
+import static jdk.nashorn.internal.tools.nasgen.StringConstants.PROPERTYMAP_FIELD_NAME;
+import static jdk.nashorn.internal.tools.nasgen.StringConstants.PROPERTYMAP_SETISSHARED;
+import static jdk.nashorn.internal.tools.nasgen.StringConstants.PROPERTYMAP_SETISSHARED_DESC;
+import static jdk.nashorn.internal.tools.nasgen.StringConstants.PROPERTYMAP_NEWMAP;
+import static jdk.nashorn.internal.tools.nasgen.StringConstants.PROPERTYMAP_NEWMAP_DESC;
+import static jdk.nashorn.internal.tools.nasgen.StringConstants.PROPERTYMAP_TYPE;
import static jdk.nashorn.internal.tools.nasgen.StringConstants.OBJECT_DESC;
import static jdk.nashorn.internal.tools.nasgen.StringConstants.SCRIPTFUNCTIONIMPL_MAKEFUNCTION;
import static jdk.nashorn.internal.tools.nasgen.StringConstants.SCRIPTFUNCTIONIMPL_MAKEFUNCTION_DESC;
@@ -160,18 +171,30 @@ public class ClassGenerator {
return new MethodGenerator(mv, access, name, desc);
}
- static void emitStaticInitPrefix(final MethodGenerator mi, final String className) {
+ static void emitStaticInitPrefix(final MethodGenerator mi, final String className, final int memberCount) {
mi.visitCode();
- mi.pushNull();
- mi.putStatic(className, MAP_FIELD_NAME, MAP_DESC);
- mi.loadClass(className);
- mi.invokeStatic(MAP_TYPE, MAP_NEWMAP, MAP_NEWMAP_DESC);
- // stack: PropertyMap
+ if (memberCount > 0) {
+ // new ArrayList(int)
+ mi.newObject(ARRAYLIST_TYPE);
+ mi.dup();
+ mi.push(memberCount);
+ mi.invokeSpecial(ARRAYLIST_TYPE, INIT, ARRAYLIST_INIT_DESC);
+ // stack: ArrayList
+ } else {
+ // java.util.Collections.EMPTY_LIST
+ mi.getStatic(COLLECTIONS_TYPE, COLLECTIONS_EMPTY_LIST, LIST_DESC);
+ // stack List
+ }
}
static void emitStaticInitSuffix(final MethodGenerator mi, final String className) {
- // stack: PropertyMap
- mi.putStatic(className, MAP_FIELD_NAME, MAP_DESC);
+ // stack: Collection
+ // pmap = PropertyMap.newMap(Collection);
+ mi.invokeStatic(PROPERTYMAP_TYPE, PROPERTYMAP_NEWMAP, PROPERTYMAP_NEWMAP_DESC);
+ // pmap.setIsShared();
+ mi.invokeVirtual(PROPERTYMAP_TYPE, PROPERTYMAP_SETISSHARED, PROPERTYMAP_SETISSHARED_DESC);
+ // $nasgenmap$ = pmap;
+ mi.putStatic(className, PROPERTYMAP_FIELD_NAME, PROPERTYMAP_DESC);
mi.returnVoid();
mi.computeMaxs();
mi.visitEnd();
@@ -235,9 +258,9 @@ public class ClassGenerator {
}
static void addMapField(final ClassVisitor cv) {
- // add a MAP static field
- final FieldVisitor fv = cv.visitField(ACC_PRIVATE | ACC_STATIC,
- MAP_FIELD_NAME, MAP_DESC, null, null);
+ // add a PropertyMap static field
+ final FieldVisitor fv = cv.visitField(ACC_PRIVATE | ACC_STATIC | ACC_FINAL,
+ PROPERTYMAP_FIELD_NAME, PROPERTYMAP_DESC, null, null);
if (fv != null) {
fv.visitEnd();
}
@@ -278,7 +301,11 @@ public class ClassGenerator {
static void linkerAddGetterSetter(final MethodGenerator mi, final String className, final MemberInfo memInfo) {
final String propertyName = memInfo.getName();
- // stack: PropertyMap
+ // stack: Collection
+ // dup of Collection instance
+ mi.dup();
+
+ // property = AccessorProperty.create(key, flags, getter, setter);
mi.loadLiteral(propertyName);
// setup flags
mi.push(memInfo.getAttributes());
@@ -292,13 +319,21 @@ public class ClassGenerator {
javaName = SETTER_PREFIX + memInfo.getJavaName();
mi.visitLdcInsn(new Handle(H_INVOKEVIRTUAL, className, javaName, setterDesc(memInfo)));
}
- mi.invokeStatic(LOOKUP_TYPE, LOOKUP_NEWPROPERTY, LOOKUP_NEWPROPERTY_DESC);
- // stack: PropertyMap
+ mi.invokeStatic(ACCESSORPROPERTY_TYPE, ACCESSORPROPERTY_CREATE, ACCESSORPROPERTY_CREATE_DESC);
+ // boolean Collection.add(property)
+ mi.invokeInterface(COLLECTION_TYPE, COLLECTION_ADD, COLLECTION_ADD_DESC);
+ // pop return value of Collection.add
+ mi.pop();
+ // stack: Collection
}
static void linkerAddGetterSetter(final MethodGenerator mi, final String className, final MemberInfo getter, final MemberInfo setter) {
final String propertyName = getter.getName();
- // stack: PropertyMap
+ // stack: Collection
+ // dup of Collection instance
+ mi.dup();
+
+ // property = AccessorProperty.create(key, flags, getter, setter);
mi.loadLiteral(propertyName);
// setup flags
mi.push(getter.getAttributes());
@@ -312,8 +347,12 @@ public class ClassGenerator {
mi.visitLdcInsn(new Handle(H_INVOKESTATIC, className,
setter.getJavaName(), setter.getJavaDesc()));
}
- mi.invokeStatic(LOOKUP_TYPE, LOOKUP_NEWPROPERTY, LOOKUP_NEWPROPERTY_DESC);
- // stack: PropertyMap
+ mi.invokeStatic(ACCESSORPROPERTY_TYPE, ACCESSORPROPERTY_CREATE, ACCESSORPROPERTY_CREATE_DESC);
+ // boolean Collection.add(property)
+ mi.invokeInterface(COLLECTION_TYPE, COLLECTION_ADD, COLLECTION_ADD_DESC);
+ // pop return value of Collection.add
+ mi.pop();
+ // stack: Collection
}
static ScriptClassInfo getScriptClassInfo(final String fileName) throws IOException {
diff --git a/nashorn/buildtools/nasgen/src/jdk/nashorn/internal/tools/nasgen/ConstructorGenerator.java b/nashorn/buildtools/nasgen/src/jdk/nashorn/internal/tools/nasgen/ConstructorGenerator.java
index 7c59f8c3c2b..e90b53ecb81 100644
--- a/nashorn/buildtools/nasgen/src/jdk/nashorn/internal/tools/nasgen/ConstructorGenerator.java
+++ b/nashorn/buildtools/nasgen/src/jdk/nashorn/internal/tools/nasgen/ConstructorGenerator.java
@@ -32,11 +32,11 @@ import static jdk.internal.org.objectweb.asm.Opcodes.V1_7;
import static jdk.nashorn.internal.tools.nasgen.StringConstants.CONSTRUCTOR_SUFFIX;
import static jdk.nashorn.internal.tools.nasgen.StringConstants.DEFAULT_INIT_DESC;
import static jdk.nashorn.internal.tools.nasgen.StringConstants.INIT;
-import static jdk.nashorn.internal.tools.nasgen.StringConstants.MAP_DESC;
-import static jdk.nashorn.internal.tools.nasgen.StringConstants.MAP_DUPLICATE;
-import static jdk.nashorn.internal.tools.nasgen.StringConstants.MAP_DUPLICATE_DESC;
-import static jdk.nashorn.internal.tools.nasgen.StringConstants.MAP_FIELD_NAME;
-import static jdk.nashorn.internal.tools.nasgen.StringConstants.MAP_TYPE;
+import static jdk.nashorn.internal.tools.nasgen.StringConstants.PROPERTYMAP_DESC;
+import static jdk.nashorn.internal.tools.nasgen.StringConstants.PROPERTYMAP_DUPLICATE;
+import static jdk.nashorn.internal.tools.nasgen.StringConstants.PROPERTYMAP_DUPLICATE_DESC;
+import static jdk.nashorn.internal.tools.nasgen.StringConstants.PROPERTYMAP_FIELD_NAME;
+import static jdk.nashorn.internal.tools.nasgen.StringConstants.PROPERTYMAP_TYPE;
import static jdk.nashorn.internal.tools.nasgen.StringConstants.OBJECT_DESC;
import static jdk.nashorn.internal.tools.nasgen.StringConstants.PROTOTYPEOBJECT_SETCONSTRUCTOR;
import static jdk.nashorn.internal.tools.nasgen.StringConstants.PROTOTYPEOBJECT_SETCONSTRUCTOR_DESC;
@@ -129,7 +129,7 @@ public class ConstructorGenerator extends ClassGenerator {
private void emitStaticInitializer() {
final MethodGenerator mi = makeStaticInitializer();
- emitStaticInitPrefix(mi, className);
+ emitStaticInitPrefix(mi, className, memberCount);
for (final MemberInfo memInfo : scriptClassInfo.getMembers()) {
if (memInfo.isConstructorFunction() || memInfo.isConstructorProperty()) {
@@ -170,10 +170,10 @@ public class ConstructorGenerator extends ClassGenerator {
private void loadMap(final MethodGenerator mi) {
if (memberCount > 0) {
- mi.getStatic(className, MAP_FIELD_NAME, MAP_DESC);
+ mi.getStatic(className, PROPERTYMAP_FIELD_NAME, PROPERTYMAP_DESC);
// make sure we use duplicated PropertyMap so that original map
- // stays intact and so can be used for many globals in same context
- mi.invokeVirtual(MAP_TYPE, MAP_DUPLICATE, MAP_DUPLICATE_DESC);
+ // stays intact and so can be used for many globals.
+ mi.invokeVirtual(PROPERTYMAP_TYPE, PROPERTYMAP_DUPLICATE, PROPERTYMAP_DUPLICATE_DESC);
}
}
diff --git a/nashorn/buildtools/nasgen/src/jdk/nashorn/internal/tools/nasgen/MethodGenerator.java b/nashorn/buildtools/nasgen/src/jdk/nashorn/internal/tools/nasgen/MethodGenerator.java
index c3dfd878526..475d7328c69 100644
--- a/nashorn/buildtools/nasgen/src/jdk/nashorn/internal/tools/nasgen/MethodGenerator.java
+++ b/nashorn/buildtools/nasgen/src/jdk/nashorn/internal/tools/nasgen/MethodGenerator.java
@@ -57,6 +57,7 @@ import static jdk.internal.org.objectweb.asm.Opcodes.IALOAD;
import static jdk.internal.org.objectweb.asm.Opcodes.IASTORE;
import static jdk.internal.org.objectweb.asm.Opcodes.ICONST_0;
import static jdk.internal.org.objectweb.asm.Opcodes.ILOAD;
+import static jdk.internal.org.objectweb.asm.Opcodes.INVOKEINTERFACE;
import static jdk.internal.org.objectweb.asm.Opcodes.INVOKESPECIAL;
import static jdk.internal.org.objectweb.asm.Opcodes.INVOKESTATIC;
import static jdk.internal.org.objectweb.asm.Opcodes.INVOKEVIRTUAL;
@@ -347,6 +348,10 @@ public class MethodGenerator extends MethodVisitor {
}
// invokes, field get/sets
+ void invokeInterface(final String owner, final String method, final String desc) {
+ super.visitMethodInsn(INVOKEINTERFACE, owner, method, desc);
+ }
+
void invokeVirtual(final String owner, final String method, final String desc) {
super.visitMethodInsn(INVOKEVIRTUAL, owner, method, desc);
}
diff --git a/nashorn/buildtools/nasgen/src/jdk/nashorn/internal/tools/nasgen/PrototypeGenerator.java b/nashorn/buildtools/nasgen/src/jdk/nashorn/internal/tools/nasgen/PrototypeGenerator.java
index 17750cd1bbf..98048a294b2 100644
--- a/nashorn/buildtools/nasgen/src/jdk/nashorn/internal/tools/nasgen/PrototypeGenerator.java
+++ b/nashorn/buildtools/nasgen/src/jdk/nashorn/internal/tools/nasgen/PrototypeGenerator.java
@@ -30,11 +30,11 @@ import static jdk.internal.org.objectweb.asm.Opcodes.ACC_SUPER;
import static jdk.internal.org.objectweb.asm.Opcodes.V1_7;
import static jdk.nashorn.internal.tools.nasgen.StringConstants.DEFAULT_INIT_DESC;
import static jdk.nashorn.internal.tools.nasgen.StringConstants.INIT;
-import static jdk.nashorn.internal.tools.nasgen.StringConstants.MAP_DESC;
-import static jdk.nashorn.internal.tools.nasgen.StringConstants.MAP_DUPLICATE;
-import static jdk.nashorn.internal.tools.nasgen.StringConstants.MAP_DUPLICATE_DESC;
-import static jdk.nashorn.internal.tools.nasgen.StringConstants.MAP_FIELD_NAME;
-import static jdk.nashorn.internal.tools.nasgen.StringConstants.MAP_TYPE;
+import static jdk.nashorn.internal.tools.nasgen.StringConstants.PROPERTYMAP_DESC;
+import static jdk.nashorn.internal.tools.nasgen.StringConstants.PROPERTYMAP_DUPLICATE;
+import static jdk.nashorn.internal.tools.nasgen.StringConstants.PROPERTYMAP_DUPLICATE_DESC;
+import static jdk.nashorn.internal.tools.nasgen.StringConstants.PROPERTYMAP_FIELD_NAME;
+import static jdk.nashorn.internal.tools.nasgen.StringConstants.PROPERTYMAP_TYPE;
import static jdk.nashorn.internal.tools.nasgen.StringConstants.OBJECT_DESC;
import static jdk.nashorn.internal.tools.nasgen.StringConstants.PROTOTYPEOBJECT_TYPE;
import static jdk.nashorn.internal.tools.nasgen.StringConstants.PROTOTYPE_SUFFIX;
@@ -67,6 +67,7 @@ public class PrototypeGenerator extends ClassGenerator {
// add
emitStaticInitializer();
}
+
// add
emitConstructor();
@@ -106,7 +107,7 @@ public class PrototypeGenerator extends ClassGenerator {
private void emitStaticInitializer() {
final MethodGenerator mi = makeStaticInitializer();
- emitStaticInitPrefix(mi, className);
+ emitStaticInitPrefix(mi, className, memberCount);
for (final MemberInfo memInfo : scriptClassInfo.getMembers()) {
if (memInfo.isPrototypeFunction() || memInfo.isPrototypeProperty()) {
linkerAddGetterSetter(mi, className, memInfo);
@@ -124,10 +125,10 @@ public class PrototypeGenerator extends ClassGenerator {
mi.loadThis();
if (memberCount > 0) {
// call "super(map$)"
- mi.getStatic(className, MAP_FIELD_NAME, MAP_DESC);
+ mi.getStatic(className, PROPERTYMAP_FIELD_NAME, PROPERTYMAP_DESC);
// make sure we use duplicated PropertyMap so that original map
- // stays intact and so can be used for many globals in same context
- mi.invokeVirtual(MAP_TYPE, MAP_DUPLICATE, MAP_DUPLICATE_DESC);
+ // stays intact and so can be used for many global.
+ mi.invokeVirtual(PROPERTYMAP_TYPE, PROPERTYMAP_DUPLICATE, PROPERTYMAP_DUPLICATE_DESC);
mi.invokeSpecial(PROTOTYPEOBJECT_TYPE, INIT, SCRIPTOBJECT_INIT_DESC);
// initialize Function type fields
initFunctionFields(mi);
diff --git a/nashorn/buildtools/nasgen/src/jdk/nashorn/internal/tools/nasgen/ScriptClassInstrumentor.java b/nashorn/buildtools/nasgen/src/jdk/nashorn/internal/tools/nasgen/ScriptClassInstrumentor.java
index ffeb90bea3e..1622e02b469 100644
--- a/nashorn/buildtools/nasgen/src/jdk/nashorn/internal/tools/nasgen/ScriptClassInstrumentor.java
+++ b/nashorn/buildtools/nasgen/src/jdk/nashorn/internal/tools/nasgen/ScriptClassInstrumentor.java
@@ -37,10 +37,7 @@ import static jdk.nashorn.internal.tools.nasgen.StringConstants.$CLINIT$;
import static jdk.nashorn.internal.tools.nasgen.StringConstants.CLINIT;
import static jdk.nashorn.internal.tools.nasgen.StringConstants.DEFAULT_INIT_DESC;
import static jdk.nashorn.internal.tools.nasgen.StringConstants.INIT;
-import static jdk.nashorn.internal.tools.nasgen.StringConstants.MAP_DESC;
-import static jdk.nashorn.internal.tools.nasgen.StringConstants.MAP_FIELD_NAME;
import static jdk.nashorn.internal.tools.nasgen.StringConstants.OBJECT_DESC;
-import static jdk.nashorn.internal.tools.nasgen.StringConstants.SCRIPTOBJECT_INIT_DESC;
import static jdk.nashorn.internal.tools.nasgen.StringConstants.SCRIPTOBJECT_TYPE;
import java.io.BufferedInputStream;
@@ -159,14 +156,7 @@ public class ScriptClassInstrumentor extends ClassVisitor {
public void visitMethodInsn(final int opcode, final String owner, final String name, final String desc) {
if (isConstructor && opcode == INVOKESPECIAL &&
INIT.equals(name) && SCRIPTOBJECT_TYPE.equals(owner)) {
-
- // replace call to empty super-constructor with one passing PropertyMap argument
- if (DEFAULT_INIT_DESC.equals(desc)) {
- super.visitFieldInsn(GETSTATIC, scriptClassInfo.getJavaName(), MAP_FIELD_NAME, MAP_DESC);
- super.visitMethodInsn(INVOKESPECIAL, SCRIPTOBJECT_TYPE, INIT, SCRIPTOBJECT_INIT_DESC);
- } else {
- super.visitMethodInsn(opcode, owner, name, desc);
- }
+ super.visitMethodInsn(opcode, owner, name, desc);
if (memberCount > 0) {
// initialize @Property fields if needed
@@ -256,7 +246,7 @@ public class ScriptClassInstrumentor extends ClassVisitor {
}
// Now generate $clinit$
final MethodGenerator mi = ClassGenerator.makeStaticInitializer(this, $CLINIT$);
- ClassGenerator.emitStaticInitPrefix(mi, className);
+ ClassGenerator.emitStaticInitPrefix(mi, className, memberCount);
if (memberCount > 0) {
for (final MemberInfo memInfo : scriptClassInfo.getMembers()) {
if (memInfo.isInstanceProperty() || memInfo.isInstanceFunction()) {
diff --git a/nashorn/buildtools/nasgen/src/jdk/nashorn/internal/tools/nasgen/StringConstants.java b/nashorn/buildtools/nasgen/src/jdk/nashorn/internal/tools/nasgen/StringConstants.java
index 5a5032f93a9..c4c1ab8d465 100644
--- a/nashorn/buildtools/nasgen/src/jdk/nashorn/internal/tools/nasgen/StringConstants.java
+++ b/nashorn/buildtools/nasgen/src/jdk/nashorn/internal/tools/nasgen/StringConstants.java
@@ -27,10 +27,14 @@ package jdk.nashorn.internal.tools.nasgen;
import java.lang.invoke.MethodHandle;
import java.lang.reflect.Method;
+import java.util.Collection;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
import jdk.internal.org.objectweb.asm.Type;
-import jdk.nashorn.internal.lookup.Lookup;
import jdk.nashorn.internal.objects.PrototypeObject;
import jdk.nashorn.internal.objects.ScriptFunctionImpl;
+import jdk.nashorn.internal.runtime.AccessorProperty;
import jdk.nashorn.internal.runtime.PropertyMap;
import jdk.nashorn.internal.runtime.ScriptFunction;
import jdk.nashorn.internal.runtime.ScriptObject;
@@ -40,15 +44,41 @@ import jdk.nashorn.internal.runtime.ScriptObject;
*/
@SuppressWarnings("javadoc")
public interface StringConstants {
+ // standard jdk types, methods
static final Type TYPE_METHOD = Type.getType(Method.class);
static final Type TYPE_METHODHANDLE = Type.getType(MethodHandle.class);
static final Type TYPE_METHODHANDLE_ARRAY = Type.getType(MethodHandle[].class);
static final Type TYPE_OBJECT = Type.getType(Object.class);
static final Type TYPE_CLASS = Type.getType(Class.class);
static final Type TYPE_STRING = Type.getType(String.class);
+ static final Type TYPE_COLLECTION = Type.getType(Collection.class);
+ static final Type TYPE_COLLECTIONS = Type.getType(Collections.class);
+ static final Type TYPE_ARRAYLIST = Type.getType(ArrayList.class);
+ static final Type TYPE_LIST = Type.getType(List.class);
- // Nashorn types
- static final Type TYPE_LOOKUP = Type.getType(Lookup.class);
+ static final String CLINIT = "";
+ static final String INIT = "";
+ static final String DEFAULT_INIT_DESC = Type.getMethodDescriptor(Type.VOID_TYPE);
+
+ static final String METHODHANDLE_TYPE = TYPE_METHODHANDLE.getInternalName();
+ static final String OBJECT_TYPE = TYPE_OBJECT.getInternalName();
+ static final String OBJECT_DESC = TYPE_OBJECT.getDescriptor();
+ static final String OBJECT_ARRAY_DESC = Type.getDescriptor(Object[].class);
+ static final String ARRAYLIST_TYPE = TYPE_ARRAYLIST.getInternalName();
+ static final String COLLECTION_TYPE = TYPE_COLLECTION.getInternalName();
+ static final String COLLECTIONS_TYPE = TYPE_COLLECTIONS.getInternalName();
+
+ // java.util.Collection.add(Object)
+ static final String COLLECTION_ADD = "add";
+ static final String COLLECTION_ADD_DESC = Type.getMethodDescriptor(Type.BOOLEAN_TYPE, TYPE_OBJECT);
+ // java.util.ArrayList.(int)
+ static final String ARRAYLIST_INIT_DESC = Type.getMethodDescriptor(Type.VOID_TYPE, Type.INT_TYPE);
+ // java.util.Collections.EMPTY_LIST
+ static final String COLLECTIONS_EMPTY_LIST = "EMPTY_LIST";
+ static final String LIST_DESC = TYPE_LIST.getDescriptor();
+
+ // Nashorn types, methods
+ static final Type TYPE_ACCESSORPROPERTY = Type.getType(AccessorProperty.class);
static final Type TYPE_PROPERTYMAP = Type.getType(PropertyMap.class);
static final Type TYPE_PROTOTYPEOBJECT = Type.getType(PrototypeObject.class);
static final Type TYPE_SCRIPTFUNCTION = Type.getType(ScriptFunction.class);
@@ -57,54 +87,56 @@ public interface StringConstants {
static final String PROTOTYPE_SUFFIX = "$Prototype";
static final String CONSTRUCTOR_SUFFIX = "$Constructor";
+
// This field name is known to Nashorn runtime (Context).
// Synchronize the name change, if needed at all.
- static final String MAP_FIELD_NAME = "$nasgenmap$";
+ static final String PROPERTYMAP_FIELD_NAME = "$nasgenmap$";
static final String $CLINIT$ = "$clinit$";
- static final String CLINIT = "";
- static final String INIT = "";
- static final String DEFAULT_INIT_DESC = Type.getMethodDescriptor(Type.VOID_TYPE);
- static final String SCRIPTOBJECT_INIT_DESC = Type.getMethodDescriptor(Type.VOID_TYPE, TYPE_PROPERTYMAP);
+ // AccessorProperty
+ static final String ACCESSORPROPERTY_TYPE = TYPE_ACCESSORPROPERTY.getInternalName();
+ static final String ACCESSORPROPERTY_CREATE = "create";
+ static final String ACCESSORPROPERTY_CREATE_DESC =
+ Type.getMethodDescriptor(TYPE_ACCESSORPROPERTY, TYPE_STRING, Type.INT_TYPE, TYPE_METHODHANDLE, TYPE_METHODHANDLE);
- static final String METHODHANDLE_TYPE = TYPE_METHODHANDLE.getInternalName();
+ // PropertyMap
+ static final String PROPERTYMAP_TYPE = TYPE_PROPERTYMAP.getInternalName();
+ static final String PROPERTYMAP_DESC = TYPE_PROPERTYMAP.getDescriptor();
+ static final String PROPERTYMAP_NEWMAP = "newMap";
+ static final String PROPERTYMAP_NEWMAP_DESC = Type.getMethodDescriptor(TYPE_PROPERTYMAP, TYPE_COLLECTION);
+ static final String PROPERTYMAP_DUPLICATE = "duplicate";
+ static final String PROPERTYMAP_DUPLICATE_DESC = Type.getMethodDescriptor(TYPE_PROPERTYMAP);
+ static final String PROPERTYMAP_SETISSHARED = "setIsShared";
+ static final String PROPERTYMAP_SETISSHARED_DESC = Type.getMethodDescriptor(TYPE_PROPERTYMAP);
- static final String OBJECT_TYPE = TYPE_OBJECT.getInternalName();
- static final String OBJECT_DESC = TYPE_OBJECT.getDescriptor();
- static final String OBJECT_ARRAY_DESC = Type.getDescriptor(Object[].class);
+ // PrototypeObject
+ static final String PROTOTYPEOBJECT_TYPE = TYPE_PROTOTYPEOBJECT.getInternalName();
+ static final String PROTOTYPEOBJECT_SETCONSTRUCTOR = "setConstructor";
+ static final String PROTOTYPEOBJECT_SETCONSTRUCTOR_DESC = Type.getMethodDescriptor(Type.VOID_TYPE, TYPE_OBJECT, TYPE_OBJECT);
+ // ScriptFunction
static final String SCRIPTFUNCTION_TYPE = TYPE_SCRIPTFUNCTION.getInternalName();
+ static final String SCRIPTFUNCTION_SETARITY = "setArity";
+ static final String SCRIPTFUNCTION_SETARITY_DESC = Type.getMethodDescriptor(Type.VOID_TYPE, Type.INT_TYPE);
+ static final String SCRIPTFUNCTION_SETPROTOTYPE = "setPrototype";
+ static final String SCRIPTFUNCTION_SETPROTOTYPE_DESC = Type.getMethodDescriptor(Type.VOID_TYPE, TYPE_OBJECT);
+
+ // ScriptFunctionImpl
static final String SCRIPTFUNCTIONIMPL_TYPE = TYPE_SCRIPTFUNCTIONIMPL.getInternalName();
static final String SCRIPTFUNCTIONIMPL_MAKEFUNCTION = "makeFunction";
static final String SCRIPTFUNCTIONIMPL_MAKEFUNCTION_DESC =
Type.getMethodDescriptor(TYPE_SCRIPTFUNCTION, TYPE_STRING, TYPE_METHODHANDLE);
static final String SCRIPTFUNCTIONIMPL_MAKEFUNCTION_SPECS_DESC =
Type.getMethodDescriptor(TYPE_SCRIPTFUNCTION, TYPE_STRING, TYPE_METHODHANDLE, TYPE_METHODHANDLE_ARRAY);
-
static final String SCRIPTFUNCTIONIMPL_INIT_DESC3 =
Type.getMethodDescriptor(Type.VOID_TYPE, TYPE_STRING, TYPE_METHODHANDLE, TYPE_METHODHANDLE_ARRAY);
static final String SCRIPTFUNCTIONIMPL_INIT_DESC4 =
Type.getMethodDescriptor(Type.VOID_TYPE, TYPE_STRING, TYPE_METHODHANDLE, TYPE_PROPERTYMAP, TYPE_METHODHANDLE_ARRAY);
- static final String SCRIPTFUNCTION_SETARITY = "setArity";
- static final String SCRIPTFUNCTION_SETARITY_DESC = Type.getMethodDescriptor(Type.VOID_TYPE, Type.INT_TYPE);
- static final String SCRIPTFUNCTION_SETPROTOTYPE = "setPrototype";
- static final String SCRIPTFUNCTION_SETPROTOTYPE_DESC = Type.getMethodDescriptor(Type.VOID_TYPE, TYPE_OBJECT);
- static final String PROTOTYPEOBJECT_TYPE = TYPE_PROTOTYPEOBJECT.getInternalName();
- static final String PROTOTYPEOBJECT_SETCONSTRUCTOR = "setConstructor";
- static final String PROTOTYPEOBJECT_SETCONSTRUCTOR_DESC = Type.getMethodDescriptor(Type.VOID_TYPE, TYPE_OBJECT, TYPE_OBJECT);
+
+ // ScriptObject
static final String SCRIPTOBJECT_TYPE = TYPE_SCRIPTOBJECT.getInternalName();
- static final String MAP_TYPE = TYPE_PROPERTYMAP.getInternalName();
- static final String MAP_DESC = TYPE_PROPERTYMAP.getDescriptor();
- static final String MAP_NEWMAP = "newMap";
- static final String MAP_NEWMAP_DESC = Type.getMethodDescriptor(TYPE_PROPERTYMAP, TYPE_CLASS);
- static final String MAP_DUPLICATE = "duplicate";
- static final String MAP_DUPLICATE_DESC = Type.getMethodDescriptor(TYPE_PROPERTYMAP);
- static final String MAP_SETFLAGS = "setFlags";
- static final String LOOKUP_TYPE = TYPE_LOOKUP.getInternalName();
- static final String LOOKUP_GETMETHOD = "getMethod";
- static final String LOOKUP_NEWPROPERTY = "newProperty";
- static final String LOOKUP_NEWPROPERTY_DESC =
- Type.getMethodDescriptor(TYPE_PROPERTYMAP, TYPE_PROPERTYMAP, TYPE_STRING, Type.INT_TYPE, TYPE_METHODHANDLE, TYPE_METHODHANDLE);
+ static final String SCRIPTOBJECT_INIT_DESC = Type.getMethodDescriptor(Type.VOID_TYPE, TYPE_PROPERTYMAP);
+
static final String GETTER_PREFIX = "G$";
static final String SETTER_PREFIX = "S$";
diff --git a/nashorn/docs/JavaScriptingProgrammersGuide.html b/nashorn/docs/JavaScriptingProgrammersGuide.html
index 18ae823d82e..dd74d74903e 100644
--- a/nashorn/docs/JavaScriptingProgrammersGuide.html
+++ b/nashorn/docs/JavaScriptingProgrammersGuide.html
@@ -501,14 +501,19 @@ or
var anArrayListWithSize = new ArrayList(16)
-In the special case of inner classes, you need to use the JVM fully qualified name, meaning using $ sign in the class name:
+In the special case of inner classes, you can either use the JVM fully qualified name, meaning using the dollar sign in the class name, or you can use the dot:
var ftype = Java.type("java.awt.geom.Arc2D$Float")
+and
+
+
+ var ftype = Java.type("java.awt.geom.Arc2D.Float")
+
-However, once you retrieved the outer class, you can access the inner class as a property on it:
+both work. Note however that using the dollar sign is faster, as Java.type first tries to resolve the class name as it is originally specified, and the internal JVM names for inner classes use the dollar sign. If you use the dot, Java.type will internally get a ClassNotFoundException and subsequently retry by changing the last dot to dollar sign. As a matter of fact, it'll keep replacing dots with dollar signs until it either successfully loads the class or runs out of all dots in the name. This way it can correctly resolve and load even multiply nested inner classes with the dot notation. Again, this will be slower than using the dollar signs in the name. An alternative way to access the inner class is as a property of the outer class:
var arctype = Java.type("java.awt.geom.Arc2D")
diff --git a/nashorn/make/build-nasgen.xml b/nashorn/make/build-nasgen.xml
index a50d41e02c3..9dca5505316 100644
--- a/nashorn/make/build-nasgen.xml
+++ b/nashorn/make/build-nasgen.xml
@@ -42,11 +42,6 @@
-
-
-
-
-
@@ -66,7 +61,6 @@
-
@@ -75,7 +69,6 @@
-
diff --git a/nashorn/make/build.xml b/nashorn/make/build.xml
index 7e2d999d328..da2ded1ea1d 100644
--- a/nashorn/make/build.xml
+++ b/nashorn/make/build.xml
@@ -100,7 +100,8 @@
target="${javac.target}"
debug="${javac.debug}"
encoding="${javac.encoding}"
- includeantruntime="false">
+ includeantruntime="false" fork="true">
+
@@ -235,44 +236,31 @@
-
+
-
-
-
-
-
-
-
+grant codeBase "file:/${basedir}/${nashorn.internal.tests.jar}" {
+ permission java.security.AllPermission;
+};
-
-
-
-
-
-
-
+grant codeBase "file:/${basedir}/${file.reference.testng.jar}" {
+ permission java.security.AllPermission;
+};
-
-
-
-
-
-
-
+grant codeBase "file:/${basedir}/test/script/trusted/*" {
+ permission java.security.AllPermission;
+};
-
-
-
-
-
-
-
-
-
-
-
-
+grant codeBase "file:/${basedir}/test/script/basic/*" {
+ permission java.io.FilePermission "${basedir}/test/script/-", "read";
+ permission java.io.FilePermission "$${user.dir}", "read";
+ permission java.util.PropertyPermission "user.dir", "read";
+ permission java.util.PropertyPermission "nashorn.test.*", "read";
+};
+
+grant codeBase "file:/${basedir}/test/script/basic/JDK-8010946-privileged.js" {
+ permission java.util.PropertyPermission "java.security.policy", "read";
+};
+ \////
diff --git a/nashorn/make/code_coverage.xml b/nashorn/make/code_coverage.xml
index 3e2860f8d9d..dea03099e36 100644
--- a/nashorn/make/code_coverage.xml
+++ b/nashorn/make/code_coverage.xml
@@ -60,16 +60,8 @@
-
-
-
-
-
-
-
-
diff --git a/nashorn/make/project.properties b/nashorn/make/project.properties
index 66bbdbebab7..dbd9efce80c 100644
--- a/nashorn/make/project.properties
+++ b/nashorn/make/project.properties
@@ -200,6 +200,9 @@ test262-test-sys-prop.test.failed.list.file=${build.dir}/test/failedTests
# test262 test frameworks
test262-test-sys-prop.test.js.framework=\
+ --class-cache-size=0 \
+ --no-java \
+ --no-typed-arrays \
-timezone=PST \
${test.script.dir}/test262.js \
${test262.dir}/test/harness/framework.js \
diff --git a/nashorn/makefiles/BuildNashorn.gmk b/nashorn/makefiles/BuildNashorn.gmk
index d08f7e8fa6f..96bedf44ac4 100644
--- a/nashorn/makefiles/BuildNashorn.gmk
+++ b/nashorn/makefiles/BuildNashorn.gmk
@@ -71,7 +71,6 @@ $(eval $(call SetupJavaCompilation,BUILD_NASGEN,\
$(BUILD_NASGEN): $(BUILD_NASHORN)
# Copy classes to final classes dir and run nasgen to modify classes in jdk.nashorn.internal.objects package
-# Finally rename classes in jdk.nashorn.internal.objects package
$(NASHORN_OUTPUTDIR)/classes/_the.nasgen.run: $(BUILD_NASGEN)
$(ECHO) Running nasgen
$(MKDIR) -p $(@D)
@@ -80,9 +79,6 @@ $(NASHORN_OUTPUTDIR)/classes/_the.nasgen.run: $(BUILD_NASGEN)
$(FIXPATH) $(JAVA) \
-cp "$(NASHORN_OUTPUTDIR)/nasgen_classes$(PATH_SEP)$(NASHORN_OUTPUTDIR)/nashorn_classes" \
jdk.nashorn.internal.tools.nasgen.Main $(@D) jdk.nashorn.internal.objects $(@D)
- for f in `$(FIND) $(@D)/jdk/nashorn/internal/objects/ -name "*.class"`; do \
- mv "$$f" `$(ECHO) "$$f" | $(SED) "s/\.class$$/\.clazz/"`; \
- done
$(TOUCH) $@
# Version file needs to be processed with version numbers
@@ -104,7 +100,7 @@ $(eval $(call SetupArchive,BUILD_NASHORN_JAR,\
$(NASHORN_OUTPUTDIR)/classes/_the.nasgen.run \
$(VERSION_FILE),\
SRCS:=$(NASHORN_OUTPUTDIR)/classes,\
- SUFFIXES:=.class .clazz .js .properties Factory,\
+ SUFFIXES:=.class .js .properties Factory,\
MANIFEST:=$(NASHORN_TOPDIR)/src/META-INF/MANIFEST.MF,\
EXTRA_MANIFEST_ATTR:=$(MANIFEST_ATTRIBUTES),\
SKIP_METAINF:=true,\
diff --git a/nashorn/src/jdk/internal/dynalink/beans/AbstractJavaLinker.java b/nashorn/src/jdk/internal/dynalink/beans/AbstractJavaLinker.java
index 702c1509fd4..f541fa65d2a 100644
--- a/nashorn/src/jdk/internal/dynalink/beans/AbstractJavaLinker.java
+++ b/nashorn/src/jdk/internal/dynalink/beans/AbstractJavaLinker.java
@@ -86,7 +86,10 @@ package jdk.internal.dynalink.beans;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
+import java.lang.reflect.AccessibleObject;
+import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
+import java.lang.reflect.Member;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.HashMap;
@@ -109,10 +112,11 @@ import jdk.internal.dynalink.support.Lookup;
* @author Attila Szegedi
*/
abstract class AbstractJavaLinker implements GuardingDynamicLinker {
+
final Class> clazz;
private final MethodHandle classGuard;
private final MethodHandle assignableGuard;
- private final Map propertyGetters = new HashMap<>();
+ private final Map propertyGetters = new HashMap<>();
private final Map propertySetters = new HashMap<>();
private final Map methods = new HashMap<>();
@@ -129,22 +133,19 @@ abstract class AbstractJavaLinker implements GuardingDynamicLinker {
// Add methods and properties
for(Method method: introspector.getMethods()) {
final String name = method.getName();
- final MethodHandle methodHandle = introspector.unreflect(method);
// Add method
- addMember(name, methodHandle, methods);
+ addMember(name, method, methods);
// Add the method as a property getter and/or setter
if(name.startsWith("get") && name.length() > 3 && method.getParameterTypes().length == 0) {
// Property getter
- setPropertyGetter(decapitalize(name.substring(3)), introspector.unreflect(
- getMostGenericGetter(method)), ValidationType.INSTANCE_OF);
+ setPropertyGetter(method, 3);
} else if(name.startsWith("is") && name.length() > 2 && method.getParameterTypes().length == 0 &&
method.getReturnType() == boolean.class) {
// Boolean property getter
- setPropertyGetter(decapitalize(name.substring(2)), introspector.unreflect(
- getMostGenericGetter(method)), ValidationType.INSTANCE_OF);
+ setPropertyGetter(method, 2);
} else if(name.startsWith("set") && name.length() > 3 && method.getParameterTypes().length == 1) {
// Property setter
- addMember(decapitalize(name.substring(3)), methodHandle, propertySetters);
+ addMember(decapitalize(name.substring(3)), method, propertySetters);
}
}
@@ -156,7 +157,8 @@ abstract class AbstractJavaLinker implements GuardingDynamicLinker {
setPropertyGetter(name, introspector.unreflectGetter(field), ValidationType.EXACT_CLASS);
}
if(!(Modifier.isFinal(field.getModifiers()) || propertySetters.containsKey(name))) {
- addMember(name, introspector.unreflectSetter(field), propertySetters);
+ addMember(name, new SimpleDynamicMethod(introspector.unreflectSetter(field), clazz, name),
+ propertySetters);
}
}
@@ -192,38 +194,119 @@ abstract class AbstractJavaLinker implements GuardingDynamicLinker {
abstract FacetIntrospector createFacetIntrospector();
- void setPropertyGetter(String name, MethodHandle handle, ValidationType validationType) {
- propertyGetters.put(name, new AnnotatedMethodHandle(handle, validationType));
+ /**
+ * Sets the specified dynamic method to be the property getter for the specified property. Note that you can only
+ * use this when you're certain that the method handle does not belong to a caller-sensitive method. For properties
+ * that are caller-sensitive, you must use {@link #setPropertyGetter(String, SingleDynamicMethod, ValidationType)}
+ * instead.
+ * @param name name of the property
+ * @param handle the method handle that implements the property getter
+ * @param validationType the validation type for the property
+ */
+ private void setPropertyGetter(String name, SingleDynamicMethod handle, ValidationType validationType) {
+ propertyGetters.put(name, new AnnotatedDynamicMethod(handle, validationType));
}
- private void addMember(String name, MethodHandle mh, Map methodMap) {
+ /**
+ * Sets the specified reflective method to be the property getter for the specified property.
+ * @param getter the getter method
+ * @param prefixLen the getter prefix in the method name; should be 3 for getter names starting with "get" and 2 for
+ * names starting with "is".
+ */
+ private void setPropertyGetter(Method getter, int prefixLen) {
+ setPropertyGetter(decapitalize(getter.getName().substring(prefixLen)), createDynamicMethod(
+ getMostGenericGetter(getter)), ValidationType.INSTANCE_OF);
+ }
+
+ /**
+ * Sets the specified method handle to be the property getter for the specified property. Note that you can only
+ * use this when you're certain that the method handle does not belong to a caller-sensitive method. For properties
+ * that are caller-sensitive, you must use {@link #setPropertyGetter(String, SingleDynamicMethod, ValidationType)}
+ * instead.
+ * @param name name of the property
+ * @param handle the method handle that implements the property getter
+ * @param validationType the validation type for the property
+ */
+ void setPropertyGetter(String name, MethodHandle handle, ValidationType validationType) {
+ setPropertyGetter(name, new SimpleDynamicMethod(handle, clazz, name), validationType);
+ }
+
+ private void addMember(String name, AccessibleObject ao, Map methodMap) {
+ addMember(name, createDynamicMethod(ao), methodMap);
+ }
+
+ private void addMember(String name, SingleDynamicMethod method, Map methodMap) {
final DynamicMethod existingMethod = methodMap.get(name);
- final DynamicMethod newMethod = addMember(mh, existingMethod, clazz, name);
+ final DynamicMethod newMethod = mergeMethods(method, existingMethod, clazz, name);
if(newMethod != existingMethod) {
methodMap.put(name, newMethod);
}
}
- static DynamicMethod createDynamicMethod(Iterable methodHandles, Class> clazz, String name) {
+ /**
+ * Given one or more reflective methods or constructors, creates a dynamic method that represents them all. The
+ * methods should represent all overloads of the same name (or all constructors of the class).
+ * @param members the reflective members
+ * @param clazz the class declaring the reflective members
+ * @param name the common name of the reflective members.
+ * @return a dynamic method representing all the specified reflective members.
+ */
+ static DynamicMethod createDynamicMethod(Iterable extends AccessibleObject> members, Class> clazz, String name) {
DynamicMethod dynMethod = null;
- for(MethodHandle methodHandle: methodHandles) {
- dynMethod = addMember(methodHandle, dynMethod, clazz, name);
+ for(AccessibleObject method: members) {
+ dynMethod = mergeMethods(createDynamicMethod(method), dynMethod, clazz, name);
}
return dynMethod;
}
- private static DynamicMethod addMember(MethodHandle mh, DynamicMethod existing, Class> clazz, String name) {
+ /**
+ * Given a reflective method or a constructor, creates a dynamic method that represents it. This method will
+ * distinguish between caller sensitive and ordinary methods/constructors, and create appropriate caller sensitive
+ * dynamic method when needed.
+ * @param m the reflective member
+ * @return the single dynamic method representing the reflective member
+ */
+ private static SingleDynamicMethod createDynamicMethod(AccessibleObject m) {
+ if(CallerSensitiveDetector.isCallerSensitive(m)) {
+ return new CallerSensitiveDynamicMethod(m);
+ }
+ final Member member = (Member)m;
+ return new SimpleDynamicMethod(unreflectSafely(m), member.getDeclaringClass(), member.getName());
+ }
+
+ /**
+ * Unreflects a method handle from a Method or a Constructor using safe (zero-privilege) unreflection. Should be
+ * only used for methods and constructors that are not caller sensitive. If a caller sensitive method were
+ * unreflected through this mechanism, it would not be a security issue, but would be bound to the zero-privilege
+ * unreflector as its caller, and thus completely useless.
+ * @param m the method or constructor
+ * @return the method handle
+ */
+ private static MethodHandle unreflectSafely(AccessibleObject m) {
+ if(m instanceof Method) {
+ final Method reflMethod = (Method)m;
+ final MethodHandle handle = SafeUnreflector.unreflect(reflMethod);
+ if(Modifier.isStatic(reflMethod.getModifiers())) {
+ return StaticClassIntrospector.editStaticMethodHandle(handle);
+ }
+ return handle;
+ }
+ return StaticClassIntrospector.editConstructorMethodHandle(SafeUnreflector.unreflectConstructor(
+ (Constructor>)m));
+ }
+
+ private static DynamicMethod mergeMethods(SingleDynamicMethod method, DynamicMethod existing, Class> clazz, String name) {
if(existing == null) {
- return new SimpleDynamicMethod(mh, clazz, name);
- } else if(existing.contains(mh)) {
+ return method;
+ } else if(existing.contains(method)) {
return existing;
- } else if(existing instanceof SimpleDynamicMethod) {
+ } else if(existing instanceof SingleDynamicMethod) {
final OverloadedDynamicMethod odm = new OverloadedDynamicMethod(clazz, name);
- odm.addMethod(((SimpleDynamicMethod)existing));
- odm.addMethod(mh);
+ odm.addMethod(((SingleDynamicMethod)existing));
+ odm.addMethod(method);
return odm;
} else if(existing instanceof OverloadedDynamicMethod) {
- ((OverloadedDynamicMethod)existing).addMethod(mh);
+ ((OverloadedDynamicMethod)existing).addMethod(method);
return existing;
}
throw new AssertionError();
@@ -296,7 +379,7 @@ abstract class AbstractJavaLinker implements GuardingDynamicLinker {
private GuardedInvocation getCallPropWithThis(CallSiteDescriptor callSiteDescriptor, LinkerServices linkerServices) {
switch(callSiteDescriptor.getNameTokenCount()) {
case 3: {
- return createGuardedDynamicMethodInvocation(callSiteDescriptor.getMethodType(), linkerServices,
+ return createGuardedDynamicMethodInvocation(callSiteDescriptor, linkerServices,
callSiteDescriptor.getNameToken(CallSiteDescriptor.NAME_OPERAND), methods);
}
default: {
@@ -305,16 +388,16 @@ abstract class AbstractJavaLinker implements GuardingDynamicLinker {
}
}
- private GuardedInvocation createGuardedDynamicMethodInvocation(MethodType callSiteType,
+ private GuardedInvocation createGuardedDynamicMethodInvocation(CallSiteDescriptor callSiteDescriptor,
LinkerServices linkerServices, String methodName, Map methodMap){
- final MethodHandle inv = getDynamicMethodInvocation(callSiteType, linkerServices, methodName, methodMap);
- return inv == null ? null : new GuardedInvocation(inv, getClassGuard(callSiteType));
+ final MethodHandle inv = getDynamicMethodInvocation(callSiteDescriptor, linkerServices, methodName, methodMap);
+ return inv == null ? null : new GuardedInvocation(inv, getClassGuard(callSiteDescriptor.getMethodType()));
}
- private static MethodHandle getDynamicMethodInvocation(MethodType callSiteType, LinkerServices linkerServices,
- String methodName, Map methodMap) {
+ private static MethodHandle getDynamicMethodInvocation(CallSiteDescriptor callSiteDescriptor,
+ LinkerServices linkerServices, String methodName, Map methodMap) {
final DynamicMethod dynaMethod = getDynamicMethod(methodName, methodMap);
- return dynaMethod != null ? dynaMethod.getInvocation(callSiteType, linkerServices) : null;
+ return dynaMethod != null ? dynaMethod.getInvocation(callSiteDescriptor, linkerServices) : null;
}
private static DynamicMethod getDynamicMethod(String methodName, Map methodMap) {
@@ -322,13 +405,13 @@ abstract class AbstractJavaLinker implements GuardingDynamicLinker {
return dynaMethod != null ? dynaMethod : getExplicitSignatureDynamicMethod(methodName, methodMap);
}
- private static SimpleDynamicMethod getExplicitSignatureDynamicMethod(String methodName,
+ private static SingleDynamicMethod getExplicitSignatureDynamicMethod(String methodName,
Map methodsMap) {
// What's below is meant to support the "name(type, type, ...)" syntax that programmers can use in a method name
// to manually pin down an exact overloaded variant. This is not usually required, as the overloaded method
// resolution works correctly in almost every situation. However, in presence of many language-specific
// conversions with a radically dynamic language, most overloaded methods will end up being constantly selected
- // at invocation time, so a programmer knowledgable of the situation might choose to pin down an exact overload
+ // at invocation time, so a programmer knowledgeable of the situation might choose to pin down an exact overload
// for performance reasons.
// Is the method name lexically of the form "name(types)"?
@@ -377,8 +460,8 @@ abstract class AbstractJavaLinker implements GuardingDynamicLinker {
final MethodType setterType = type.dropParameterTypes(1, 2);
// Bind property setter handle to the expected setter type and linker services. Type is
// MethodHandle(Object, String, Object)
- final MethodHandle boundGetter = MethodHandles.insertArguments(getPropertySetterHandle, 0, setterType,
- linkerServices);
+ final MethodHandle boundGetter = MethodHandles.insertArguments(getPropertySetterHandle, 0,
+ CallSiteDescriptorFactory.dropParameterTypes(callSiteDescriptor, 1, 2), linkerServices);
// Cast getter to MethodHandle(O, N, V)
final MethodHandle typedGetter = linkerServices.asType(boundGetter, type.changeReturnType(
@@ -415,9 +498,8 @@ abstract class AbstractJavaLinker implements GuardingDynamicLinker {
case 3: {
// Must have two arguments: target object and property value
assertParameterCount(callSiteDescriptor, 2);
- final GuardedInvocation gi = createGuardedDynamicMethodInvocation(callSiteDescriptor.getMethodType(),
- linkerServices, callSiteDescriptor.getNameToken(CallSiteDescriptor.NAME_OPERAND),
- propertySetters);
+ final GuardedInvocation gi = createGuardedDynamicMethodInvocation(callSiteDescriptor, linkerServices,
+ callSiteDescriptor.getNameToken(CallSiteDescriptor.NAME_OPERAND), propertySetters);
// If we have a property setter with this name, this composite operation will always stop here
if(gi != null) {
return new GuardedInvocationComponent(gi, clazz, ValidationType.EXACT_CLASS);
@@ -435,14 +517,13 @@ abstract class AbstractJavaLinker implements GuardingDynamicLinker {
private static final Lookup privateLookup = new Lookup(MethodHandles.lookup());
- private static final MethodHandle IS_ANNOTATED_HANDLE_NOT_NULL = Guards.isNotNull().asType(MethodType.methodType(
- boolean.class, AnnotatedMethodHandle.class));
- private static final MethodHandle CONSTANT_NULL_DROP_ANNOTATED_HANDLE = MethodHandles.dropArguments(
- MethodHandles.constant(Object.class, null), 0, AnnotatedMethodHandle.class);
- private static final MethodHandle GET_ANNOTATED_HANDLE = privateLookup.findGetter(AnnotatedMethodHandle.class,
- "handle", MethodHandle.class);
- private static final MethodHandle GENERIC_PROPERTY_GETTER_HANDLER_INVOKER = MethodHandles.filterArguments(
- MethodHandles.invoker(MethodType.methodType(Object.class, Object.class)), 0, GET_ANNOTATED_HANDLE);
+ private static final MethodHandle IS_ANNOTATED_METHOD_NOT_NULL = Guards.isNotNull().asType(MethodType.methodType(
+ boolean.class, AnnotatedDynamicMethod.class));
+ private static final MethodHandle CONSTANT_NULL_DROP_ANNOTATED_METHOD = MethodHandles.dropArguments(
+ MethodHandles.constant(Object.class, null), 0, AnnotatedDynamicMethod.class);
+ private static final MethodHandle GET_ANNOTATED_METHOD = privateLookup.findVirtual(AnnotatedDynamicMethod.class,
+ "getTarget", MethodType.methodType(MethodHandle.class, MethodHandles.Lookup.class));
+ private static final MethodHandle GETTER_INVOKER = MethodHandles.invoker(MethodType.methodType(Object.class, Object.class));
private GuardedInvocationComponent getPropertyGetter(CallSiteDescriptor callSiteDescriptor,
LinkerServices linkerServices, List ops) throws Exception {
@@ -455,16 +536,20 @@ abstract class AbstractJavaLinker implements GuardingDynamicLinker {
// What's below is basically:
// foldArguments(guardWithTest(isNotNull, invoke(get_handle), null|nextComponent.invocation), get_getter_handle)
// only with a bunch of method signature adjustments. Basically, retrieve method getter
- // AnnotatedMethodHandle; if it is non-null, invoke its "handle" field, otherwise either return null,
+ // AnnotatedDynamicMethod; if it is non-null, invoke its "handle" field, otherwise either return null,
// or delegate to next component's invocation.
final MethodHandle typedGetter = linkerServices.asType(getPropertyGetterHandle, type.changeReturnType(
- AnnotatedMethodHandle.class));
- // Object(AnnotatedMethodHandle, Object)->R(AnnotatedMethodHandle, T0)
- final MethodHandle invokeHandleTyped = linkerServices.asType(GENERIC_PROPERTY_GETTER_HANDLER_INVOKER,
- MethodType.methodType(type.returnType(), AnnotatedMethodHandle.class, type.parameterType(0)));
+ AnnotatedDynamicMethod.class));
+ final MethodHandle callSiteBoundMethodGetter = MethodHandles.insertArguments(
+ GET_ANNOTATED_METHOD, 1, callSiteDescriptor.getLookup());
+ final MethodHandle callSiteBoundInvoker = MethodHandles.filterArguments(GETTER_INVOKER, 0,
+ callSiteBoundMethodGetter);
+ // Object(AnnotatedDynamicMethod, Object)->R(AnnotatedDynamicMethod, T0)
+ final MethodHandle invokeHandleTyped = linkerServices.asType(callSiteBoundInvoker,
+ MethodType.methodType(type.returnType(), AnnotatedDynamicMethod.class, type.parameterType(0)));
// Since it's in the target of a fold, drop the unnecessary second argument
- // R(AnnotatedMethodHandle, T0)->R(AnnotatedMethodHandle, T0, T1)
+ // R(AnnotatedDynamicMethod, T0)->R(AnnotatedDynamicMethod, T0, T1)
final MethodHandle invokeHandleFolded = MethodHandles.dropArguments(invokeHandleTyped, 2,
type.parameterType(1));
final GuardedInvocationComponent nextComponent = getGuardedInvocationComponent(callSiteDescriptor,
@@ -472,19 +557,19 @@ abstract class AbstractJavaLinker implements GuardingDynamicLinker {
final MethodHandle fallbackFolded;
if(nextComponent == null) {
- // Object(AnnotatedMethodHandle)->R(AnnotatedMethodHandle, T0, T1); returns constant null
- fallbackFolded = MethodHandles.dropArguments(CONSTANT_NULL_DROP_ANNOTATED_HANDLE, 1,
- type.parameterList()).asType(type.insertParameterTypes(0, AnnotatedMethodHandle.class));
+ // Object(AnnotatedDynamicMethod)->R(AnnotatedDynamicMethod, T0, T1); returns constant null
+ fallbackFolded = MethodHandles.dropArguments(CONSTANT_NULL_DROP_ANNOTATED_METHOD, 1,
+ type.parameterList()).asType(type.insertParameterTypes(0, AnnotatedDynamicMethod.class));
} else {
- // R(T0, T1)->R(AnnotatedMethodHAndle, T0, T1); adapts the next component's invocation to drop the
+ // R(T0, T1)->R(AnnotatedDynamicMethod, T0, T1); adapts the next component's invocation to drop the
// extra argument resulting from fold
fallbackFolded = MethodHandles.dropArguments(nextComponent.getGuardedInvocation().getInvocation(),
- 0, AnnotatedMethodHandle.class);
+ 0, AnnotatedDynamicMethod.class);
}
- // fold(R(AnnotatedMethodHandle, T0, T1), AnnotatedMethodHandle(T0, T1))
+ // fold(R(AnnotatedDynamicMethod, T0, T1), AnnotatedDynamicMethod(T0, T1))
final MethodHandle compositeGetter = MethodHandles.foldArguments(MethodHandles.guardWithTest(
- IS_ANNOTATED_HANDLE_NOT_NULL, invokeHandleFolded, fallbackFolded), typedGetter);
+ IS_ANNOTATED_METHOD_NOT_NULL, invokeHandleFolded, fallbackFolded), typedGetter);
if(nextComponent == null) {
return getClassGuardedInvocationComponent(compositeGetter, type);
}
@@ -494,13 +579,13 @@ abstract class AbstractJavaLinker implements GuardingDynamicLinker {
// Must have exactly one argument: receiver
assertParameterCount(callSiteDescriptor, 1);
// Fixed name
- final AnnotatedMethodHandle annGetter = propertyGetters.get(callSiteDescriptor.getNameToken(
+ final AnnotatedDynamicMethod annGetter = propertyGetters.get(callSiteDescriptor.getNameToken(
CallSiteDescriptor.NAME_OPERAND));
if(annGetter == null) {
// We have no such property, always delegate to the next component operation
return getGuardedInvocationComponent(callSiteDescriptor, linkerServices, ops);
}
- final MethodHandle getter = annGetter.handle;
+ final MethodHandle getter = annGetter.getInvocation(callSiteDescriptor, linkerServices);
// NOTE: since property getters (not field getters!) are no-arg, we don't have to worry about them being
// overloaded in a subclass. Therefore, we can discover the most abstract superclass that has the
// method, and use that as the guard with Guards.isInstance() for a more stably linked call site. If
@@ -508,6 +593,7 @@ abstract class AbstractJavaLinker implements GuardingDynamicLinker {
// NOTE: No delegation to the next component operation if we have a property with this name, even if its
// value is null.
final ValidationType validationType = annGetter.validationType;
+ // TODO: we aren't using the type that declares the most generic getter here!
return new GuardedInvocationComponent(linkerServices.asType(getter, type), getGuard(validationType,
type), clazz, validationType);
}
@@ -623,14 +709,15 @@ abstract class AbstractJavaLinker implements GuardingDynamicLinker {
// args are dropped; this makes handles with first three args conform to "Object, String, Object" though, which is
// a typical property setter with variable name signature (target, name, value).
private static final MethodHandle GET_PROPERTY_SETTER_HANDLE = MethodHandles.dropArguments(MethodHandles.dropArguments(
- privateLookup.findOwnSpecial("getPropertySetterHandle", MethodHandle.class, MethodType.class,
+ privateLookup.findOwnSpecial("getPropertySetterHandle", MethodHandle.class, CallSiteDescriptor.class,
LinkerServices.class, Object.class), 3, Object.class), 5, Object.class);
// Type is MethodHandle(MethodType, LinkerServices, Object, String, Object)
private final MethodHandle getPropertySetterHandle = GET_PROPERTY_SETTER_HANDLE.bindTo(this);
@SuppressWarnings("unused")
- private MethodHandle getPropertySetterHandle(MethodType setterType, LinkerServices linkerServices, Object id) {
- return getDynamicMethodInvocation(setterType, linkerServices, String.valueOf(id), propertySetters);
+ private MethodHandle getPropertySetterHandle(CallSiteDescriptor setterDescriptor, LinkerServices linkerServices,
+ Object id) {
+ return getDynamicMethodInvocation(setterDescriptor, linkerServices, String.valueOf(id), propertySetters);
}
private static MethodHandle GET_DYNAMIC_METHOD = MethodHandles.dropArguments(privateLookup.findOwnSpecial(
@@ -689,13 +776,24 @@ abstract class AbstractJavaLinker implements GuardingDynamicLinker {
return null;
}
- private static final class AnnotatedMethodHandle {
- final MethodHandle handle;
+ private static final class AnnotatedDynamicMethod {
+ private final SingleDynamicMethod method;
/*private*/ final ValidationType validationType;
- AnnotatedMethodHandle(MethodHandle handle, ValidationType validationType) {
- this.handle = handle;
+ AnnotatedDynamicMethod(SingleDynamicMethod method, ValidationType validationType) {
+ this.method = method;
this.validationType = validationType;
}
+
+ MethodHandle getInvocation(CallSiteDescriptor callSiteDescriptor, LinkerServices linkerServices) {
+ return method.getInvocation(callSiteDescriptor, linkerServices);
+ }
+
+ @SuppressWarnings("unused")
+ MethodHandle getTarget(MethodHandles.Lookup lookup) {
+ MethodHandle inv = method.getTarget(lookup);
+ assert inv != null;
+ return inv;
+ }
}
}
diff --git a/nashorn/src/jdk/internal/dynalink/beans/ApplicableOverloadedMethods.java b/nashorn/src/jdk/internal/dynalink/beans/ApplicableOverloadedMethods.java
index a232caf137a..39a03a8ef96 100644
--- a/nashorn/src/jdk/internal/dynalink/beans/ApplicableOverloadedMethods.java
+++ b/nashorn/src/jdk/internal/dynalink/beans/ApplicableOverloadedMethods.java
@@ -83,7 +83,6 @@
package jdk.internal.dynalink.beans;
-import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodType;
import java.util.LinkedList;
import java.util.List;
@@ -95,7 +94,7 @@ import jdk.internal.dynalink.support.TypeUtilities;
* @author Attila Szegedi
*/
class ApplicableOverloadedMethods {
- private final List methods;
+ private final List methods;
private final boolean varArgs;
/**
@@ -106,10 +105,10 @@ class ApplicableOverloadedMethods {
* @param test applicability test. One of {@link #APPLICABLE_BY_SUBTYPING},
* {@link #APPLICABLE_BY_METHOD_INVOCATION_CONVERSION}, or {@link #APPLICABLE_BY_VARIABLE_ARITY}.
*/
- ApplicableOverloadedMethods(final List methods, final MethodType callSiteType,
+ ApplicableOverloadedMethods(final List methods, final MethodType callSiteType,
final ApplicabilityTest test) {
this.methods = new LinkedList<>();
- for(MethodHandle m: methods) {
+ for(SingleDynamicMethod m: methods) {
if(test.isApplicable(callSiteType, m)) {
this.methods.add(m);
}
@@ -122,7 +121,7 @@ class ApplicableOverloadedMethods {
*
* @return list of all methods.
*/
- List getMethods() {
+ List getMethods() {
return methods;
}
@@ -131,12 +130,12 @@ class ApplicableOverloadedMethods {
*
* @return a list of maximally specific methods.
*/
- List findMaximallySpecificMethods() {
+ List findMaximallySpecificMethods() {
return MaximallySpecific.getMaximallySpecificMethods(methods, varArgs);
}
abstract static class ApplicabilityTest {
- abstract boolean isApplicable(MethodType callSiteType, MethodHandle method);
+ abstract boolean isApplicable(MethodType callSiteType, SingleDynamicMethod method);
}
/**
@@ -144,8 +143,8 @@ class ApplicableOverloadedMethods {
*/
static final ApplicabilityTest APPLICABLE_BY_SUBTYPING = new ApplicabilityTest() {
@Override
- boolean isApplicable(MethodType callSiteType, MethodHandle method) {
- final MethodType methodType = method.type();
+ boolean isApplicable(MethodType callSiteType, SingleDynamicMethod method) {
+ final MethodType methodType = method.getMethodType();
final int methodArity = methodType.parameterCount();
if(methodArity != callSiteType.parameterCount()) {
return false;
@@ -166,8 +165,8 @@ class ApplicableOverloadedMethods {
*/
static final ApplicabilityTest APPLICABLE_BY_METHOD_INVOCATION_CONVERSION = new ApplicabilityTest() {
@Override
- boolean isApplicable(MethodType callSiteType, MethodHandle method) {
- final MethodType methodType = method.type();
+ boolean isApplicable(MethodType callSiteType, SingleDynamicMethod method) {
+ final MethodType methodType = method.getMethodType();
final int methodArity = methodType.parameterCount();
if(methodArity != callSiteType.parameterCount()) {
return false;
@@ -189,11 +188,11 @@ class ApplicableOverloadedMethods {
*/
static final ApplicabilityTest APPLICABLE_BY_VARIABLE_ARITY = new ApplicabilityTest() {
@Override
- boolean isApplicable(MethodType callSiteType, MethodHandle method) {
- if(!method.isVarargsCollector()) {
+ boolean isApplicable(MethodType callSiteType, SingleDynamicMethod method) {
+ if(!method.isVarArgs()) {
return false;
}
- final MethodType methodType = method.type();
+ final MethodType methodType = method.getMethodType();
final int methodArity = methodType.parameterCount();
final int fixArity = methodArity - 1;
final int callSiteArity = callSiteType.parameterCount();
diff --git a/nashorn/src/jdk/internal/dynalink/beans/CallerSensitiveDetector.java b/nashorn/src/jdk/internal/dynalink/beans/CallerSensitiveDetector.java
new file mode 100644
index 00000000000..466bafe65dc
--- /dev/null
+++ b/nashorn/src/jdk/internal/dynalink/beans/CallerSensitiveDetector.java
@@ -0,0 +1,148 @@
+/*
+ * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * This file is available under and governed by the GNU General Public
+ * License version 2 only, as published by the Free Software Foundation.
+ * However, the following notice accompanied the original version of this
+ * file, and Oracle licenses the original version of this file under the BSD
+ * license:
+ */
+/*
+ Copyright 2009-2013 Attila Szegedi
+
+ Licensed under both the Apache License, Version 2.0 (the "Apache License")
+ and the BSD License (the "BSD License"), with licensee being free to
+ choose either of the two at their discretion.
+
+ You may not use this file except in compliance with either the Apache
+ License or the BSD License.
+
+ If you choose to use this file in compliance with the Apache License, the
+ following notice applies to you:
+
+ You may obtain a copy of the Apache License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied. See the License for the specific language governing
+ permissions and limitations under the License.
+
+ If you choose to use this file in compliance with the BSD License, the
+ following notice applies to you:
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are
+ met:
+ * Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+ * Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in the
+ documentation and/or other materials provided with the distribution.
+ * Neither the name of the copyright holder nor the names of
+ contributors may be used to endorse or promote products derived from
+ this software without specific prior written permission.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
+ IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
+ TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
+ PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDER
+ BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+ BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+ WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
+ OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+*/
+
+package jdk.internal.dynalink.beans;
+
+import java.lang.annotation.Annotation;
+import java.lang.reflect.AccessibleObject;
+import sun.reflect.CallerSensitive;
+
+/**
+ * Utility class that determines if a method or constructor is caller sensitive. It actually encapsulates two different
+ * strategies for determining caller sensitivity; a more robust one that works if Dynalink runs as code with access
+ * to {@code sun.reflect} package, and an unprivileged one that is used when Dynalink doesn't have access to that
+ * package. Note that even the unprivileged strategy is ordinarily robust, but it relies on the {@code toString} method
+ * of the annotation. If an attacker were to use a different annotation to spoof the string representation of the
+ * {@code CallerSensitive} annotation, they could designate their own methods as caller sensitive. This however does not
+ * escalate privileges, only causes Dynalink to never cache method handles for such methods, so all it would do would
+ * decrease the performance in linking such methods. In the opposite case when an attacker could trick Dynalink into not
+ * recognizing genuine {@code CallerSensitive} annotations, Dynalink would treat caller sensitive methods as ordinary
+ * methods, and would cache them bound to a zero-privilege delegate as the caller (just what Dynalink did before it
+ * could handle caller-sensitive methods). That would practically render caller-sensitive methods exposed through
+ * Dynalink unusable, but again, can not lead to any privilege escalations. Therefore, even the less robust unprivileged
+ * strategy is safe; the worst thing a successful attack against it can achieve is slight reduction in Dynalink-exposed
+ * functionality or performance.
+ */
+public class CallerSensitiveDetector {
+
+ private static final DetectionStrategy DETECTION_STRATEGY = getDetectionStrategy();
+
+ static boolean isCallerSensitive(AccessibleObject ao) {
+ return DETECTION_STRATEGY.isCallerSensitive(ao);
+ }
+
+ private static DetectionStrategy getDetectionStrategy() {
+ try {
+ return new PrivilegedDetectionStrategy();
+ } catch(Throwable t) {
+ return new UnprivilegedDetectionStrategy();
+ }
+ }
+
+ private abstract static class DetectionStrategy {
+ abstract boolean isCallerSensitive(AccessibleObject ao);
+ }
+
+ private static class PrivilegedDetectionStrategy extends DetectionStrategy {
+ private static final Class extends Annotation> CALLER_SENSITIVE_ANNOTATION_CLASS = CallerSensitive.class;
+
+ @Override
+ boolean isCallerSensitive(AccessibleObject ao) {
+ return ao.getAnnotation(CALLER_SENSITIVE_ANNOTATION_CLASS) != null;
+ }
+ }
+
+ private static class UnprivilegedDetectionStrategy extends DetectionStrategy {
+ private static final String CALLER_SENSITIVE_ANNOTATION_STRING = "@sun.reflect.CallerSensitive()";
+
+ @Override
+ boolean isCallerSensitive(AccessibleObject o) {
+ for(Annotation a: o.getAnnotations()) {
+ if(String.valueOf(a).equals(CALLER_SENSITIVE_ANNOTATION_STRING)) {
+ return true;
+ }
+ }
+ return false;
+ }
+ }
+}
diff --git a/nashorn/src/jdk/internal/dynalink/beans/CallerSensitiveDynamicMethod.java b/nashorn/src/jdk/internal/dynalink/beans/CallerSensitiveDynamicMethod.java
new file mode 100644
index 00000000000..1e274d516e9
--- /dev/null
+++ b/nashorn/src/jdk/internal/dynalink/beans/CallerSensitiveDynamicMethod.java
@@ -0,0 +1,158 @@
+/*
+ * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * This file is available under and governed by the GNU General Public
+ * License version 2 only, as published by the Free Software Foundation.
+ * However, the following notice accompanied the original version of this
+ * file, and Oracle licenses the original version of this file under the BSD
+ * license:
+ */
+/*
+ Copyright 2009-2013 Attila Szegedi
+
+ Licensed under both the Apache License, Version 2.0 (the "Apache License")
+ and the BSD License (the "BSD License"), with licensee being free to
+ choose either of the two at their discretion.
+
+ You may not use this file except in compliance with either the Apache
+ License or the BSD License.
+
+ If you choose to use this file in compliance with the Apache License, the
+ following notice applies to you:
+
+ You may obtain a copy of the Apache License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied. See the License for the specific language governing
+ permissions and limitations under the License.
+
+ If you choose to use this file in compliance with the BSD License, the
+ following notice applies to you:
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are
+ met:
+ * Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+ * Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in the
+ documentation and/or other materials provided with the distribution.
+ * Neither the name of the copyright holder nor the names of
+ contributors may be used to endorse or promote products derived from
+ this software without specific prior written permission.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
+ IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
+ TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
+ PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDER
+ BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+ BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+ WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
+ OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+*/
+
+package jdk.internal.dynalink.beans;
+
+import java.lang.invoke.MethodHandle;
+import java.lang.invoke.MethodHandles;
+import java.lang.invoke.MethodType;
+import java.lang.reflect.AccessibleObject;
+import java.lang.reflect.Constructor;
+import java.lang.reflect.Member;
+import java.lang.reflect.Method;
+import java.lang.reflect.Modifier;
+import jdk.internal.dynalink.support.Lookup;
+
+/**
+ * A dynamic method bound to exactly one Java method or constructor that is caller sensitive. Since the target method is
+ * caller sensitive, it doesn't cache a method handle but rather uses the passed lookup object in
+ * {@link #getTarget(java.lang.invoke.MethodHandles.Lookup)} to unreflect a method handle from the reflective member on
+ * every request.
+ *
+ * @author Attila Szegedi
+ */
+class CallerSensitiveDynamicMethod extends SingleDynamicMethod {
+ // Typed as "AccessibleObject" as it can be either a method or a constructor.
+ // If we were Java8-only, we could use java.lang.reflect.Executable
+ private final AccessibleObject target;
+ private final MethodType type;
+
+ public CallerSensitiveDynamicMethod(AccessibleObject target) {
+ super(getName(target));
+ this.target = target;
+ this.type = getMethodType(target);
+ }
+
+ private static String getName(AccessibleObject target) {
+ final Member m = (Member)target;
+ return getMethodNameWithSignature(getMethodType(target), getClassAndMethodName(m.getDeclaringClass(),
+ m.getName()));
+ }
+
+ @Override
+ MethodType getMethodType() {
+ return type;
+ }
+
+ private static MethodType getMethodType(AccessibleObject ao) {
+ final boolean isMethod = ao instanceof Method;
+ final Class> rtype = isMethod ? ((Method)ao).getReturnType() : ((Constructor>)ao).getDeclaringClass();
+ final Class>[] ptypes = isMethod ? ((Method)ao).getParameterTypes() : ((Constructor>)ao).getParameterTypes();
+ final MethodType type = MethodType.methodType(rtype, ptypes);
+ final Member m = (Member)ao;
+ return type.insertParameterTypes(0,
+ isMethod ?
+ Modifier.isStatic(m.getModifiers()) ?
+ Object.class :
+ m.getDeclaringClass() :
+ StaticClass.class);
+ }
+
+ @Override
+ boolean isVarArgs() {
+ return target instanceof Method ? ((Method)target).isVarArgs() : ((Constructor>)target).isVarArgs();
+ }
+
+ @Override
+ MethodHandle getTarget(MethodHandles.Lookup lookup) {
+ if(target instanceof Method) {
+ final MethodHandle mh = Lookup.unreflect(lookup, (Method)target);
+ if(Modifier.isStatic(((Member)target).getModifiers())) {
+ return StaticClassIntrospector.editStaticMethodHandle(mh);
+ }
+ return mh;
+ }
+ return StaticClassIntrospector.editConstructorMethodHandle(Lookup.unreflectConstructor(lookup,
+ (Constructor>)target));
+ }
+}
diff --git a/nashorn/src/jdk/internal/dynalink/beans/ClassString.java b/nashorn/src/jdk/internal/dynalink/beans/ClassString.java
index dfcb378662f..8ab45727de6 100644
--- a/nashorn/src/jdk/internal/dynalink/beans/ClassString.java
+++ b/nashorn/src/jdk/internal/dynalink/beans/ClassString.java
@@ -155,8 +155,8 @@ final class ClassString {
}
List getMaximallySpecifics(List methods, LinkerServices linkerServices, boolean varArg) {
- return MaximallySpecific.getMaximallySpecificMethods(getApplicables(methods, linkerServices, varArg), varArg,
- classes, linkerServices);
+ return MaximallySpecific.getMaximallySpecificMethodHandles(getApplicables(methods, linkerServices, varArg),
+ varArg, classes, linkerServices);
}
/**
diff --git a/nashorn/src/jdk/internal/dynalink/beans/DynamicMethod.java b/nashorn/src/jdk/internal/dynalink/beans/DynamicMethod.java
index aee69ff722e..6beb92b12f7 100644
--- a/nashorn/src/jdk/internal/dynalink/beans/DynamicMethod.java
+++ b/nashorn/src/jdk/internal/dynalink/beans/DynamicMethod.java
@@ -84,8 +84,7 @@
package jdk.internal.dynalink.beans;
import java.lang.invoke.MethodHandle;
-import java.lang.invoke.MethodType;
-import java.util.StringTokenizer;
+import jdk.internal.dynalink.CallSiteDescriptor;
import jdk.internal.dynalink.linker.LinkerServices;
/**
@@ -116,45 +115,28 @@ abstract class DynamicMethod {
* is a variable arguments (vararg) method, it will pack the extra arguments in an array before the invocation of
* the underlying method if it is not already done.
*
- * @param callSiteType the method type at a call site
+ * @param callSiteDescriptor the descriptor of the call site
* @param linkerServices linker services. Used for language-specific type conversions.
* @return an invocation suitable for calling the method from the specified call site.
*/
- abstract MethodHandle getInvocation(MethodType callSiteType, LinkerServices linkerServices);
+ abstract MethodHandle getInvocation(CallSiteDescriptor callSiteDescriptor, LinkerServices linkerServices);
/**
- * Returns a simple dynamic method representing a single underlying Java method (possibly selected among several
+ * Returns a single dynamic method representing a single underlying Java method (possibly selected among several
* overloads) with formal parameter types exactly matching the passed signature.
* @param paramTypes the comma-separated list of requested parameter type names. The names will match both
* qualified and unqualified type names.
- * @return a simple dynamic method representing a single underlying Java method, or null if none of the Java methods
+ * @return a single dynamic method representing a single underlying Java method, or null if none of the Java methods
* behind this dynamic method exactly match the requested parameter types.
*/
- abstract SimpleDynamicMethod getMethodForExactParamTypes(String paramTypes);
+ abstract SingleDynamicMethod getMethodForExactParamTypes(String paramTypes);
/**
- * True if this dynamic method already contains a method handle with an identical signature as the passed in method
- * handle.
- * @param mh the method handle to check
- * @return true if it already contains an equivalent method handle.
+ * True if this dynamic method already contains a method with an identical signature as the passed in method.
+ * @param method the method to check
+ * @return true if it already contains an equivalent method.
*/
- abstract boolean contains(MethodHandle mh);
-
- static boolean typeMatchesDescription(String paramTypes, MethodType type) {
- final StringTokenizer tok = new StringTokenizer(paramTypes, ", ");
- for(int i = 1; i < type.parameterCount(); ++i) { // i = 1 as we ignore the receiver
- if(!(tok.hasMoreTokens() && typeNameMatches(tok.nextToken(), type.parameterType(i)))) {
- return false;
- }
- }
- return !tok.hasMoreTokens();
- }
-
- private static boolean typeNameMatches(String typeName, Class> type) {
- final int lastDot = typeName.lastIndexOf('.');
- final String fullTypeName = type.getCanonicalName();
- return lastDot != -1 && fullTypeName.endsWith(typeName.substring(lastDot)) || typeName.equals(fullTypeName);
- }
+ abstract boolean contains(SingleDynamicMethod method);
static String getClassAndMethodName(Class> clazz, String name) {
final String clazzName = clazz.getCanonicalName();
diff --git a/nashorn/src/jdk/internal/dynalink/beans/DynamicMethodLinker.java b/nashorn/src/jdk/internal/dynalink/beans/DynamicMethodLinker.java
index d8ceeea0045..32942b9a423 100644
--- a/nashorn/src/jdk/internal/dynalink/beans/DynamicMethodLinker.java
+++ b/nashorn/src/jdk/internal/dynalink/beans/DynamicMethodLinker.java
@@ -85,12 +85,12 @@ package jdk.internal.dynalink.beans;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
-import java.lang.invoke.MethodType;
import jdk.internal.dynalink.CallSiteDescriptor;
import jdk.internal.dynalink.linker.GuardedInvocation;
import jdk.internal.dynalink.linker.LinkRequest;
import jdk.internal.dynalink.linker.LinkerServices;
import jdk.internal.dynalink.linker.TypeBasedGuardingDynamicLinker;
+import jdk.internal.dynalink.support.CallSiteDescriptorFactory;
import jdk.internal.dynalink.support.Guards;
/**
@@ -110,19 +110,18 @@ class DynamicMethodLinker implements TypeBasedGuardingDynamicLinker {
return null;
}
final CallSiteDescriptor desc = linkRequest.getCallSiteDescriptor();
- if(desc.getNameTokenCount() != 2 && desc.getNameToken(CallSiteDescriptor.SCHEME) != "dyn") {
+ if(desc.getNameTokenCount() != 2 && desc.getNameToken(CallSiteDescriptor.SCHEME) != "dyn") {
return null;
}
final String operator = desc.getNameToken(CallSiteDescriptor.OPERATOR);
if(operator == "call") {
- final MethodType type = desc.getMethodType();
- final MethodHandle invocation = ((DynamicMethod)receiver).getInvocation(type.dropParameterTypes(0, 1),
- linkerServices);
+ final MethodHandle invocation = ((DynamicMethod)receiver).getInvocation(
+ CallSiteDescriptorFactory.dropParameterTypes(desc, 0, 1), linkerServices);
if(invocation == null) {
return null;
}
- return new GuardedInvocation(MethodHandles.dropArguments(invocation, 0, type.parameterType(0)),
- Guards.getIdentityGuard(receiver));
+ return new GuardedInvocation(MethodHandles.dropArguments(invocation, 0,
+ desc.getMethodType().parameterType(0)), Guards.getIdentityGuard(receiver));
}
return null;
}
diff --git a/nashorn/src/jdk/internal/dynalink/beans/FacetIntrospector.java b/nashorn/src/jdk/internal/dynalink/beans/FacetIntrospector.java
index f4fbd8244f1..97e431ca24b 100644
--- a/nashorn/src/jdk/internal/dynalink/beans/FacetIntrospector.java
+++ b/nashorn/src/jdk/internal/dynalink/beans/FacetIntrospector.java
@@ -167,10 +167,6 @@ abstract class FacetIntrospector {
return editMethodHandle(SafeUnreflector.unreflectSetter(field));
}
- MethodHandle unreflect(Method method) {
- return editMethodHandle(SafeUnreflector.unreflect(method));
- }
-
/**
* Returns an edited method handle. A facet might need to edit an unreflected method handle before it is usable with
* the facet. By default, returns the passed method handle unchanged. The class' static facet will introduce a
diff --git a/nashorn/src/jdk/internal/dynalink/beans/MaximallySpecific.java b/nashorn/src/jdk/internal/dynalink/beans/MaximallySpecific.java
index 182fd01695d..3ee8e41ab30 100644
--- a/nashorn/src/jdk/internal/dynalink/beans/MaximallySpecific.java
+++ b/nashorn/src/jdk/internal/dynalink/beans/MaximallySpecific.java
@@ -105,10 +105,58 @@ class MaximallySpecific {
* @param varArgs whether to assume the methods are varargs
* @return the list of maximally specific methods.
*/
- static List getMaximallySpecificMethods(List methods, boolean varArgs) {
- return getMaximallySpecificMethods(methods, varArgs, null, null);
+ static List getMaximallySpecificMethods(List methods, boolean varArgs) {
+ return getMaximallySpecificSingleDynamicMethods(methods, varArgs, null, null);
}
+ private abstract static class MethodTypeGetter {
+ abstract MethodType getMethodType(T t);
+ }
+
+ private static final MethodTypeGetter METHOD_HANDLE_TYPE_GETTER =
+ new MethodTypeGetter() {
+ @Override
+ MethodType getMethodType(MethodHandle t) {
+ return t.type();
+ }
+ };
+
+ private static final MethodTypeGetter DYNAMIC_METHOD_TYPE_GETTER =
+ new MethodTypeGetter() {
+ @Override
+ MethodType getMethodType(SingleDynamicMethod t) {
+ return t.getMethodType();
+ }
+ };
+
+ /**
+ * Given a list of methods handles, returns a list of maximally specific methods, applying language-runtime
+ * specific conversion preferences.
+ *
+ * @param methods the list of method handles
+ * @param varArgs whether to assume the method handles are varargs
+ * @param argTypes concrete argument types for the invocation
+ * @return the list of maximally specific method handles.
+ */
+ static List getMaximallySpecificMethodHandles(List methods, boolean varArgs,
+ Class>[] argTypes, LinkerServices ls) {
+ return getMaximallySpecificMethods(methods, varArgs, argTypes, ls, METHOD_HANDLE_TYPE_GETTER);
+ }
+
+ /**
+ * Given a list of methods, returns a list of maximally specific methods, applying language-runtime specific
+ * conversion preferences.
+ *
+ * @param methods the list of methods
+ * @param varArgs whether to assume the methods are varargs
+ * @param argTypes concrete argument types for the invocation
+ * @return the list of maximally specific methods.
+ */
+ static List getMaximallySpecificSingleDynamicMethods(List methods,
+ boolean varArgs, Class>[] argTypes, LinkerServices ls) {
+ return getMaximallySpecificMethods(methods, varArgs, argTypes, ls, DYNAMIC_METHOD_TYPE_GETTER);
+ }
+
/**
* Given a list of methods, returns a list of maximally specific methods, applying language-runtime specific
* conversion preferences.
@@ -118,18 +166,18 @@ class MaximallySpecific {
* @param argTypes concrete argument types for the invocation
* @return the list of maximally specific methods.
*/
- static List getMaximallySpecificMethods(List methods, boolean varArgs,
- Class>[] argTypes, LinkerServices ls) {
+ private static List getMaximallySpecificMethods(List methods, boolean varArgs,
+ Class>[] argTypes, LinkerServices ls, MethodTypeGetter methodTypeGetter) {
if(methods.size() < 2) {
return methods;
}
- final LinkedList maximals = new LinkedList<>();
- for(MethodHandle m: methods) {
- final MethodType methodType = m.type();
+ final LinkedList maximals = new LinkedList<>();
+ for(T m: methods) {
+ final MethodType methodType = methodTypeGetter.getMethodType(m);
boolean lessSpecific = false;
- for(Iterator maximal = maximals.iterator(); maximal.hasNext();) {
- final MethodHandle max = maximal.next();
- switch(isMoreSpecific(methodType, max.type(), varArgs, argTypes, ls)) {
+ for(Iterator maximal = maximals.iterator(); maximal.hasNext();) {
+ final T max = maximal.next();
+ switch(isMoreSpecific(methodType, methodTypeGetter.getMethodType(max), varArgs, argTypes, ls)) {
case TYPE_1_BETTER: {
maximal.remove();
break;
diff --git a/nashorn/src/jdk/internal/dynalink/beans/OverloadedDynamicMethod.java b/nashorn/src/jdk/internal/dynalink/beans/OverloadedDynamicMethod.java
index 7873cf1520e..407d2b8310f 100644
--- a/nashorn/src/jdk/internal/dynalink/beans/OverloadedDynamicMethod.java
+++ b/nashorn/src/jdk/internal/dynalink/beans/OverloadedDynamicMethod.java
@@ -84,16 +84,21 @@
package jdk.internal.dynalink.beans;
import java.lang.invoke.MethodHandle;
+import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
+import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
+import jdk.internal.dynalink.CallSiteDescriptor;
import jdk.internal.dynalink.beans.ApplicableOverloadedMethods.ApplicabilityTest;
import jdk.internal.dynalink.linker.LinkerServices;
import jdk.internal.dynalink.support.TypeUtilities;
/**
- * Represents an overloaded method.
+ * Represents a group of {@link SingleDynamicMethod} objects that represents all overloads of a particular name (or all
+ * constructors) for a particular class. Correctly handles overload resolution, variable arity methods, and caller
+ * sensitive methods within the overloads.
*
* @author Attila Szegedi
*/
@@ -101,7 +106,7 @@ class OverloadedDynamicMethod extends DynamicMethod {
/**
* Holds a list of all methods.
*/
- private final LinkedList methods;
+ private final LinkedList methods;
private final ClassLoader classLoader;
/**
@@ -111,21 +116,22 @@ class OverloadedDynamicMethod extends DynamicMethod {
* @param name the name of the method
*/
OverloadedDynamicMethod(Class> clazz, String name) {
- this(new LinkedList(), clazz.getClassLoader(), getClassAndMethodName(clazz, name));
+ this(new LinkedList(), clazz.getClassLoader(), getClassAndMethodName(clazz, name));
}
- private OverloadedDynamicMethod(LinkedList methods, ClassLoader classLoader, String name) {
+ private OverloadedDynamicMethod(LinkedList methods, ClassLoader classLoader, String name) {
super(name);
this.methods = methods;
this.classLoader = classLoader;
}
@Override
- SimpleDynamicMethod getMethodForExactParamTypes(String paramTypes) {
- final LinkedList matchingMethods = new LinkedList<>();
- for(MethodHandle method: methods) {
- if(typeMatchesDescription(paramTypes, method.type())) {
- matchingMethods.add(method);
+ SingleDynamicMethod getMethodForExactParamTypes(String paramTypes) {
+ final LinkedList matchingMethods = new LinkedList<>();
+ for(SingleDynamicMethod method: methods) {
+ final SingleDynamicMethod matchingMethod = method.getMethodForExactParamTypes(paramTypes);
+ if(matchingMethod != null) {
+ matchingMethods.add(matchingMethod);
}
}
switch(matchingMethods.size()) {
@@ -133,8 +139,7 @@ class OverloadedDynamicMethod extends DynamicMethod {
return null;
}
case 1: {
- final MethodHandle target = matchingMethods.get(0);
- return new SimpleDynamicMethod(target, SimpleDynamicMethod.getMethodNameWithSignature(target, getName()));
+ return matchingMethods.getFirst();
}
default: {
throw new BootstrapMethodError("Can't choose among " + matchingMethods + " for argument types "
@@ -144,7 +149,8 @@ class OverloadedDynamicMethod extends DynamicMethod {
}
@Override
- public MethodHandle getInvocation(final MethodType callSiteType, final LinkerServices linkerServices) {
+ public MethodHandle getInvocation(final CallSiteDescriptor callSiteDescriptor, final LinkerServices linkerServices) {
+ final MethodType callSiteType = callSiteDescriptor.getMethodType();
// First, find all methods applicable to the call site by subtyping (JLS 15.12.2.2)
final ApplicableOverloadedMethods subtypingApplicables = getApplicables(callSiteType,
ApplicableOverloadedMethods.APPLICABLE_BY_SUBTYPING);
@@ -156,7 +162,7 @@ class OverloadedDynamicMethod extends DynamicMethod {
ApplicableOverloadedMethods.APPLICABLE_BY_VARIABLE_ARITY);
// Find the methods that are maximally specific based on the call site signature
- List maximallySpecifics = subtypingApplicables.findMaximallySpecificMethods();
+ List maximallySpecifics = subtypingApplicables.findMaximallySpecificMethods();
if(maximallySpecifics.isEmpty()) {
maximallySpecifics = methodInvocationApplicables.findMaximallySpecificMethods();
if(maximallySpecifics.isEmpty()) {
@@ -171,12 +177,12 @@ class OverloadedDynamicMethod extends DynamicMethod {
// (Object, Object), and we have a method whose parameter types are (String, int). None of the JLS applicability
// rules will trigger, but we must consider the method, as it can be the right match for a concrete invocation.
@SuppressWarnings({ "unchecked", "rawtypes" })
- final List invokables = (List)methods.clone();
+ final List invokables = (List)methods.clone();
invokables.removeAll(subtypingApplicables.getMethods());
invokables.removeAll(methodInvocationApplicables.getMethods());
invokables.removeAll(variableArityApplicables.getMethods());
- for(final Iterator it = invokables.iterator(); it.hasNext();) {
- final MethodHandle m = it.next();
+ for(final Iterator it = invokables.iterator(); it.hasNext();) {
+ final SingleDynamicMethod m = it.next();
if(!isApplicableDynamically(linkerServices, callSiteType, m)) {
it.remove();
}
@@ -199,54 +205,45 @@ class OverloadedDynamicMethod extends DynamicMethod {
}
case 1: {
// Very lucky, we ended up with a single candidate method handle based on the call site signature; we
- // can link it very simply by delegating to a SimpleDynamicMethod.
- final MethodHandle mh = invokables.iterator().next();
- return new SimpleDynamicMethod(mh).getInvocation(callSiteType, linkerServices);
+ // can link it very simply by delegating to the SingleDynamicMethod.
+ invokables.iterator().next().getInvocation(callSiteDescriptor, linkerServices);
}
default: {
// We have more than one candidate. We have no choice but to link to a method that resolves overloads on
// every invocation (alternatively, we could opportunistically link the one method that resolves for the
// current arguments, but we'd need to install a fairly complex guard for that and when it'd fail, we'd
- // go back all the way to candidate selection.
- // TODO: cache per call site type
- return new OverloadedMethod(invokables, this, callSiteType, linkerServices).getInvoker();
+ // go back all the way to candidate selection. Note that we're resolving any potential caller sensitive
+ // methods here to their handles, as the OverloadedMethod instance is specific to a call site, so it
+ // has an already determined Lookup.
+ final List methodHandles = new ArrayList<>(invokables.size());
+ final MethodHandles.Lookup lookup = callSiteDescriptor.getLookup();
+ for(SingleDynamicMethod method: invokables) {
+ methodHandles.add(method.getTarget(lookup));
+ }
+ return new OverloadedMethod(methodHandles, this, callSiteType, linkerServices).getInvoker();
}
}
}
@Override
- public boolean contains(MethodHandle mh) {
- final MethodType type = mh.type();
- for(MethodHandle method: methods) {
- if(typesEqualNoReceiver(type, method.type())) {
+ public boolean contains(SingleDynamicMethod m) {
+ for(SingleDynamicMethod method: methods) {
+ if(method.contains(m)) {
return true;
}
}
return false;
}
- private static boolean typesEqualNoReceiver(MethodType type1, MethodType type2) {
- final int pc = type1.parameterCount();
- if(pc != type2.parameterCount()) {
- return false;
- }
- for(int i = 1; i < pc; ++i) { // i = 1: ignore receiver
- if(type1.parameterType(i) != type2.parameterType(i)) {
- return false;
- }
- }
- return true;
- }
-
ClassLoader getClassLoader() {
return classLoader;
}
private static boolean isApplicableDynamically(LinkerServices linkerServices, MethodType callSiteType,
- MethodHandle m) {
- final MethodType methodType = m.type();
- final boolean varArgs = m.isVarargsCollector();
+ SingleDynamicMethod m) {
+ final MethodType methodType = m.getMethodType();
+ final boolean varArgs = m.isVarArgs();
final int fixedArgLen = methodType.parameterCount() - (varArgs ? 1 : 0);
final int callSiteArgLen = callSiteType.parameterCount();
@@ -300,21 +297,12 @@ class OverloadedDynamicMethod extends DynamicMethod {
return new ApplicableOverloadedMethods(methods, callSiteType, test);
}
- /**
- * Add a method identified by a {@link SimpleDynamicMethod} to this overloaded method's set.
- *
- * @param method the method to add.
- */
- void addMethod(SimpleDynamicMethod method) {
- addMethod(method.getTarget());
- }
-
/**
* Add a method to this overloaded method's set.
*
* @param method a method to add
*/
- public void addMethod(MethodHandle method) {
+ public void addMethod(SingleDynamicMethod method) {
methods.add(method);
}
}
diff --git a/nashorn/src/jdk/internal/dynalink/beans/OverloadedMethod.java b/nashorn/src/jdk/internal/dynalink/beans/OverloadedMethod.java
index 7093e757497..f711489b037 100644
--- a/nashorn/src/jdk/internal/dynalink/beans/OverloadedMethod.java
+++ b/nashorn/src/jdk/internal/dynalink/beans/OverloadedMethod.java
@@ -135,7 +135,7 @@ class OverloadedMethod {
varArgMethods.trimToSize();
final MethodHandle bound = SELECT_METHOD.bindTo(this);
- final MethodHandle collecting = SimpleDynamicMethod.collectArguments(bound, argNum).asType(
+ final MethodHandle collecting = SingleDynamicMethod.collectArguments(bound, argNum).asType(
callSiteType.changeReturnType(MethodHandle.class));
invoker = MethodHandles.foldArguments(MethodHandles.exactInvoker(callSiteType), collecting);
}
@@ -167,7 +167,7 @@ class OverloadedMethod {
break;
}
case 1: {
- method = new SimpleDynamicMethod(methods.get(0)).getInvocation(callSiteType, linkerServices);
+ method = SingleDynamicMethod.getInvocation(methods.get(0), callSiteType, linkerServices);
break;
}
default: {
diff --git a/nashorn/src/jdk/internal/dynalink/beans/SimpleDynamicMethod.java b/nashorn/src/jdk/internal/dynalink/beans/SimpleDynamicMethod.java
index 1fbf7dbb1a0..9d4d6961081 100644
--- a/nashorn/src/jdk/internal/dynalink/beans/SimpleDynamicMethod.java
+++ b/nashorn/src/jdk/internal/dynalink/beans/SimpleDynamicMethod.java
@@ -84,28 +84,21 @@
package jdk.internal.dynalink.beans;
import java.lang.invoke.MethodHandle;
-import java.lang.invoke.MethodHandles;
+import java.lang.invoke.MethodHandles.Lookup;
import java.lang.invoke.MethodType;
-import java.lang.reflect.Array;
-import jdk.internal.dynalink.linker.LinkerServices;
-import jdk.internal.dynalink.support.Guards;
/**
- * A dynamic method bound to exactly one, non-overloaded Java method. Handles varargs.
+ * A dynamic method bound to exactly one Java method or constructor that is not caller sensitive. Since its target is
+ * not caller sensitive, this class pre-caches its method handle and always returns it from the call to
+ * {@link #getTarget(Lookup)}. Can be used in general to represents dynamic methods bound to a single method handle,
+ * even if that handle is not mapped to a Java method, i.e. as a wrapper around field getters/setters, array element
+ * getters/setters, etc.
*
* @author Attila Szegedi
*/
-class SimpleDynamicMethod extends DynamicMethod {
+class SimpleDynamicMethod extends SingleDynamicMethod {
private final MethodHandle target;
- /**
- * Creates a simple dynamic method with no name.
- * @param target the target method handle
- */
- SimpleDynamicMethod(MethodHandle target) {
- this(target, null);
- }
-
/**
* Creates a new simple dynamic method, with a name constructed from the class name, method name, and handle
* signature.
@@ -115,125 +108,26 @@ class SimpleDynamicMethod extends DynamicMethod {
* @param name the simple name of the method
*/
SimpleDynamicMethod(MethodHandle target, Class> clazz, String name) {
- this(target, getName(target, clazz, name));
- }
-
- SimpleDynamicMethod(MethodHandle target, String name) {
- super(name);
+ super(getName(target, clazz, name));
this.target = target;
}
private static String getName(MethodHandle target, Class> clazz, String name) {
- return getMethodNameWithSignature(target, getClassAndMethodName(clazz, name));
+ return getMethodNameWithSignature(target.type(), getClassAndMethodName(clazz, name));
}
- static String getMethodNameWithSignature(MethodHandle target, String methodName) {
- final String typeStr = target.type().toString();
- final int retTypeIndex = typeStr.lastIndexOf(')') + 1;
- int secondParamIndex = typeStr.indexOf(',') + 1;
- if(secondParamIndex == 0) {
- secondParamIndex = retTypeIndex - 1;
- }
- return typeStr.substring(retTypeIndex) + " " + methodName + "(" + typeStr.substring(secondParamIndex, retTypeIndex);
+ @Override
+ boolean isVarArgs() {
+ return target.isVarargsCollector();
}
- /**
- * Returns the target of this dynamic method
- *
- * @return the target of this dynamic method
- */
- MethodHandle getTarget() {
+ @Override
+ MethodType getMethodType() {
+ return target.type();
+ }
+
+ @Override
+ MethodHandle getTarget(Lookup lookup) {
return target;
}
-
- @Override
- SimpleDynamicMethod getMethodForExactParamTypes(String paramTypes) {
- return typeMatchesDescription(paramTypes, target.type()) ? this : null;
- }
-
- @Override
- MethodHandle getInvocation(MethodType callSiteType, LinkerServices linkerServices) {
- final MethodType methodType = target.type();
- final int paramsLen = methodType.parameterCount();
- final boolean varArgs = target.isVarargsCollector();
- final MethodHandle fixTarget = varArgs ? target.asFixedArity() : target;
- final int fixParamsLen = varArgs ? paramsLen - 1 : paramsLen;
- final int argsLen = callSiteType.parameterCount();
- if(argsLen < fixParamsLen) {
- // Less actual arguments than number of fixed declared arguments; can't invoke.
- return null;
- }
- // Method handle has the same number of fixed arguments as the call site type
- if(argsLen == fixParamsLen) {
- // Method handle that matches the number of actual arguments as the number of fixed arguments
- final MethodHandle matchedMethod;
- if(varArgs) {
- // If vararg, add a zero-length array of the expected type as the last argument to signify no variable
- // arguments.
- matchedMethod = MethodHandles.insertArguments(fixTarget, fixParamsLen, Array.newInstance(
- methodType.parameterType(fixParamsLen).getComponentType(), 0));
- } else {
- // Otherwise, just use the method
- matchedMethod = fixTarget;
- }
- return createConvertingInvocation(matchedMethod, linkerServices, callSiteType);
- }
-
- // What's below only works for varargs
- if(!varArgs) {
- return null;
- }
-
- final Class> varArgType = methodType.parameterType(fixParamsLen);
- // Handle a somewhat sinister corner case: caller passes exactly one argument in the vararg position, and we
- // must handle both a prepacked vararg array as well as a genuine 1-long vararg sequence.
- if(argsLen == paramsLen) {
- final Class> callSiteLastArgType = callSiteType.parameterType(fixParamsLen);
- if(varArgType.isAssignableFrom(callSiteLastArgType)) {
- // Call site signature guarantees we'll always be passed a single compatible array; just link directly
- // to the method.
- return createConvertingInvocation(fixTarget, linkerServices, callSiteType);
- }
- if(!linkerServices.canConvert(callSiteLastArgType, varArgType)) {
- // Call site signature guarantees the argument can definitely not be an array (i.e. it is primitive);
- // link immediately to a vararg-packing method handle.
- return createConvertingInvocation(collectArguments(fixTarget, argsLen), linkerServices, callSiteType);
- }
- // Call site signature makes no guarantees that the single argument in the vararg position will be
- // compatible across all invocations. Need to insert an appropriate guard and fall back to generic vararg
- // method when it is not.
- return MethodHandles.guardWithTest(Guards.isInstance(varArgType, fixParamsLen, callSiteType),
- createConvertingInvocation(fixTarget, linkerServices, callSiteType),
- createConvertingInvocation(collectArguments(fixTarget, argsLen), linkerServices, callSiteType));
- }
-
- // Remaining case: more than one vararg.
- return createConvertingInvocation(collectArguments(fixTarget, argsLen), linkerServices, callSiteType);
- }
-
- @Override
- public boolean contains(MethodHandle mh) {
- return target.type().parameterList().equals(mh.type().parameterList());
- }
-
- /**
- * Creates a method handle out of the original target that will collect the varargs for the exact component type of
- * the varArg array. Note that this will nicely trigger language-specific type converters for exactly those varargs
- * for which it is necessary when later passed to linkerServices.convertArguments().
- *
- * @param target the original method handle
- * @param parameterCount the total number of arguments in the new method handle
- * @return a collecting method handle
- */
- static MethodHandle collectArguments(MethodHandle target, final int parameterCount) {
- final MethodType methodType = target.type();
- final int fixParamsLen = methodType.parameterCount() - 1;
- final Class> arrayType = methodType.parameterType(fixParamsLen);
- return target.asCollector(arrayType, parameterCount - fixParamsLen);
- }
-
- private static MethodHandle createConvertingInvocation(final MethodHandle sizedMethod,
- final LinkerServices linkerServices, final MethodType callSiteType) {
- return linkerServices.asType(sizedMethod, callSiteType);
- }
}
diff --git a/nashorn/src/jdk/internal/dynalink/beans/SingleDynamicMethod.java b/nashorn/src/jdk/internal/dynalink/beans/SingleDynamicMethod.java
new file mode 100644
index 00000000000..d15fab9966e
--- /dev/null
+++ b/nashorn/src/jdk/internal/dynalink/beans/SingleDynamicMethod.java
@@ -0,0 +1,255 @@
+/*
+ * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * This file is available under and governed by the GNU General Public
+ * License version 2 only, as published by the Free Software Foundation.
+ * However, the following notice accompanied the original version of this
+ * file, and Oracle licenses the original version of this file under the BSD
+ * license:
+ */
+/*
+ Copyright 2009-2013 Attila Szegedi
+
+ Licensed under both the Apache License, Version 2.0 (the "Apache License")
+ and the BSD License (the "BSD License"), with licensee being free to
+ choose either of the two at their discretion.
+
+ You may not use this file except in compliance with either the Apache
+ License or the BSD License.
+
+ If you choose to use this file in compliance with the Apache License, the
+ following notice applies to you:
+
+ You may obtain a copy of the Apache License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied. See the License for the specific language governing
+ permissions and limitations under the License.
+
+ If you choose to use this file in compliance with the BSD License, the
+ following notice applies to you:
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are
+ met:
+ * Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+ * Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in the
+ documentation and/or other materials provided with the distribution.
+ * Neither the name of the copyright holder nor the names of
+ contributors may be used to endorse or promote products derived from
+ this software without specific prior written permission.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
+ IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
+ TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
+ PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDER
+ BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+ BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+ WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
+ OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+*/
+
+package jdk.internal.dynalink.beans;
+
+import java.lang.invoke.MethodHandle;
+import java.lang.invoke.MethodHandles;
+import java.lang.invoke.MethodType;
+import java.lang.reflect.Array;
+import java.util.StringTokenizer;
+import jdk.internal.dynalink.CallSiteDescriptor;
+import jdk.internal.dynalink.linker.LinkerServices;
+import jdk.internal.dynalink.support.Guards;
+
+/**
+ * Base class for dynamic methods that dispatch to a single target Java method or constructor. Handles adaptation of the
+ * target method to a call site type (including mapping variable arity methods to a call site signature with different
+ * arity).
+ * @author Attila Szegedi
+ * @version $Id: $
+ */
+abstract class SingleDynamicMethod extends DynamicMethod {
+ SingleDynamicMethod(String name) {
+ super(name);
+ }
+
+ /**
+ * Returns true if this method is variable arity.
+ * @return true if this method is variable arity.
+ */
+ abstract boolean isVarArgs();
+
+ /**
+ * Returns this method's native type.
+ * @return this method's native type.
+ */
+ abstract MethodType getMethodType();
+
+ /**
+ * Given a specified lookup, returns a method handle to this method's target.
+ * @param lookup the lookup to use.
+ * @return the handle to this method's target method.
+ */
+ abstract MethodHandle getTarget(MethodHandles.Lookup lookup);
+
+ @Override
+ MethodHandle getInvocation(CallSiteDescriptor callSiteDescriptor, LinkerServices linkerServices) {
+ return getInvocation(getTarget(callSiteDescriptor.getLookup()), callSiteDescriptor.getMethodType(),
+ linkerServices);
+ }
+
+ @Override
+ SingleDynamicMethod getMethodForExactParamTypes(String paramTypes) {
+ return typeMatchesDescription(paramTypes, getMethodType()) ? this : null;
+ }
+
+ @Override
+ boolean contains(SingleDynamicMethod method) {
+ return getMethodType().parameterList().equals(method.getMethodType().parameterList());
+ }
+
+ static String getMethodNameWithSignature(MethodType type, String methodName) {
+ final String typeStr = type.toString();
+ final int retTypeIndex = typeStr.lastIndexOf(')') + 1;
+ int secondParamIndex = typeStr.indexOf(',') + 1;
+ if(secondParamIndex == 0) {
+ secondParamIndex = retTypeIndex - 1;
+ }
+ return typeStr.substring(retTypeIndex) + " " + methodName + "(" + typeStr.substring(secondParamIndex, retTypeIndex);
+ }
+
+ /**
+ * Given a method handle and a call site type, adapts the method handle to the call site type. Performs type
+ * conversions as needed using the specified linker services, and in case that the method handle is a vararg
+ * collector, matches it to the arity of the call site.
+ * @param target the method handle to adapt
+ * @param callSiteType the type of the call site
+ * @param linkerServices the linker services used for type conversions
+ * @return the adapted method handle.
+ */
+ static MethodHandle getInvocation(MethodHandle target, MethodType callSiteType, LinkerServices linkerServices) {
+ final MethodType methodType = target.type();
+ final int paramsLen = methodType.parameterCount();
+ final boolean varArgs = target.isVarargsCollector();
+ final MethodHandle fixTarget = varArgs ? target.asFixedArity() : target;
+ final int fixParamsLen = varArgs ? paramsLen - 1 : paramsLen;
+ final int argsLen = callSiteType.parameterCount();
+ if(argsLen < fixParamsLen) {
+ // Less actual arguments than number of fixed declared arguments; can't invoke.
+ return null;
+ }
+ // Method handle has the same number of fixed arguments as the call site type
+ if(argsLen == fixParamsLen) {
+ // Method handle that matches the number of actual arguments as the number of fixed arguments
+ final MethodHandle matchedMethod;
+ if(varArgs) {
+ // If vararg, add a zero-length array of the expected type as the last argument to signify no variable
+ // arguments.
+ matchedMethod = MethodHandles.insertArguments(fixTarget, fixParamsLen, Array.newInstance(
+ methodType.parameterType(fixParamsLen).getComponentType(), 0));
+ } else {
+ // Otherwise, just use the method
+ matchedMethod = fixTarget;
+ }
+ return createConvertingInvocation(matchedMethod, linkerServices, callSiteType);
+ }
+
+ // What's below only works for varargs
+ if(!varArgs) {
+ return null;
+ }
+
+ final Class> varArgType = methodType.parameterType(fixParamsLen);
+ // Handle a somewhat sinister corner case: caller passes exactly one argument in the vararg position, and we
+ // must handle both a prepacked vararg array as well as a genuine 1-long vararg sequence.
+ if(argsLen == paramsLen) {
+ final Class> callSiteLastArgType = callSiteType.parameterType(fixParamsLen);
+ if(varArgType.isAssignableFrom(callSiteLastArgType)) {
+ // Call site signature guarantees we'll always be passed a single compatible array; just link directly
+ // to the method, introducing necessary conversions. Also, preserve it being a variable arity method.
+ return createConvertingInvocation(target, linkerServices, callSiteType).asVarargsCollector(
+ callSiteLastArgType);
+ }
+ if(!linkerServices.canConvert(callSiteLastArgType, varArgType)) {
+ // Call site signature guarantees the argument can definitely not be an array (i.e. it is primitive);
+ // link immediately to a vararg-packing method handle.
+ return createConvertingInvocation(collectArguments(fixTarget, argsLen), linkerServices, callSiteType);
+ }
+ // Call site signature makes no guarantees that the single argument in the vararg position will be
+ // compatible across all invocations. Need to insert an appropriate guard and fall back to generic vararg
+ // method when it is not.
+ return MethodHandles.guardWithTest(Guards.isInstance(varArgType, fixParamsLen, callSiteType),
+ createConvertingInvocation(fixTarget, linkerServices, callSiteType),
+ createConvertingInvocation(collectArguments(fixTarget, argsLen), linkerServices, callSiteType));
+ }
+
+ // Remaining case: more than one vararg.
+ return createConvertingInvocation(collectArguments(fixTarget, argsLen), linkerServices, callSiteType);
+ }
+
+ /**
+ * Creates a method handle out of the original target that will collect the varargs for the exact component type of
+ * the varArg array. Note that this will nicely trigger language-specific type converters for exactly those varargs
+ * for which it is necessary when later passed to linkerServices.convertArguments().
+ *
+ * @param target the original method handle
+ * @param parameterCount the total number of arguments in the new method handle
+ * @return a collecting method handle
+ */
+ static MethodHandle collectArguments(MethodHandle target, final int parameterCount) {
+ final MethodType methodType = target.type();
+ final int fixParamsLen = methodType.parameterCount() - 1;
+ final Class> arrayType = methodType.parameterType(fixParamsLen);
+ return target.asCollector(arrayType, parameterCount - fixParamsLen);
+ }
+
+ private static MethodHandle createConvertingInvocation(final MethodHandle sizedMethod,
+ final LinkerServices linkerServices, final MethodType callSiteType) {
+ return linkerServices.asType(sizedMethod, callSiteType);
+ }
+
+ private static boolean typeMatchesDescription(String paramTypes, MethodType type) {
+ final StringTokenizer tok = new StringTokenizer(paramTypes, ", ");
+ for(int i = 1; i < type.parameterCount(); ++i) { // i = 1 as we ignore the receiver
+ if(!(tok.hasMoreTokens() && typeNameMatches(tok.nextToken(), type.parameterType(i)))) {
+ return false;
+ }
+ }
+ return !tok.hasMoreTokens();
+ }
+
+ private static boolean typeNameMatches(String typeName, Class> type) {
+ return typeName.equals(typeName.indexOf('.') == -1 ? type.getSimpleName() : type.getCanonicalName());
+ }
+}
diff --git a/nashorn/src/jdk/internal/dynalink/beans/StaticClassIntrospector.java b/nashorn/src/jdk/internal/dynalink/beans/StaticClassIntrospector.java
index 214152a41ec..62ce41a95a6 100644
--- a/nashorn/src/jdk/internal/dynalink/beans/StaticClassIntrospector.java
+++ b/nashorn/src/jdk/internal/dynalink/beans/StaticClassIntrospector.java
@@ -106,10 +106,18 @@ class StaticClassIntrospector extends FacetIntrospector {
@Override
MethodHandle editMethodHandle(MethodHandle mh) {
+ return editStaticMethodHandle(mh);
+ }
+
+ static MethodHandle editStaticMethodHandle(MethodHandle mh) {
return dropReceiver(mh, Object.class);
}
- static MethodHandle dropReceiver(final MethodHandle mh, final Class> receiverClass) {
+ static MethodHandle editConstructorMethodHandle(MethodHandle cmh) {
+ return dropReceiver(cmh, StaticClass.class);
+ }
+
+ private static MethodHandle dropReceiver(final MethodHandle mh, final Class> receiverClass) {
MethodHandle newHandle = MethodHandles.dropArguments(mh, 0, receiverClass);
// NOTE: this is a workaround for the fact that dropArguments doesn't preserve vararg collector state.
if(mh.isVarargsCollector() && !newHandle.isVarargsCollector()) {
diff --git a/nashorn/src/jdk/internal/dynalink/beans/StaticClassLinker.java b/nashorn/src/jdk/internal/dynalink/beans/StaticClassLinker.java
index d6096fe559b..8cd221f3df4 100644
--- a/nashorn/src/jdk/internal/dynalink/beans/StaticClassLinker.java
+++ b/nashorn/src/jdk/internal/dynalink/beans/StaticClassLinker.java
@@ -87,9 +87,7 @@ import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.lang.reflect.Array;
-import java.lang.reflect.Constructor;
-import java.util.ArrayList;
-import java.util.List;
+import java.util.Arrays;
import jdk.internal.dynalink.CallSiteDescriptor;
import jdk.internal.dynalink.beans.GuardedInvocationComponent.ValidationType;
import jdk.internal.dynalink.linker.GuardedInvocation;
@@ -131,20 +129,11 @@ class StaticClassLinker implements TypeBasedGuardingDynamicLinker {
private static DynamicMethod createConstructorMethod(Class> clazz) {
if(clazz.isArray()) {
final MethodHandle boundArrayCtor = ARRAY_CTOR.bindTo(clazz.getComponentType());
- return new SimpleDynamicMethod(drop(boundArrayCtor.asType(boundArrayCtor.type().changeReturnType(
- clazz))), clazz, "");
+ return new SimpleDynamicMethod(StaticClassIntrospector.editConstructorMethodHandle(
+ boundArrayCtor.asType(boundArrayCtor.type().changeReturnType(clazz))), clazz, "");
}
- final Constructor>[] ctrs = clazz.getConstructors();
- final List mhs = new ArrayList<>(ctrs.length);
- for(int i = 0; i < ctrs.length; ++i) {
- mhs.add(drop(SafeUnreflector.unreflectConstructor(ctrs[i])));
- }
- return createDynamicMethod(mhs, clazz, "");
- }
-
- private static MethodHandle drop(MethodHandle mh) {
- return StaticClassIntrospector.dropReceiver(mh, StaticClass.class);
+ return createDynamicMethod(Arrays.asList(clazz.getConstructors()), clazz, "");
}
@Override
@@ -161,11 +150,10 @@ class StaticClassLinker implements TypeBasedGuardingDynamicLinker {
}
final CallSiteDescriptor desc = request.getCallSiteDescriptor();
final String op = desc.getNameToken(CallSiteDescriptor.OPERATOR);
- final MethodType methodType = desc.getMethodType();
if("new" == op && constructor != null) {
- final MethodHandle ctorInvocation = constructor.getInvocation(methodType, linkerServices);
+ final MethodHandle ctorInvocation = constructor.getInvocation(desc, linkerServices);
if(ctorInvocation != null) {
- return new GuardedInvocation(ctorInvocation, getClassGuard(methodType));
+ return new GuardedInvocation(ctorInvocation, getClassGuard(desc.getMethodType()));
}
}
return null;
diff --git a/nashorn/src/jdk/internal/dynalink/support/AbstractCallSiteDescriptor.java b/nashorn/src/jdk/internal/dynalink/support/AbstractCallSiteDescriptor.java
index e51f6fe2f2a..3161cf50a76 100644
--- a/nashorn/src/jdk/internal/dynalink/support/AbstractCallSiteDescriptor.java
+++ b/nashorn/src/jdk/internal/dynalink/support/AbstractCallSiteDescriptor.java
@@ -139,8 +139,9 @@ public abstract class AbstractCallSiteDescriptor implements CallSiteDescriptor {
@Override
public int hashCode() {
+ final MethodHandles.Lookup lookup = getLookup();
+ int h = lookup.lookupClass().hashCode() + 31 * lookup.lookupModes();
final int c = getNameTokenCount();
- int h = 0;
for(int i = 0; i < c; ++i) {
h = h * 31 + getNameToken(i).hashCode();
}
diff --git a/nashorn/src/jdk/internal/dynalink/support/Lookup.java b/nashorn/src/jdk/internal/dynalink/support/Lookup.java
index 52a610246a8..4b21e1c4af4 100644
--- a/nashorn/src/jdk/internal/dynalink/support/Lookup.java
+++ b/nashorn/src/jdk/internal/dynalink/support/Lookup.java
@@ -122,6 +122,18 @@ public class Lookup {
* @return the unreflected method handle.
*/
public MethodHandle unreflect(Method m) {
+ return unreflect(lookup, m);
+ }
+
+ /**
+ * Performs a {@link java.lang.invoke.MethodHandles.Lookup#unreflect(Method)}, converting any encountered
+ * {@link IllegalAccessException} into an {@link IllegalAccessError}.
+ *
+ * @param lookup the lookup used to unreflect
+ * @param m the method to unreflect
+ * @return the unreflected method handle.
+ */
+ public static MethodHandle unreflect(MethodHandles.Lookup lookup, Method m) {
try {
return lookup.unreflect(m);
} catch(IllegalAccessException e) {
@@ -131,7 +143,6 @@ public class Lookup {
}
}
-
/**
* Performs a {@link java.lang.invoke.MethodHandles.Lookup#unreflectGetter(Field)}, converting any encountered
* {@link IllegalAccessException} into an {@link IllegalAccessError}.
@@ -202,6 +213,18 @@ public class Lookup {
* @return the unreflected constructor handle.
*/
public MethodHandle unreflectConstructor(Constructor> c) {
+ return unreflectConstructor(lookup, c);
+ }
+
+ /**
+ * Performs a {@link java.lang.invoke.MethodHandles.Lookup#unreflectConstructor(Constructor)}, converting any
+ * encountered {@link IllegalAccessException} into an {@link IllegalAccessError}.
+ *
+ * @param lookup the lookup used to unreflect
+ * @param c the constructor to unreflect
+ * @return the unreflected constructor handle.
+ */
+ public static MethodHandle unreflectConstructor(MethodHandles.Lookup lookup, Constructor> c) {
try {
return lookup.unreflectConstructor(c);
} catch(IllegalAccessException e) {
diff --git a/nashorn/src/jdk/nashorn/api/scripting/NashornException.java b/nashorn/src/jdk/nashorn/api/scripting/NashornException.java
index 3cd687cce08..d5ec5bb4a60 100644
--- a/nashorn/src/jdk/nashorn/api/scripting/NashornException.java
+++ b/nashorn/src/jdk/nashorn/api/scripting/NashornException.java
@@ -146,7 +146,7 @@ public abstract class NashornException extends RuntimeException {
* @return array of javascript stack frames
*/
public static StackTraceElement[] getScriptFrames(final Throwable exception) {
- final StackTraceElement[] frames = ((Throwable)exception).getStackTrace();
+ final StackTraceElement[] frames = exception.getStackTrace();
final List filtered = new ArrayList<>();
for (final StackTraceElement st : frames) {
if (ECMAErrors.isScriptFrame(st)) {
@@ -170,7 +170,7 @@ public abstract class NashornException extends RuntimeException {
*/
public static String getScriptStackString(final Throwable exception) {
final StringBuilder buf = new StringBuilder();
- final StackTraceElement[] frames = getScriptFrames((Throwable)exception);
+ final StackTraceElement[] frames = getScriptFrames(exception);
for (final StackTraceElement st : frames) {
buf.append("\tat ");
buf.append(st.getMethodName());
diff --git a/nashorn/src/jdk/nashorn/api/scripting/ScriptObjectMirror.java b/nashorn/src/jdk/nashorn/api/scripting/ScriptObjectMirror.java
index c7dbab5a184..52684cfe0c8 100644
--- a/nashorn/src/jdk/nashorn/api/scripting/ScriptObjectMirror.java
+++ b/nashorn/src/jdk/nashorn/api/scripting/ScriptObjectMirror.java
@@ -308,9 +308,9 @@ public final class ScriptObjectMirror extends JSObject implements Bindings {
public void putAll(final Map extends String, ? extends Object> map) {
final ScriptObject oldGlobal = NashornScriptEngine.getNashornGlobal();
final boolean globalChanged = (oldGlobal != global);
- final boolean strict = sobj.isStrictContext();
inGlobal(new Callable
- * In the special case of inner classes, you need to use the JVM fully qualified name, meaning using {@code $} sign
- * in the class name:
+ * In the special case of inner classes, you can either use the JVM fully qualified name, meaning using {@code $}
+ * sign in the class name, or you can use the dot:
*
* var ftype = Java.type("java.awt.geom.Arc2D$Float")
*
- * However, once you retrieved the outer class, you can access the inner class as a property on it:
+ * and
+ *
+ * var ftype = Java.type("java.awt.geom.Arc2D.Float")
+ *
+ * both work. Note however that using the dollar sign is faster, as Java.type first tries to resolve the class name
+ * as it is originally specified, and the internal JVM names for inner classes use the dollar sign. If you use the
+ * dot, Java.type will internally get a ClassNotFoundException and subsequently retry by changing the last dot to
+ * dollar sign. As a matter of fact, it'll keep replacing dots with dollar signs until it either successfully loads
+ * the class or runs out of all dots in the name. This way it can correctly resolve and load even multiply nested
+ * inner classes with the dot notation. Again, this will be slower than using the dollar signs in the name. An
+ * alternative way to access the inner class is as a property of the outer class:
*
* var arctype = Java.type("java.awt.geom.Arc2D")
* var ftype = arctype.Float
@@ -388,7 +403,33 @@ public final class NativeJava {
private static Class> simpleType(final String typeName) throws ClassNotFoundException {
final Class> primClass = TypeUtilities.getPrimitiveTypeByName(typeName);
- return primClass != null ? primClass : Global.getThisContext().findClass(typeName);
+ if(primClass != null) {
+ return primClass;
+ }
+ final Context ctx = Global.getThisContext();
+ try {
+ return ctx.findClass(typeName);
+ } catch(ClassNotFoundException e) {
+ // The logic below compensates for a frequent user error - when people use dot notation to separate inner
+ // class names, i.e. "java.lang.Character.UnicodeBlock" vs."java.lang.Character$UnicodeBlock". The logic
+ // below will try alternative class names, replacing dots at the end of the name with dollar signs.
+ final StringBuilder nextName = new StringBuilder(typeName);
+ int lastDot = nextName.length();
+ for(;;) {
+ lastDot = nextName.lastIndexOf(".", lastDot - 1);
+ if(lastDot == -1) {
+ // Exhausted the search space, class not found - rethrow the original exception.
+ throw e;
+ }
+ nextName.setCharAt(lastDot, '$');
+ try {
+ return ctx.findClass(nextName.toString());
+ } catch(ClassNotFoundException cnfe) {
+ // Intentionally ignored, so the loop retries with the next name
+ }
+ }
+ }
+
}
private static Class> arrayType(final String typeName) throws ClassNotFoundException {
diff --git a/nashorn/src/jdk/nashorn/internal/objects/NativeJavaImporter.java b/nashorn/src/jdk/nashorn/internal/objects/NativeJavaImporter.java
index 9d4c15ac4d1..c2d2bd10e81 100644
--- a/nashorn/src/jdk/nashorn/internal/objects/NativeJavaImporter.java
+++ b/nashorn/src/jdk/nashorn/internal/objects/NativeJavaImporter.java
@@ -59,11 +59,23 @@ public final class NativeJavaImporter extends ScriptObject {
// initialized by nasgen
private static PropertyMap $nasgenmap$;
- NativeJavaImporter(final Object[] args) {
- super(Global.instance().getJavaImporterPrototype(), $nasgenmap$);
+ static PropertyMap getInitialMap() {
+ return $nasgenmap$;
+ }
+
+ private NativeJavaImporter(final Object[] args, final ScriptObject proto, final PropertyMap map) {
+ super(proto, map);
this.args = args;
}
+ private NativeJavaImporter(final Object[] args, final Global global) {
+ this(args, global.getJavaImporterPrototype(), global.getJavaImporterMap());
+ }
+
+ private NativeJavaImporter(final Object[] args) {
+ this(args, Global.instance());
+ }
+
@Override
public String getClassName() {
return "JavaImporter";
diff --git a/nashorn/src/jdk/nashorn/internal/objects/NativeMath.java b/nashorn/src/jdk/nashorn/internal/objects/NativeMath.java
index 2b093548315..cc50fbb4f00 100644
--- a/nashorn/src/jdk/nashorn/internal/objects/NativeMath.java
+++ b/nashorn/src/jdk/nashorn/internal/objects/NativeMath.java
@@ -43,10 +43,12 @@ import jdk.nashorn.internal.runtime.ScriptObject;
public final class NativeMath extends ScriptObject {
// initialized by nasgen
+ @SuppressWarnings("unused")
private static PropertyMap $nasgenmap$;
- NativeMath() {
- super(Global.objectPrototype(), $nasgenmap$);
+ private NativeMath() {
+ // don't create me!
+ throw new UnsupportedOperationException();
}
/** ECMA 15.8.1.1 - E, always a double constant. Not writable or configurable */
diff --git a/nashorn/src/jdk/nashorn/internal/objects/NativeNumber.java b/nashorn/src/jdk/nashorn/internal/objects/NativeNumber.java
index 94a7cca1a4d..c69478967f4 100644
--- a/nashorn/src/jdk/nashorn/internal/objects/NativeNumber.java
+++ b/nashorn/src/jdk/nashorn/internal/objects/NativeNumber.java
@@ -87,17 +87,26 @@ public final class NativeNumber extends ScriptObject {
// initialized by nasgen
private static PropertyMap $nasgenmap$;
- NativeNumber(final double value) {
- this(value, Global.instance().getNumberPrototype());
+ static PropertyMap getInitialMap() {
+ return $nasgenmap$;
}
- private NativeNumber(final double value, final ScriptObject proto) {
- super(proto, $nasgenmap$);
+ private NativeNumber(final double value, final ScriptObject proto, final PropertyMap map) {
+ super(proto, map);
this.value = value;
this.isInt = isRepresentableAsInt(value);
this.isLong = isRepresentableAsLong(value);
}
+ NativeNumber(final double value, final Global global) {
+ this(value, global.getNumberPrototype(), global.getNumberMap());
+ }
+
+ private NativeNumber(final double value) {
+ this(value, Global.instance());
+ }
+
+
@Override
public String safeToString() {
return "[Number " + toString() + "]";
@@ -165,16 +174,7 @@ public final class NativeNumber extends ScriptObject {
public static Object constructor(final boolean newObj, final Object self, final Object... args) {
final double num = (args.length > 0) ? JSType.toNumber(args[0]) : 0.0;
- if (newObj) {
- final ScriptObject proto =
- (self instanceof ScriptObject) ?
- ((ScriptObject)self).getProto() :
- Global.instance().getNumberPrototype();
-
- return new NativeNumber(num, proto);
- }
-
- return num;
+ return newObj? new NativeNumber(num) : num;
}
/**
@@ -380,10 +380,6 @@ public final class NativeNumber extends ScriptObject {
}
private static MethodHandle findWrapFilter() {
- try {
- return MethodHandles.lookup().findStatic(NativeNumber.class, "wrapFilter", MH.type(NativeNumber.class, Object.class));
- } catch (final NoSuchMethodException | IllegalAccessException e) {
- throw new MethodHandleFactory.LookupException(e);
- }
+ return MH.findStatic(MethodHandles.lookup(), NativeNumber.class, "wrapFilter", MH.type(NativeNumber.class, Object.class));
}
}
diff --git a/nashorn/src/jdk/nashorn/internal/objects/NativeObject.java b/nashorn/src/jdk/nashorn/internal/objects/NativeObject.java
index 1034034506b..6e4791bd20c 100644
--- a/nashorn/src/jdk/nashorn/internal/objects/NativeObject.java
+++ b/nashorn/src/jdk/nashorn/internal/objects/NativeObject.java
@@ -27,7 +27,6 @@ package jdk.nashorn.internal.objects;
import static jdk.nashorn.internal.runtime.ECMAErrors.typeError;
import static jdk.nashorn.internal.runtime.ScriptRuntime.UNDEFINED;
-
import jdk.nashorn.api.scripting.ScriptObjectMirror;
import jdk.nashorn.internal.objects.annotations.Attribute;
import jdk.nashorn.internal.objects.annotations.Constructor;
@@ -55,9 +54,12 @@ public final class NativeObject {
private static final InvokeByName TO_STRING = new InvokeByName("toString", ScriptObject.class);
// initialized by nasgen
+ @SuppressWarnings("unused")
private static PropertyMap $nasgenmap$;
private NativeObject() {
+ // don't create me!
+ throw new UnsupportedOperationException();
}
private static ECMAException notAnObject(final Object obj) {
diff --git a/nashorn/src/jdk/nashorn/internal/objects/NativeRangeError.java b/nashorn/src/jdk/nashorn/internal/objects/NativeRangeError.java
index faf68f871f7..d51a0c09d41 100644
--- a/nashorn/src/jdk/nashorn/internal/objects/NativeRangeError.java
+++ b/nashorn/src/jdk/nashorn/internal/objects/NativeRangeError.java
@@ -58,8 +58,12 @@ public final class NativeRangeError extends ScriptObject {
// initialized by nasgen
private static PropertyMap $nasgenmap$;
- NativeRangeError(final Object msg) {
- super(Global.instance().getRangeErrorPrototype(), $nasgenmap$);
+ static PropertyMap getInitialMap() {
+ return $nasgenmap$;
+ }
+
+ private NativeRangeError(final Object msg, final ScriptObject proto, final PropertyMap map) {
+ super(proto, map);
if (msg != UNDEFINED) {
this.instMessage = JSType.toString(msg);
} else {
@@ -67,6 +71,14 @@ public final class NativeRangeError extends ScriptObject {
}
}
+ NativeRangeError(final Object msg, final Global global) {
+ this(msg, global.getRangeErrorPrototype(), global.getRangeErrorMap());
+ }
+
+ private NativeRangeError(final Object msg) {
+ this(msg, Global.instance());
+ }
+
@Override
public String getClassName() {
return "Error";
diff --git a/nashorn/src/jdk/nashorn/internal/objects/NativeReferenceError.java b/nashorn/src/jdk/nashorn/internal/objects/NativeReferenceError.java
index 954eed641f5..a269b51520a 100644
--- a/nashorn/src/jdk/nashorn/internal/objects/NativeReferenceError.java
+++ b/nashorn/src/jdk/nashorn/internal/objects/NativeReferenceError.java
@@ -58,8 +58,12 @@ public final class NativeReferenceError extends ScriptObject {
// initialized by nasgen
private static PropertyMap $nasgenmap$;
- NativeReferenceError(final Object msg) {
- super(Global.instance().getReferenceErrorPrototype(), $nasgenmap$);
+ static PropertyMap getInitialMap() {
+ return $nasgenmap$;
+ }
+
+ private NativeReferenceError(final Object msg, final ScriptObject proto, final PropertyMap map) {
+ super(proto, map);
if (msg != UNDEFINED) {
this.instMessage = JSType.toString(msg);
} else {
@@ -67,6 +71,14 @@ public final class NativeReferenceError extends ScriptObject {
}
}
+ NativeReferenceError(final Object msg, final Global global) {
+ this(msg, global.getReferenceErrorPrototype(), global.getReferenceErrorMap());
+ }
+
+ private NativeReferenceError(final Object msg) {
+ this(msg, Global.instance());
+ }
+
@Override
public String getClassName() {
return "Error";
diff --git a/nashorn/src/jdk/nashorn/internal/objects/NativeRegExp.java b/nashorn/src/jdk/nashorn/internal/objects/NativeRegExp.java
index bec8b37db0a..e6aa4be4357 100644
--- a/nashorn/src/jdk/nashorn/internal/objects/NativeRegExp.java
+++ b/nashorn/src/jdk/nashorn/internal/objects/NativeRegExp.java
@@ -68,9 +68,20 @@ public final class NativeRegExp extends ScriptObject {
private Global globalObject;
// initialized by nasgen
+ @SuppressWarnings("unused")
private static PropertyMap $nasgenmap$;
- NativeRegExp(final String input, final String flagString) {
+ static PropertyMap getInitialMap() {
+ return $nasgenmap$;
+ }
+
+ private NativeRegExp(final Global global) {
+ super(global.getRegExpPrototype(), global.getRegExpMap());
+ this.globalObject = global;
+ }
+
+ NativeRegExp(final String input, final String flagString, final Global global) {
+ this(global);
try {
this.regexp = RegExpFactory.create(input, flagString);
} catch (final ParserException e) {
@@ -80,17 +91,24 @@ public final class NativeRegExp extends ScriptObject {
}
this.setLastIndex(0);
- init();
+ }
+
+ NativeRegExp(final String input, final String flagString) {
+ this(input, flagString, Global.instance());
+ }
+
+ NativeRegExp(final String string, final Global global) {
+ this(string, "", global);
}
NativeRegExp(final String string) {
- this(string, "");
+ this(string, Global.instance());
}
NativeRegExp(final NativeRegExp regExp) {
+ this(Global.instance());
this.lastIndex = regExp.getLastIndexObject();
this.regexp = regExp.getRegExp();
- init();
}
@Override
@@ -614,7 +632,7 @@ public final class NativeRegExp extends ScriptObject {
return null;
}
- return new NativeRegExpExecResult(match);
+ return new NativeRegExpExecResult(match, globalObject);
}
/**
@@ -885,12 +903,6 @@ public final class NativeRegExp extends ScriptObject {
this.lastIndex = JSType.toObject(lastIndex);
}
- private void init() {
- // Keep reference to global object to support "static" properties of RegExp
- this.globalObject = Global.instance();
- this.setProto(globalObject.getRegExpPrototype());
- }
-
private static NativeRegExp checkRegExp(final Object self) {
Global.checkObjectCoercible(self);
if (self instanceof NativeRegExp) {
diff --git a/nashorn/src/jdk/nashorn/internal/objects/NativeRegExpExecResult.java b/nashorn/src/jdk/nashorn/internal/objects/NativeRegExpExecResult.java
index 667205528ed..3508e5f67d1 100644
--- a/nashorn/src/jdk/nashorn/internal/objects/NativeRegExpExecResult.java
+++ b/nashorn/src/jdk/nashorn/internal/objects/NativeRegExpExecResult.java
@@ -53,8 +53,12 @@ public final class NativeRegExpExecResult extends ScriptObject {
// initialized by nasgen
private static PropertyMap $nasgenmap$;
- NativeRegExpExecResult(final RegExpResult result) {
- super(Global.instance().getArrayPrototype(), $nasgenmap$);
+ static PropertyMap getInitialMap() {
+ return $nasgenmap$;
+ }
+
+ NativeRegExpExecResult(final RegExpResult result, final Global global) {
+ super(global.getArrayPrototype(), global.getRegExpExecResultMap());
setIsArray();
this.setArray(ArrayData.allocate(result.getGroups().clone()));
this.index = result.getIndex();
diff --git a/nashorn/src/jdk/nashorn/internal/objects/NativeStrictArguments.java b/nashorn/src/jdk/nashorn/internal/objects/NativeStrictArguments.java
index cf434f9fce4..de6e4b51435 100644
--- a/nashorn/src/jdk/nashorn/internal/objects/NativeStrictArguments.java
+++ b/nashorn/src/jdk/nashorn/internal/objects/NativeStrictArguments.java
@@ -30,14 +30,14 @@ import static jdk.nashorn.internal.lookup.Lookup.MH;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
+import java.util.ArrayList;
import java.util.Arrays;
+import jdk.nashorn.internal.runtime.AccessorProperty;
import jdk.nashorn.internal.runtime.Property;
import jdk.nashorn.internal.runtime.PropertyMap;
import jdk.nashorn.internal.runtime.ScriptFunction;
import jdk.nashorn.internal.runtime.ScriptObject;
import jdk.nashorn.internal.runtime.arrays.ArrayData;
-import jdk.nashorn.internal.lookup.Lookup;
-import jdk.nashorn.internal.lookup.MethodHandleFactory;
/**
* ECMA 10.6 Arguments Object.
@@ -54,21 +54,26 @@ public final class NativeStrictArguments extends ScriptObject {
private static final PropertyMap map$;
static {
- PropertyMap map = PropertyMap.newMap(NativeStrictArguments.class);
- map = Lookup.newProperty(map, "length", Property.NOT_ENUMERABLE, G$LENGTH, S$LENGTH);
+ final ArrayList properties = new ArrayList<>(1);
+ properties.add(AccessorProperty.create("length", Property.NOT_ENUMERABLE, G$LENGTH, S$LENGTH));
+ PropertyMap map = PropertyMap.newMap(properties);
// In strict mode, the caller and callee properties should throw TypeError
// Need to add properties directly to map since slots are assigned speculatively by newUserAccessors.
final int flags = Property.NOT_ENUMERABLE | Property.NOT_CONFIGURABLE;
map = map.addProperty(map.newUserAccessors("caller", flags));
map = map.addProperty(map.newUserAccessors("callee", flags));
- map$ = map;
+ map$ = map.setIsShared();
+ }
+
+ static PropertyMap getInitialMap() {
+ return map$;
}
private Object length;
private final Object[] namedArgs;
- NativeStrictArguments(final ScriptObject proto, final Object[] values, final int numParams) {
- super(proto, map$);
+ NativeStrictArguments(final Object[] values, final int numParams,final ScriptObject proto, final PropertyMap map) {
+ super(proto, map);
setIsArguments();
final ScriptFunction func = ScriptFunctionImpl.getTypeErrorThrower();
@@ -143,10 +148,6 @@ public final class NativeStrictArguments extends ScriptObject {
}
private static MethodHandle findOwnMH(final String name, final Class> rtype, final Class>... types) {
- try {
- return MethodHandles.lookup().findStatic(NativeStrictArguments.class, name, MH.type(rtype, types));
- } catch (final NoSuchMethodException | IllegalAccessException e) {
- throw new MethodHandleFactory.LookupException(e);
- }
+ return MH.findStatic(MethodHandles.lookup(), NativeStrictArguments.class, name, MH.type(rtype, types));
}
}
diff --git a/nashorn/src/jdk/nashorn/internal/objects/NativeString.java b/nashorn/src/jdk/nashorn/internal/objects/NativeString.java
index a5b9ea83e54..aa2eec63571 100644
--- a/nashorn/src/jdk/nashorn/internal/objects/NativeString.java
+++ b/nashorn/src/jdk/nashorn/internal/objects/NativeString.java
@@ -41,7 +41,7 @@ import java.util.Locale;
import jdk.internal.dynalink.CallSiteDescriptor;
import jdk.internal.dynalink.linker.GuardedInvocation;
import jdk.internal.dynalink.linker.LinkRequest;
-import jdk.nashorn.internal.lookup.MethodHandleFactory;
+import jdk.nashorn.internal.lookup.MethodHandleFactory.LookupException;
import jdk.nashorn.internal.objects.annotations.Attribute;
import jdk.nashorn.internal.objects.annotations.Constructor;
import jdk.nashorn.internal.objects.annotations.Function;
@@ -74,12 +74,20 @@ public final class NativeString extends ScriptObject {
// initialized by nasgen
private static PropertyMap $nasgenmap$;
- NativeString(final CharSequence value) {
- this(value, Global.instance().getStringPrototype());
+ static PropertyMap getInitialMap() {
+ return $nasgenmap$;
}
- private NativeString(final CharSequence value, final ScriptObject proto) {
- super(proto, $nasgenmap$);
+ private NativeString(final CharSequence value) {
+ this(value, Global.instance());
+ }
+
+ NativeString(final CharSequence value, final Global global) {
+ this(value, global.getStringPrototype(), global.getStringMap());
+ }
+
+ private NativeString(final CharSequence value, final ScriptObject proto, final PropertyMap map) {
+ super(proto, map);
assert value instanceof String || value instanceof ConsString;
this.value = value;
}
@@ -147,9 +155,9 @@ public final class NativeString extends ScriptObject {
if (returnType == Object.class && (self instanceof String || self instanceof ConsString)) {
try {
- MethodHandle mh = MethodHandles.lookup().findStatic(NativeString.class, "get", desc.getMethodType());
+ MethodHandle mh = MH.findStatic(MethodHandles.lookup(), NativeString.class, "get", desc.getMethodType());
return new GuardedInvocation(mh, NashornGuards.getInstanceOf2Guard(String.class, ConsString.class));
- } catch (final NoSuchMethodException | IllegalAccessException e) {
+ } catch (final LookupException e) {
// Shouldn't happen. Fall back to super
}
}
@@ -1065,10 +1073,7 @@ public final class NativeString extends ScriptObject {
}
private static Object newObj(final Object self, final CharSequence str) {
- if (self instanceof ScriptObject) {
- return new NativeString(str, ((ScriptObject)self).getProto());
- }
- return new NativeString(str, Global.instance().getStringPrototype());
+ return new NativeString(str);
}
/**
@@ -1202,10 +1207,6 @@ public final class NativeString extends ScriptObject {
}
private static MethodHandle findWrapFilter() {
- try {
- return MethodHandles.lookup().findStatic(NativeString.class, "wrapFilter", MH.type(NativeString.class, Object.class));
- } catch (final NoSuchMethodException | IllegalAccessException e) {
- throw new MethodHandleFactory.LookupException(e);
- }
+ return MH.findStatic(MethodHandles.lookup(), NativeString.class, "wrapFilter", MH.type(NativeString.class, Object.class));
}
}
diff --git a/nashorn/src/jdk/nashorn/internal/objects/NativeSyntaxError.java b/nashorn/src/jdk/nashorn/internal/objects/NativeSyntaxError.java
index d7d04bbaa6e..45920ba7aec 100644
--- a/nashorn/src/jdk/nashorn/internal/objects/NativeSyntaxError.java
+++ b/nashorn/src/jdk/nashorn/internal/objects/NativeSyntaxError.java
@@ -58,8 +58,12 @@ public final class NativeSyntaxError extends ScriptObject {
// initialized by nasgen
private static PropertyMap $nasgenmap$;
- NativeSyntaxError(final Object msg) {
- super(Global.instance().getSyntaxErrorPrototype(), $nasgenmap$);
+ static PropertyMap getInitialMap() {
+ return $nasgenmap$;
+ }
+
+ NativeSyntaxError(final Object msg, final Global global) {
+ super(global.getSyntaxErrorPrototype(), global.getSyntaxErrorMap());
if (msg != UNDEFINED) {
this.instMessage = JSType.toString(msg);
} else {
@@ -67,6 +71,10 @@ public final class NativeSyntaxError extends ScriptObject {
}
}
+ private NativeSyntaxError(final Object msg) {
+ this(msg, Global.instance());
+ }
+
@Override
public String getClassName() {
return "Error";
diff --git a/nashorn/src/jdk/nashorn/internal/objects/NativeTypeError.java b/nashorn/src/jdk/nashorn/internal/objects/NativeTypeError.java
index c811a530569..2b2308b143e 100644
--- a/nashorn/src/jdk/nashorn/internal/objects/NativeTypeError.java
+++ b/nashorn/src/jdk/nashorn/internal/objects/NativeTypeError.java
@@ -58,8 +58,12 @@ public final class NativeTypeError extends ScriptObject {
// initialized by nasgen
private static PropertyMap $nasgenmap$;
- NativeTypeError(final Object msg) {
- super(Global.instance().getTypeErrorPrototype(), $nasgenmap$);
+ static PropertyMap getInitialMap() {
+ return $nasgenmap$;
+ }
+
+ NativeTypeError(final Object msg, final Global global) {
+ super(global.getTypeErrorPrototype(), global.getTypeErrorMap());
if (msg != UNDEFINED) {
this.instMessage = JSType.toString(msg);
} else {
@@ -67,6 +71,10 @@ public final class NativeTypeError extends ScriptObject {
}
}
+ private NativeTypeError(final Object msg) {
+ this(msg, Global.instance());
+ }
+
@Override
public String getClassName() {
return "Error";
diff --git a/nashorn/src/jdk/nashorn/internal/objects/NativeURIError.java b/nashorn/src/jdk/nashorn/internal/objects/NativeURIError.java
index 80df6c28529..2caf136954d 100644
--- a/nashorn/src/jdk/nashorn/internal/objects/NativeURIError.java
+++ b/nashorn/src/jdk/nashorn/internal/objects/NativeURIError.java
@@ -57,8 +57,12 @@ public final class NativeURIError extends ScriptObject {
// initialized by nasgen
private static PropertyMap $nasgenmap$;
- NativeURIError(final Object msg) {
- super(Global.instance().getURIErrorPrototype(), $nasgenmap$);
+ static PropertyMap getInitialMap() {
+ return $nasgenmap$;
+ }
+
+ NativeURIError(final Object msg, final Global global) {
+ super(global.getURIErrorPrototype(), global.getURIErrorMap());
if (msg != UNDEFINED) {
this.instMessage = JSType.toString(msg);
} else {
@@ -66,6 +70,10 @@ public final class NativeURIError extends ScriptObject {
}
}
+ private NativeURIError(final Object msg) {
+ this(msg, Global.instance());
+ }
+
@Override
public String getClassName() {
return "Error";
diff --git a/nashorn/src/jdk/nashorn/internal/objects/NativeUint16Array.java b/nashorn/src/jdk/nashorn/internal/objects/NativeUint16Array.java
index 39c19131280..7c37bac9f6e 100644
--- a/nashorn/src/jdk/nashorn/internal/objects/NativeUint16Array.java
+++ b/nashorn/src/jdk/nashorn/internal/objects/NativeUint16Array.java
@@ -47,6 +47,7 @@ public final class NativeUint16Array extends ArrayBufferView {
public static final int BYTES_PER_ELEMENT = 2;
// initialized by nasgen
+ @SuppressWarnings("unused")
private static PropertyMap $nasgenmap$;
private static final Factory FACTORY = new Factory(BYTES_PER_ELEMENT) {
@@ -149,7 +150,7 @@ public final class NativeUint16Array extends ArrayBufferView {
}
@Override
- protected ScriptObject getPrototype() {
- return Global.instance().getUint16ArrayPrototype();
+ protected ScriptObject getPrototype(final Global global) {
+ return global.getUint16ArrayPrototype();
}
}
diff --git a/nashorn/src/jdk/nashorn/internal/objects/NativeUint32Array.java b/nashorn/src/jdk/nashorn/internal/objects/NativeUint32Array.java
index 37102bae590..9b51db48d0d 100644
--- a/nashorn/src/jdk/nashorn/internal/objects/NativeUint32Array.java
+++ b/nashorn/src/jdk/nashorn/internal/objects/NativeUint32Array.java
@@ -48,6 +48,7 @@ public final class NativeUint32Array extends ArrayBufferView {
public static final int BYTES_PER_ELEMENT = 4;
// initialized by nasgen
+ @SuppressWarnings("unused")
private static PropertyMap $nasgenmap$;
private static final Factory FACTORY = new Factory(BYTES_PER_ELEMENT) {
@@ -168,7 +169,7 @@ public final class NativeUint32Array extends ArrayBufferView {
}
@Override
- protected ScriptObject getPrototype() {
- return Global.instance().getUint32ArrayPrototype();
+ protected ScriptObject getPrototype(final Global global) {
+ return global.getUint32ArrayPrototype();
}
}
diff --git a/nashorn/src/jdk/nashorn/internal/objects/NativeUint8Array.java b/nashorn/src/jdk/nashorn/internal/objects/NativeUint8Array.java
index aa6f89bec67..be4e59d368b 100644
--- a/nashorn/src/jdk/nashorn/internal/objects/NativeUint8Array.java
+++ b/nashorn/src/jdk/nashorn/internal/objects/NativeUint8Array.java
@@ -47,6 +47,7 @@ public final class NativeUint8Array extends ArrayBufferView {
public static final int BYTES_PER_ELEMENT = 1;
// initialized by nasgen
+ @SuppressWarnings("unused")
private static PropertyMap $nasgenmap$;
private static final Factory FACTORY = new Factory(BYTES_PER_ELEMENT) {
@@ -142,7 +143,7 @@ public final class NativeUint8Array extends ArrayBufferView {
}
@Override
- protected ScriptObject getPrototype() {
- return Global.instance().getUint8ArrayPrototype();
+ protected ScriptObject getPrototype(final Global global) {
+ return global.getUint8ArrayPrototype();
}
}
diff --git a/nashorn/src/jdk/nashorn/internal/objects/NativeUint8ClampedArray.java b/nashorn/src/jdk/nashorn/internal/objects/NativeUint8ClampedArray.java
index 4467c856f06..43b777ba346 100644
--- a/nashorn/src/jdk/nashorn/internal/objects/NativeUint8ClampedArray.java
+++ b/nashorn/src/jdk/nashorn/internal/objects/NativeUint8ClampedArray.java
@@ -48,6 +48,7 @@ public final class NativeUint8ClampedArray extends ArrayBufferView {
public static final int BYTES_PER_ELEMENT = 1;
// initialized by nasgen
+ @SuppressWarnings("unused")
private static PropertyMap $nasgenmap$;
private static final Factory FACTORY = new Factory(BYTES_PER_ELEMENT) {
@@ -159,7 +160,7 @@ public final class NativeUint8ClampedArray extends ArrayBufferView {
}
@Override
- protected ScriptObject getPrototype() {
- return Global.instance().getUint8ClampedArrayPrototype();
+ protected ScriptObject getPrototype(final Global global) {
+ return global.getUint8ClampedArrayPrototype();
}
}
diff --git a/nashorn/src/jdk/nashorn/internal/objects/PrototypeObject.java b/nashorn/src/jdk/nashorn/internal/objects/PrototypeObject.java
index 3a7205f9bba..837fee8b789 100644
--- a/nashorn/src/jdk/nashorn/internal/objects/PrototypeObject.java
+++ b/nashorn/src/jdk/nashorn/internal/objects/PrototypeObject.java
@@ -30,12 +30,12 @@ import static jdk.nashorn.internal.lookup.Lookup.MH;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
+import java.util.ArrayList;
+import jdk.nashorn.internal.runtime.AccessorProperty;
import jdk.nashorn.internal.runtime.Property;
import jdk.nashorn.internal.runtime.PropertyMap;
import jdk.nashorn.internal.runtime.ScriptFunction;
import jdk.nashorn.internal.runtime.ScriptObject;
-import jdk.nashorn.internal.lookup.Lookup;
-import jdk.nashorn.internal.lookup.MethodHandleFactory;
/**
* Instances of this class serve as "prototype" object for script functions.
@@ -52,13 +52,22 @@ public class PrototypeObject extends ScriptObject {
private static final MethodHandle SET_CONSTRUCTOR = findOwnMH("setConstructor", void.class, Object.class, Object.class);
static {
- PropertyMap map = PropertyMap.newMap(PrototypeObject.class);
- map = Lookup.newProperty(map, "constructor", Property.NOT_ENUMERABLE, GET_CONSTRUCTOR, SET_CONSTRUCTOR);
- map$ = map;
+ final ArrayList properties = new ArrayList<>(1);
+ properties.add(AccessorProperty.create("constructor", Property.NOT_ENUMERABLE, GET_CONSTRUCTOR, SET_CONSTRUCTOR));
+ map$ = PropertyMap.newMap(properties).setIsShared();
+ }
+
+ static PropertyMap getInitialMap() {
+ return map$;
+ }
+
+ private PrototypeObject(final Global global, final PropertyMap map) {
+ super(map != map$? map.addAll(global.getPrototypeObjectMap()) : global.getPrototypeObjectMap());
+ setProto(global.getObjectPrototype());
}
PrototypeObject() {
- this(map$);
+ this(Global.instance(), map$);
}
/**
@@ -67,12 +76,11 @@ public class PrototypeObject extends ScriptObject {
* @param map property map
*/
public PrototypeObject(final PropertyMap map) {
- super(map != map$ ? map.addAll(map$) : map$);
- setProto(Global.objectPrototype());
+ this(Global.instance(), map);
}
PrototypeObject(final ScriptFunction func) {
- this(map$);
+ this(Global.instance(), map$);
this.constructor = func;
}
@@ -107,10 +115,6 @@ public class PrototypeObject extends ScriptObject {
}
private static MethodHandle findOwnMH(final String name, final Class> rtype, final Class>... types) {
- try {
- return MethodHandles.lookup().findStatic(PrototypeObject.class, name, MH.type(rtype, types));
- } catch (final NoSuchMethodException | IllegalAccessException e) {
- throw new MethodHandleFactory.LookupException(e);
- }
+ return MH.findStatic(MethodHandles.lookup(), PrototypeObject.class, name, MH.type(rtype, types));
}
}
diff --git a/nashorn/src/jdk/nashorn/internal/objects/ScriptFunctionImpl.java b/nashorn/src/jdk/nashorn/internal/objects/ScriptFunctionImpl.java
index 6834ef4b701..643d9acddf3 100644
--- a/nashorn/src/jdk/nashorn/internal/objects/ScriptFunctionImpl.java
+++ b/nashorn/src/jdk/nashorn/internal/objects/ScriptFunctionImpl.java
@@ -28,6 +28,7 @@ package jdk.nashorn.internal.objects;
import static jdk.nashorn.internal.runtime.ScriptRuntime.UNDEFINED;
import java.lang.invoke.MethodHandle;
+import java.util.ArrayList;
import jdk.nashorn.internal.runtime.GlobalFunctions;
import jdk.nashorn.internal.runtime.Property;
import jdk.nashorn.internal.runtime.PropertyMap;
@@ -36,6 +37,7 @@ import jdk.nashorn.internal.runtime.ScriptFunction;
import jdk.nashorn.internal.runtime.ScriptFunctionData;
import jdk.nashorn.internal.runtime.ScriptObject;
import jdk.nashorn.internal.lookup.Lookup;
+import jdk.nashorn.internal.runtime.AccessorProperty;
/**
* Concrete implementation of ScriptFunction. This sets correct map for the
@@ -53,9 +55,30 @@ public class ScriptFunctionImpl extends ScriptFunction {
// property map for non-strict, non-bound functions.
private static final PropertyMap map$;
+ static PropertyMap getInitialMap() {
+ return map$;
+ }
+
+ static PropertyMap getInitialAnonymousMap() {
+ return AnonymousFunction.getInitialMap();
+ }
+
+ static PropertyMap getInitialStrictMap() {
+ return strictmodemap$;
+ }
+
+ static PropertyMap getInitialBoundMap() {
+ return boundfunctionmap$;
+ }
+
// Marker object for lazily initialized prototype object
private static final Object LAZY_PROTOTYPE = new Object();
+ private ScriptFunctionImpl(final String name, final MethodHandle invokeHandle, final MethodHandle[] specs, final Global global) {
+ super(name, invokeHandle, global.getFunctionMap(), null, specs, false, true, true);
+ init(global);
+ }
+
/**
* Constructor called by Nasgen generated code, no membercount, use the default map.
* Creates builtin functions only.
@@ -65,8 +88,12 @@ public class ScriptFunctionImpl extends ScriptFunction {
* @param specs specialized versions of this method, if available, null otherwise
*/
ScriptFunctionImpl(final String name, final MethodHandle invokeHandle, final MethodHandle[] specs) {
- super(name, invokeHandle, map$, null, specs, false, true, true);
- init();
+ this(name, invokeHandle, specs, Global.instance());
+ }
+
+ private ScriptFunctionImpl(final String name, final MethodHandle invokeHandle, final PropertyMap map, final MethodHandle[] specs, final Global global) {
+ super(name, invokeHandle, map.addAll(global.getFunctionMap()), null, specs, false, true, true);
+ init(global);
}
/**
@@ -79,8 +106,12 @@ public class ScriptFunctionImpl extends ScriptFunction {
* @param specs specialized versions of this method, if available, null otherwise
*/
ScriptFunctionImpl(final String name, final MethodHandle invokeHandle, final PropertyMap map, final MethodHandle[] specs) {
- super(name, invokeHandle, map.addAll(map$), null, specs, false, true, true);
- init();
+ this(name, invokeHandle, map, specs, Global.instance());
+ }
+
+ private ScriptFunctionImpl(final String name, final MethodHandle methodHandle, final ScriptObject scope, final MethodHandle[] specs, final boolean isStrict, final boolean isBuiltin, final boolean isConstructor, final Global global) {
+ super(name, methodHandle, getMap(global, isStrict), scope, specs, isStrict, isBuiltin, isConstructor);
+ init(global);
}
/**
@@ -95,8 +126,12 @@ public class ScriptFunctionImpl extends ScriptFunction {
* @param isConstructor can the function be used as a constructor (most can; some built-ins are restricted).
*/
ScriptFunctionImpl(final String name, final MethodHandle methodHandle, final ScriptObject scope, final MethodHandle[] specs, final boolean isStrict, final boolean isBuiltin, final boolean isConstructor) {
- super(name, methodHandle, getMap(isStrict), scope, specs, isStrict, isBuiltin, isConstructor);
- init();
+ this(name, methodHandle, scope, specs, isStrict, isBuiltin, isConstructor, Global.instance());
+ }
+
+ private ScriptFunctionImpl(final RecompilableScriptFunctionData data, final ScriptObject scope, final Global global) {
+ super(data, getMap(global, data.isStrict()), scope);
+ init(global);
}
/**
@@ -106,27 +141,32 @@ public class ScriptFunctionImpl extends ScriptFunction {
* @param scope scope object
*/
public ScriptFunctionImpl(final RecompilableScriptFunctionData data, final ScriptObject scope) {
- super(data, getMap(data.isStrict()), scope);
- init();
+ this(data, scope, Global.instance());
}
/**
* Only invoked internally from {@link BoundScriptFunctionImpl} constructor.
* @param data the script function data for the bound function.
+ * @param global the global object
*/
- ScriptFunctionImpl(final ScriptFunctionData data) {
- super(data, boundfunctionmap$, null);
- init();
+ ScriptFunctionImpl(final ScriptFunctionData data, final Global global) {
+ super(data, global.getBoundFunctionMap(), null);
+ init(global);
}
static {
- PropertyMap map = PropertyMap.newMap(ScriptFunctionImpl.class);
- map = Lookup.newProperty(map, "prototype", Property.NOT_ENUMERABLE | Property.NOT_CONFIGURABLE, G$PROTOTYPE, S$PROTOTYPE);
- map = Lookup.newProperty(map, "length", Property.NOT_ENUMERABLE | Property.NOT_CONFIGURABLE | Property.NOT_WRITABLE, G$LENGTH, null);
- map = Lookup.newProperty(map, "name", Property.NOT_ENUMERABLE | Property.NOT_CONFIGURABLE | Property.NOT_WRITABLE, G$NAME, null);
- map$ = map;
+ final ArrayList properties = new ArrayList<>(3);
+ properties.add(AccessorProperty.create("prototype", Property.NOT_ENUMERABLE | Property.NOT_CONFIGURABLE, G$PROTOTYPE, S$PROTOTYPE));
+ properties.add(AccessorProperty.create("length", Property.NOT_ENUMERABLE | Property.NOT_CONFIGURABLE | Property.NOT_WRITABLE, G$LENGTH, null));
+ properties.add(AccessorProperty.create("name", Property.NOT_ENUMERABLE | Property.NOT_CONFIGURABLE | Property.NOT_WRITABLE, G$NAME, null));
+ map$ = PropertyMap.newMap(properties);
strictmodemap$ = createStrictModeMap(map$);
boundfunctionmap$ = createBoundFunctionMap(strictmodemap$);
+ // There are order dependencies between normal map, struct map and bound map
+ // We can make these 'shared' only after initialization of all three.
+ map$.setIsShared();
+ strictmodemap$.setIsShared();
+ boundfunctionmap$.setIsShared();
}
// function object representing TypeErrorThrower
@@ -149,17 +189,18 @@ public class ScriptFunctionImpl extends ScriptFunction {
return typeErrorThrower;
}
- private static PropertyMap createStrictModeMap(PropertyMap map) {
+ private static PropertyMap createStrictModeMap(final PropertyMap map) {
final int flags = Property.NOT_ENUMERABLE | Property.NOT_CONFIGURABLE;
+ PropertyMap newMap = map;
// Need to add properties directly to map since slots are assigned speculatively by newUserAccessors.
- map = map.addProperty(map.newUserAccessors("arguments", flags));
- map = map.addProperty(map.newUserAccessors("caller", flags));
- return map;
+ newMap = newMap.addProperty(map.newUserAccessors("arguments", flags));
+ newMap = newMap.addProperty(map.newUserAccessors("caller", flags));
+ return newMap;
}
// Choose the map based on strict mode!
- private static PropertyMap getMap(final boolean strict) {
- return strict ? strictmodemap$ : map$;
+ private static PropertyMap getMap(final Global global, final boolean strict) {
+ return strict ? global.getStrictFunctionMap() : global.getFunctionMap();
}
private static PropertyMap createBoundFunctionMap(final PropertyMap strictModeMap) {
@@ -171,15 +212,19 @@ public class ScriptFunctionImpl extends ScriptFunction {
// Instance of this class is used as global anonymous function which
// serves as Function.prototype object.
private static class AnonymousFunction extends ScriptFunctionImpl {
- private static final PropertyMap nasgenmap$$ = PropertyMap.newMap(AnonymousFunction.class);
+ private static final PropertyMap map$ = PropertyMap.newMap().setIsShared();
- AnonymousFunction() {
- super("", GlobalFunctions.ANONYMOUS, nasgenmap$$, null);
+ static PropertyMap getInitialMap() {
+ return map$;
+ }
+
+ AnonymousFunction(final Global global) {
+ super("", GlobalFunctions.ANONYMOUS, global.getAnonymousFunctionMap(), null);
}
}
- static ScriptFunctionImpl newAnonymousFunction() {
- return new AnonymousFunction();
+ static ScriptFunctionImpl newAnonymousFunction(final Global global) {
+ return new AnonymousFunction(global);
}
/**
@@ -254,8 +299,8 @@ public class ScriptFunctionImpl extends ScriptFunction {
}
// Internals below..
- private void init() {
- this.setProto(Global.instance().getFunctionPrototype());
+ private void init(final Global global) {
+ this.setProto(global.getFunctionPrototype());
this.prototype = LAZY_PROTOTYPE;
// We have to fill user accessor functions late as these are stored
diff --git a/nashorn/src/jdk/nashorn/internal/parser/Parser.java b/nashorn/src/jdk/nashorn/internal/parser/Parser.java
index 181dcf83dd4..fd0136e463c 100644
--- a/nashorn/src/jdk/nashorn/internal/parser/Parser.java
+++ b/nashorn/src/jdk/nashorn/internal/parser/Parser.java
@@ -1084,6 +1084,12 @@ loop:
switch (type) {
case SEMICOLON:
// for (init; test; modify)
+
+ // for each (init; test; modify) is invalid
+ if (forNode.isForEach()) {
+ throw error(AbstractParser.message("for.each.without.in"), token);
+ }
+
expect(SEMICOLON);
if (type != SEMICOLON) {
forNode = forNode.setTest(lc, expression());
@@ -2003,7 +2009,7 @@ loop:
}
if (!redefinitionOk) {
- throw error(AbstractParser.message("property.redefinition", key.toString()), property.getToken());
+ throw error(AbstractParser.message("property.redefinition", key), property.getToken());
}
PropertyNode newProperty = existingProperty;
@@ -2951,7 +2957,7 @@ loop:
} else {
lc.setFlag(fn, FunctionNode.HAS_NESTED_EVAL);
}
- lc.setFlag(lc.getFunctionBody(fn), Block.NEEDS_SCOPE);
+ lc.setBlockNeedsScope(lc.getFunctionBody(fn));
}
}
diff --git a/nashorn/src/jdk/nashorn/internal/parser/TokenType.java b/nashorn/src/jdk/nashorn/internal/parser/TokenType.java
index 92f3ad745be..c92b9e98284 100644
--- a/nashorn/src/jdk/nashorn/internal/parser/TokenType.java
+++ b/nashorn/src/jdk/nashorn/internal/parser/TokenType.java
@@ -93,7 +93,7 @@ public enum TokenType {
ASSIGN_BIT_OR (BINARY, "|=", 2, false),
OR (BINARY, "||", 4, true),
RBRACE (BRACKET, "}"),
- BIT_NOT (BINARY, "~", 14, false),
+ BIT_NOT (UNARY, "~", 14, false),
// ECMA 7.6.1.1 Keywords, 7.6.1.2 Future Reserved Words.
// All other Java keywords are commented out.
diff --git a/nashorn/src/jdk/nashorn/internal/runtime/AccessorProperty.java b/nashorn/src/jdk/nashorn/internal/runtime/AccessorProperty.java
index bfdfa71995d..f7ece9df533 100644
--- a/nashorn/src/jdk/nashorn/internal/runtime/AccessorProperty.java
+++ b/nashorn/src/jdk/nashorn/internal/runtime/AccessorProperty.java
@@ -75,6 +75,8 @@ public class AccessorProperty extends Property {
private static final MethodType[] ACCESSOR_GETTER_TYPES = new MethodType[NOOF_TYPES];
private static final MethodType[] ACCESSOR_SETTER_TYPES = new MethodType[NOOF_TYPES];
+ private static final MethodType ACCESSOR_GETTER_PRIMITIVE_TYPE;
+ private static final MethodType ACCESSOR_SETTER_PRIMITIVE_TYPE;
private static final MethodHandle SPILL_ELEMENT_GETTER;
private static final MethodHandle SPILL_ELEMENT_SETTER;
@@ -82,17 +84,43 @@ public class AccessorProperty extends Property {
private static final MethodHandle[] SPILL_ACCESSORS = new MethodHandle[SPILL_CACHE_SIZE * 2];
static {
+ MethodType getterPrimitiveType = null;
+ MethodType setterPrimitiveType = null;
+
for (int i = 0; i < NOOF_TYPES; i++) {
final Type type = ACCESSOR_TYPES.get(i);
ACCESSOR_GETTER_TYPES[i] = MH.type(type.getTypeClass(), Object.class);
ACCESSOR_SETTER_TYPES[i] = MH.type(void.class, Object.class, type.getTypeClass());
+
+ if (type == PRIMITIVE_TYPE) {
+ getterPrimitiveType = ACCESSOR_GETTER_TYPES[i];
+ setterPrimitiveType = ACCESSOR_SETTER_TYPES[i];
+ }
}
- final MethodHandle spillGetter = MH.getter(MethodHandles.lookup(), ScriptObject.class, "spill", Object[].class);
+ ACCESSOR_GETTER_PRIMITIVE_TYPE = getterPrimitiveType;
+ ACCESSOR_SETTER_PRIMITIVE_TYPE = setterPrimitiveType;
+
+ final MethodType spillGetterType = MethodType.methodType(Object[].class, Object.class);
+ final MethodHandle spillGetter = MH.asType(MH.getter(MethodHandles.lookup(), ScriptObject.class, "spill", Object[].class), spillGetterType);
SPILL_ELEMENT_GETTER = MH.filterArguments(MH.arrayElementGetter(Object[].class), 0, spillGetter);
SPILL_ELEMENT_SETTER = MH.filterArguments(MH.arrayElementSetter(Object[].class), 0, spillGetter);
}
+ /**
+ * Create a new accessor property. Factory method used by nasgen generated code.
+ *
+ * @param key {@link Property} key.
+ * @param propertyFlags {@link Property} flags.
+ * @param getter {@link Property} get accessor method.
+ * @param setter {@link Property} set accessor method.
+ *
+ * @return New {@link AccessorProperty} created.
+ */
+ public static AccessorProperty create(final String key, final int propertyFlags, final MethodHandle getter, final MethodHandle setter) {
+ return new AccessorProperty(key, propertyFlags, -1, getter, setter);
+ }
+
/** Seed getter for the primitive version of this field (in -Dnashorn.fields.dual=true mode) */
private MethodHandle primitiveGetter;
@@ -126,8 +154,8 @@ public class AccessorProperty extends Property {
this.primitiveGetter = bindTo(property.primitiveGetter, delegate);
this.primitiveSetter = bindTo(property.primitiveSetter, delegate);
- this.objectGetter = bindTo(property.objectGetter, delegate);
- this.objectSetter = bindTo(property.objectSetter, delegate);
+ this.objectGetter = bindTo(property.ensureObjectGetter(), delegate);
+ this.objectSetter = bindTo(property.ensureObjectSetter(), delegate);
setCurrentType(property.getCurrentType());
}
@@ -177,9 +205,8 @@ public class AccessorProperty extends Property {
ACCESSOR_GETTER_TYPES[i]);
}
} else {
- //this will work as the object setter and getter will be converted appropriately
- objectGetter = getter;
- objectSetter = setter;
+ objectGetter = getter.type() != Lookup.GET_OBJECT_TYPE ? MH.asType(getter, Lookup.GET_OBJECT_TYPE) : getter;
+ objectSetter = setter != null && setter.type() != Lookup.SET_OBJECT_TYPE ? MH.asType(setter, Lookup.SET_OBJECT_TYPE) : setter;
}
setCurrentType(getterType);
@@ -195,8 +222,8 @@ public class AccessorProperty extends Property {
setters = new MethodHandle[fieldCount];
for(int i = 0; i < fieldCount; ++i) {
final String fieldName = ObjectClassGenerator.getFieldName(i, Type.OBJECT);
- getters[i] = MH.getter(lookup, structure, fieldName, Type.OBJECT.getTypeClass());
- setters[i] = MH.setter(lookup, structure, fieldName, Type.OBJECT.getTypeClass());
+ getters[i] = MH.asType(MH.getter(lookup, structure, fieldName, Type.OBJECT.getTypeClass()), Lookup.GET_OBJECT_TYPE);
+ setters[i] = MH.asType(MH.setter(lookup, structure, fieldName, Type.OBJECT.getTypeClass()), Lookup.SET_OBJECT_TYPE);
}
}
}
@@ -224,17 +251,18 @@ public class AccessorProperty extends Property {
final MethodHandle arguments = MH.getter(lookup, structure, "arguments", Object.class);
final MethodHandle argumentsSO = MH.asType(arguments, arguments.type().changeReturnType(ScriptObject.class));
- objectGetter = MH.insertArguments(MH.filterArguments(ScriptObject.GET_ARGUMENT.methodHandle(), 0, argumentsSO), 1, slot);
- objectSetter = MH.insertArguments(MH.filterArguments(ScriptObject.SET_ARGUMENT.methodHandle(), 0, argumentsSO), 1, slot);
+ objectGetter = MH.asType(MH.insertArguments(MH.filterArguments(ScriptObject.GET_ARGUMENT.methodHandle(), 0, argumentsSO), 1, slot), Lookup.GET_OBJECT_TYPE);
+ objectSetter = MH.asType(MH.insertArguments(MH.filterArguments(ScriptObject.SET_ARGUMENT.methodHandle(), 0, argumentsSO), 1, slot), Lookup.SET_OBJECT_TYPE);
} else {
final GettersSetters gs = GETTERS_SETTERS.get(structure);
objectGetter = gs.getters[slot];
objectSetter = gs.setters[slot];
if (!OBJECT_FIELDS_ONLY) {
- final String fieldNamePrimitive = ObjectClassGenerator.getFieldName(slot, ObjectClassGenerator.PRIMITIVE_TYPE);
- primitiveGetter = MH.getter(lookup, structure, fieldNamePrimitive, PRIMITIVE_TYPE.getTypeClass());
- primitiveSetter = MH.setter(lookup, structure, fieldNamePrimitive, PRIMITIVE_TYPE.getTypeClass());
+ final String fieldNamePrimitive = ObjectClassGenerator.getFieldName(slot, PRIMITIVE_TYPE);
+ final Class> typeClass = PRIMITIVE_TYPE.getTypeClass();
+ primitiveGetter = MH.asType(MH.getter(lookup, structure, fieldNamePrimitive, typeClass), ACCESSOR_GETTER_PRIMITIVE_TYPE);
+ primitiveSetter = MH.asType(MH.setter(lookup, structure, fieldNamePrimitive, typeClass), ACCESSOR_SETTER_PRIMITIVE_TYPE);
}
}
@@ -317,24 +345,30 @@ public class AccessorProperty extends Property {
}
}
- @Override
- public MethodHandle getGetter(final Class> type) {
+ // Spill getters and setters are lazily initialized, see JDK-8011630
+ private MethodHandle ensureObjectGetter() {
if (isSpill() && objectGetter == null) {
objectGetter = getSpillGetter();
}
+ return objectGetter;
+ }
+
+ private MethodHandle ensureObjectSetter() {
+ if (isSpill() && objectSetter == null) {
+ objectSetter = getSpillSetter();
+ }
+ return objectSetter;
+ }
+
+ @Override
+ public MethodHandle getGetter(final Class> type) {
final int i = getAccessorTypeIndex(type);
+ ensureObjectGetter();
+
if (getters[i] == null) {
getters[i] = debug(
- MH.asType(
- createGetter(
- currentType,
- type,
- primitiveGetter,
- objectGetter),
- ACCESSOR_GETTER_TYPES[i]),
- currentType,
- type,
- "get");
+ createGetter(currentType, type, primitiveGetter, objectGetter),
+ currentType, type, "get");
}
return getters[i];
@@ -366,11 +400,8 @@ public class AccessorProperty extends Property {
}
private MethodHandle generateSetter(final Class> forType, final Class> type) {
- if (isSpill() && objectSetter == null) {
- objectSetter = getSpillSetter();
- }
+ ensureObjectSetter();
MethodHandle mh = createSetter(forType, type, primitiveSetter, objectSetter);
- mh = MH.asType(mh, ACCESSOR_SETTER_TYPES[getAccessorTypeIndex(type)]); //has to be the case for invokeexact to work in ScriptObject
mh = debug(mh, currentType, type, "set");
return mh;
}
@@ -423,9 +454,9 @@ public class AccessorProperty extends Property {
final int slot = getSlot();
MethodHandle getter = slot < SPILL_CACHE_SIZE ? SPILL_ACCESSORS[slot * 2] : null;
if (getter == null) {
- getter = MH.asType(MH.insertArguments(SPILL_ELEMENT_GETTER, 1, slot), Lookup.GET_OBJECT_TYPE);
+ getter = MH.insertArguments(SPILL_ELEMENT_GETTER, 1, slot);
if (slot < SPILL_CACHE_SIZE) {
- SPILL_ACCESSORS[slot * 2] = getter;
+ SPILL_ACCESSORS[slot * 2 + 0] = getter;
}
}
return getter;
@@ -435,7 +466,7 @@ public class AccessorProperty extends Property {
final int slot = getSlot();
MethodHandle setter = slot < SPILL_CACHE_SIZE ? SPILL_ACCESSORS[slot * 2 + 1] : null;
if (setter == null) {
- setter = MH.asType(MH.insertArguments(SPILL_ELEMENT_SETTER, 1, slot), Lookup.SET_OBJECT_TYPE);
+ setter = MH.insertArguments(SPILL_ELEMENT_SETTER, 1, slot);
if (slot < SPILL_CACHE_SIZE) {
SPILL_ACCESSORS[slot * 2 + 1] = setter;
}
diff --git a/nashorn/src/jdk/nashorn/internal/runtime/Context.java b/nashorn/src/jdk/nashorn/internal/runtime/Context.java
index b39eb44a179..8f00d52127e 100644
--- a/nashorn/src/jdk/nashorn/internal/runtime/Context.java
+++ b/nashorn/src/jdk/nashorn/internal/runtime/Context.java
@@ -36,7 +36,6 @@ import java.io.IOException;
import java.io.PrintWriter;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
-import java.lang.reflect.Constructor;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.AccessControlContext;
@@ -55,6 +54,7 @@ import jdk.nashorn.internal.codegen.ObjectClassGenerator;
import jdk.nashorn.internal.ir.FunctionNode;
import jdk.nashorn.internal.ir.debug.ASTWriter;
import jdk.nashorn.internal.ir.debug.PrintVisitor;
+import jdk.nashorn.internal.objects.Global;
import jdk.nashorn.internal.parser.Parser;
import jdk.nashorn.internal.runtime.options.Options;
@@ -123,8 +123,8 @@ public final class Context {
sm.checkPermission(new RuntimePermission("nashorn.setGlobal"));
}
- if (global != null && !(global instanceof GlobalObject)) {
- throw new IllegalArgumentException("global does not implement GlobalObject!");
+ if (global != null && !(global instanceof Global)) {
+ throw new IllegalArgumentException("global is not an instance of Global!");
}
setGlobalTrusted(global);
@@ -253,14 +253,7 @@ public final class Context {
this.env = new ScriptEnvironment(options, out, err);
this._strict = env._strict;
this.appLoader = appLoader;
- this.scriptLoader = (ScriptLoader)AccessController.doPrivileged(
- new PrivilegedAction() {
- @Override
- public ClassLoader run() {
- final StructureLoader structureLoader = new StructureLoader(sharedLoader, Context.this);
- return new ScriptLoader(structureLoader, Context.this);
- }
- });
+ this.scriptLoader = env._loader_per_compile? null : createNewLoader();
this.errors = errors;
// if user passed -classpath option, make a class loader with that and set it as
@@ -817,25 +810,12 @@ public final class Context {
new PrivilegedAction() {
@Override
public ScriptLoader run() {
- // Generated code won't refer to any class generated by context
- // script loader and so parent loader can be the structure
- // loader -- which is parent of the context script loader.
- return new ScriptLoader((StructureLoader)scriptLoader.getParent(), Context.this);
+ return new ScriptLoader(sharedLoader, Context.this);
}
});
}
private ScriptObject newGlobalTrusted() {
- try {
- final Class> clazz = Class.forName("jdk.nashorn.internal.objects.Global", true, scriptLoader);
- final Constructor> cstr = clazz.getConstructor(Context.class);
- return (ScriptObject) cstr.newInstance(this);
- } catch (final Exception e) {
- printStackTrace(e);
- if (e instanceof RuntimeException) {
- throw (RuntimeException)e;
- }
- throw new RuntimeException(e);
- }
+ return new Global(this);
}
}
diff --git a/nashorn/src/jdk/nashorn/internal/runtime/GlobalFunctions.java b/nashorn/src/jdk/nashorn/internal/runtime/GlobalFunctions.java
index 04211fc6707..c504276f41c 100644
--- a/nashorn/src/jdk/nashorn/internal/runtime/GlobalFunctions.java
+++ b/nashorn/src/jdk/nashorn/internal/runtime/GlobalFunctions.java
@@ -34,9 +34,6 @@ import java.util.Locale;
/**
* Utilities used by Global class.
- *
- * These are actual implementation methods for functions exposed by global
- * scope. The code lives here to share the code across the contexts.
*/
public final class GlobalFunctions {
diff --git a/nashorn/src/jdk/nashorn/internal/runtime/GlobalObject.java b/nashorn/src/jdk/nashorn/internal/runtime/GlobalObject.java
index b802a1a136f..7a118290c71 100644
--- a/nashorn/src/jdk/nashorn/internal/runtime/GlobalObject.java
+++ b/nashorn/src/jdk/nashorn/internal/runtime/GlobalObject.java
@@ -30,14 +30,7 @@ import jdk.internal.dynalink.linker.GuardedInvocation;
import jdk.internal.dynalink.linker.LinkRequest;
/**
- * Runtime interface to the global scope of the current context.
- * NOTE: never access {@code jdk.nashorn.internal.objects.Global} class directly
- * from runtime/parser/codegen/ir etc. Always go through this interface.
- *
- * The reason for this is that all objects in the @{code jdk.nashorn.internal.objects.*} package
- * are different per Context and loaded separately by each Context class loader. Attempting
- * to directly refer to an object in this package from the rest of the runtime
- * will lead to {@code ClassNotFoundException} thrown upon link time
+ * Runtime interface to the global scope objects.
*/
public interface GlobalObject {
diff --git a/nashorn/src/jdk/nashorn/internal/runtime/JSType.java b/nashorn/src/jdk/nashorn/internal/runtime/JSType.java
index 9507f0d3205..4d1d825c852 100644
--- a/nashorn/src/jdk/nashorn/internal/runtime/JSType.java
+++ b/nashorn/src/jdk/nashorn/internal/runtime/JSType.java
@@ -29,7 +29,9 @@ import static jdk.nashorn.internal.codegen.CompilerConstants.staticCall;
import static jdk.nashorn.internal.runtime.ECMAErrors.typeError;
import java.util.Locale;
+import jdk.internal.dynalink.beans.BeansLinker;
import jdk.internal.dynalink.beans.StaticClass;
+import jdk.nashorn.api.scripting.ScriptObjectMirror;
import jdk.nashorn.internal.codegen.CompilerConstants.Call;
import jdk.nashorn.internal.parser.Lexer;
@@ -151,6 +153,14 @@ public enum JSType {
return JSType.FUNCTION;
}
+ if (BeansLinker.isDynamicMethod(obj)) {
+ return JSType.FUNCTION;
+ }
+
+ if (obj instanceof ScriptObjectMirror) {
+ return ((ScriptObjectMirror)obj).isFunction()? JSType.FUNCTION : JSType.OBJECT;
+ }
+
return JSType.OBJECT;
}
diff --git a/nashorn/src/jdk/nashorn/internal/runtime/ListAdapter.java b/nashorn/src/jdk/nashorn/internal/runtime/ListAdapter.java
index 428cb555fb0..194bd132000 100644
--- a/nashorn/src/jdk/nashorn/internal/runtime/ListAdapter.java
+++ b/nashorn/src/jdk/nashorn/internal/runtime/ListAdapter.java
@@ -1,3 +1,28 @@
+/*
+ * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
package jdk.nashorn.internal.runtime;
import java.util.AbstractList;
diff --git a/nashorn/src/jdk/nashorn/internal/runtime/PropertyListenerManager.java b/nashorn/src/jdk/nashorn/internal/runtime/PropertyListenerManager.java
index 34db0cb3877..1ce18b63d8f 100644
--- a/nashorn/src/jdk/nashorn/internal/runtime/PropertyListenerManager.java
+++ b/nashorn/src/jdk/nashorn/internal/runtime/PropertyListenerManager.java
@@ -41,6 +41,7 @@ public class PropertyListenerManager implements PropertyListener {
private static int listenersRemoved;
/**
+ * Return aggregate listeners added to all PropertyListenerManagers
* @return the listenersAdded
*/
public static int getListenersAdded() {
@@ -48,12 +49,21 @@ public class PropertyListenerManager implements PropertyListener {
}
/**
+ * Return aggregate listeners removed from all PropertyListenerManagers
* @return the listenersRemoved
*/
public static int getListenersRemoved() {
return listenersRemoved;
}
+ /**
+ * Return listeners added to this PropertyListenerManager.
+ * @return the listener count
+ */
+ public final int getListenerCount() {
+ return listeners != null? listeners.size() : 0;
+ }
+
// Property listener management methods
/**
diff --git a/nashorn/src/jdk/nashorn/internal/runtime/PropertyMap.java b/nashorn/src/jdk/nashorn/internal/runtime/PropertyMap.java
index e03a3ef836e..05e8dc78235 100644
--- a/nashorn/src/jdk/nashorn/internal/runtime/PropertyMap.java
+++ b/nashorn/src/jdk/nashorn/internal/runtime/PropertyMap.java
@@ -25,11 +25,8 @@
package jdk.nashorn.internal.runtime;
-import jdk.nashorn.internal.scripts.JO;
-
import static jdk.nashorn.internal.runtime.PropertyHashMap.EMPTY_HASHMAP;
-import java.lang.invoke.MethodHandle;
import java.lang.invoke.SwitchPoint;
import java.lang.ref.WeakReference;
import java.util.Arrays;
@@ -57,9 +54,8 @@ public final class PropertyMap implements Iterable, PropertyListener {
private static final int CLONEABLE_FLAGS_MASK = 0b0000_1111;
/** Has a listener been added to this property map. This flag is not copied when cloning a map. See {@link PropertyListener} */
public static final int IS_LISTENER_ADDED = 0b0001_0000;
-
- /** Empty map used for seed map for JO$ objects */
- private static final PropertyMap EMPTY_MAP = new PropertyMap(EMPTY_HASHMAP);
+ /** Is this process wide "shared" map?. This flag is not copied when cloning a map */
+ public static final int IS_SHARED = 0b0010_0000;
/** Map status flags. */
private int flags;
@@ -91,14 +87,16 @@ public final class PropertyMap implements Iterable, PropertyListener {
/**
* Constructor.
*
- * @param properties A {@link PropertyHashMap} with initial contents.
- * @param fieldCount Number of fields in use.
+ * @param properties A {@link PropertyHashMap} with initial contents.
+ * @param fieldCount Number of fields in use.
* @param fieldMaximum Number of fields available.
+ * @param spillLength Number of spill slots used.
*/
- private PropertyMap(final PropertyHashMap properties, final int fieldCount, final int fieldMaximum) {
+ private PropertyMap(final PropertyHashMap properties, final int fieldCount, final int fieldMaximum, final int spillLength) {
this.properties = properties;
this.fieldCount = fieldCount;
this.fieldMaximum = fieldMaximum;
+ this.spillLength = spillLength;
if (Context.DEBUG) {
count++;
@@ -111,7 +109,7 @@ public final class PropertyMap implements Iterable, PropertyListener {
* @param properties A {@link PropertyHashMap} with initial contents.
*/
private PropertyMap(final PropertyHashMap properties) {
- this(properties, 0, 0);
+ this(properties, 0, 0, 0);
}
/**
@@ -143,58 +141,49 @@ public final class PropertyMap implements Iterable, PropertyListener {
}
/**
- * Duplicates this PropertyMap instance. This is used by nasgen generated
- * prototype and constructor classes. {@link PropertyMap} used for singletons
- * like these (and global instance) are duplicated using this method and used.
- * The original filled map referenced by static fields of prototype and
- * constructor classes are not touched. This allows multiple independent global
- * instances to be used within a single context instance.
+ * Duplicates this PropertyMap instance. This is used to duplicate 'shared'
+ * maps {@link PropertyMap} used as process wide singletons. Shared maps are
+ * duplicated for every global scope object. That way listeners, proto and property
+ * histories are scoped within a global scope.
*
* @return Duplicated {@link PropertyMap}.
*/
public PropertyMap duplicate() {
+ if (Context.DEBUG) {
+ duplicatedCount++;
+ }
return new PropertyMap(this.properties);
}
/**
* Public property map allocator.
*
- * @param structure Class the map's {@link AccessorProperty}s apply to.
- * @param properties Collection of initial properties.
- * @param fieldCount Number of fields in use.
+ * @param properties Collection of initial properties.
+ * @param fieldCount Number of fields in use.
* @param fieldMaximum Number of fields available.
- *
+ * @param spillLength Number of used spill slots.
* @return New {@link PropertyMap}.
*/
- public static PropertyMap newMap(final Class> structure, final Collection properties, final int fieldCount, final int fieldMaximum) {
- // Reduce the number of empty maps in the context.
- if (structure == JO.class) {
- return EMPTY_MAP;
- }
-
+ public static PropertyMap newMap(final Collection properties, final int fieldCount, final int fieldMaximum, final int spillLength) {
PropertyHashMap newProperties = EMPTY_HASHMAP.immutableAdd(properties);
-
- return new PropertyMap(newProperties, fieldCount, fieldMaximum);
+ return new PropertyMap(newProperties, fieldCount, fieldMaximum, spillLength);
}
/**
- * Public property map factory allocator
- *
- * @param structure Class the map's {@link AccessorProperty}s apply to.
- *
+ * Public property map allocator. Used by nasgen generated code.
+ * @param properties Collection of initial properties.
* @return New {@link PropertyMap}.
*/
- public static PropertyMap newMap(final Class> structure) {
- return newMap(structure, null, 0, 0);
+ public static PropertyMap newMap(final Collection properties) {
+ return (properties == null || properties.isEmpty())? newMap() : newMap(properties, 0, 0, 0);
}
/**
* Return a sharable empty map.
*
- * @param context the context
* @return New empty {@link PropertyMap}.
*/
- public static PropertyMap newEmptyMap(final Context context) {
+ public static PropertyMap newMap() {
return new PropertyMap(EMPTY_HASHMAP);
}
@@ -216,6 +205,8 @@ public final class PropertyMap implements Iterable, PropertyListener {
* @return A shared {@link SwitchPoint} for the property.
*/
public SwitchPoint getProtoGetSwitchPoint(final ScriptObject proto, final String key) {
+ assert !isShared() : "proto SwitchPoint from a shared PropertyMap";
+
if (proto == null) {
return null;
}
@@ -244,6 +235,8 @@ public final class PropertyMap implements Iterable, PropertyListener {
* @param property {@link Property} to invalidate.
*/
private void invalidateProtoGetSwitchPoint(final Property property) {
+ assert !isShared() : "proto invalidation on a shared PropertyMap";
+
if (protoGetSwitches != null) {
final String key = property.getKey();
final SwitchPoint sp = protoGetSwitches.get(key);
@@ -257,17 +250,6 @@ public final class PropertyMap implements Iterable, PropertyListener {
}
}
- /**
- * Add a property to the map.
- *
- * @param property {@link Property} being added.
- *
- * @return New {@link PropertyMap} with {@link Property} added.
- */
- public PropertyMap newProperty(final Property property) {
- return addProperty(property);
- }
-
/**
* Add a property to the map, re-binding its getters and setters,
* if available, to a given receiver. This is typically the global scope. See
@@ -278,23 +260,8 @@ public final class PropertyMap implements Iterable, PropertyListener {
*
* @return New {@link PropertyMap} with {@link Property} added.
*/
- PropertyMap newPropertyBind(final AccessorProperty property, final ScriptObject bindTo) {
- return newProperty(new AccessorProperty(property, bindTo));
- }
-
- /**
- * Add a new accessor property to the map.
- *
- * @param key {@link Property} key.
- * @param propertyFlags {@link Property} flags.
- * @param slot {@link Property} slot.
- * @param getter {@link Property} get accessor method.
- * @param setter {@link Property} set accessor method.
- *
- * @return New {@link PropertyMap} with {@link AccessorProperty} added.
- */
- public PropertyMap newProperty(final String key, final int propertyFlags, final int slot, final MethodHandle getter, final MethodHandle setter) {
- return newProperty(new AccessorProperty(key, propertyFlags, slot, getter, setter));
+ PropertyMap addPropertyBind(final AccessorProperty property, final ScriptObject bindTo) {
+ return addProperty(new AccessorProperty(property, bindTo));
}
/**
@@ -495,6 +462,28 @@ public final class PropertyMap implements Iterable, PropertyListener {
return newMap;
}
+ /**
+ * Make this property map 'shared' one. Shared property map instances are
+ * process wide singleton objects. A shaped map should never be added as a listener
+ * to a proto object. Nor it should have history or proto history. A shared map
+ * is just a template that is meant to be duplicated before use. All nasgen initialized
+ * property maps are shared.
+ *
+ * @return this map after making it as shared
+ */
+ public PropertyMap setIsShared() {
+ assert !isListenerAdded() : "making PropertyMap shared after listener added";
+ assert protoHistory == null : "making PropertyMap shared after associating a proto with it";
+ if (Context.DEBUG) {
+ sharedCount++;
+ }
+
+ flags |= IS_SHARED;
+ // clear any history on this PropertyMap, won't be used.
+ history = null;
+ return this;
+ }
+
/**
* Check for any configurable properties.
*
@@ -561,6 +550,8 @@ public final class PropertyMap implements Iterable, PropertyListener {
* @param newMap {@link PropertyMap} associated with prototype.
*/
private void addToProtoHistory(final ScriptObject newProto, final PropertyMap newMap) {
+ assert !isShared() : "proto history modified on a shared PropertyMap";
+
if (protoHistory == null) {
protoHistory = new WeakHashMap<>();
}
@@ -575,6 +566,8 @@ public final class PropertyMap implements Iterable, PropertyListener {
* @param newMap Modified {@link PropertyMap}.
*/
private void addToHistory(final Property property, final PropertyMap newMap) {
+ assert !isShared() : "history modified on a shared PropertyMap";
+
if (!properties.isEmpty()) {
if (history == null) {
history = new LinkedHashMap<>();
@@ -699,6 +692,15 @@ public final class PropertyMap implements Iterable, PropertyListener {
return (flags & IS_LISTENER_ADDED) != 0;
}
+ /**
+ * Check if this map shared or not.
+ *
+ * @return true if this map is shared.
+ */
+ public boolean isShared() {
+ return (flags & IS_SHARED) != 0;
+ }
+
/**
* Test to see if {@link PropertyMap} is extensible.
*
@@ -762,6 +764,8 @@ public final class PropertyMap implements Iterable, PropertyListener {
* @return New {@link PropertyMap} with prototype changed.
*/
PropertyMap changeProto(final ScriptObject oldProto, final ScriptObject newProto) {
+ assert !isShared() : "proto associated with a shared PropertyMap";
+
if (oldProto == newProto) {
return this;
}
@@ -877,6 +881,8 @@ public final class PropertyMap implements Iterable, PropertyListener {
// counters updated only in debug mode
private static int count;
private static int clonedCount;
+ private static int sharedCount;
+ private static int duplicatedCount;
private static int historyHit;
private static int protoInvalidations;
private static int protoHistoryHit;
@@ -896,6 +902,20 @@ public final class PropertyMap implements Iterable, PropertyListener {
return clonedCount;
}
+ /**
+ * @return The number of maps that are shared.
+ */
+ public static int getSharedCount() {
+ return sharedCount;
+ }
+
+ /**
+ * @return The number of maps that are duplicated.
+ */
+ public static int getDuplicatedCount() {
+ return duplicatedCount;
+ }
+
/**
* @return The number of times history was successfully used.
*/
diff --git a/nashorn/src/jdk/nashorn/internal/runtime/ScriptEnvironment.java b/nashorn/src/jdk/nashorn/internal/runtime/ScriptEnvironment.java
index f04dedf05c9..a2f1f4a0880 100644
--- a/nashorn/src/jdk/nashorn/internal/runtime/ScriptEnvironment.java
+++ b/nashorn/src/jdk/nashorn/internal/runtime/ScriptEnvironment.java
@@ -119,9 +119,15 @@ public final class ScriptEnvironment {
/** Create a new class loaded for each compilation */
public final boolean _loader_per_compile;
+ /** Do not support Java support extensions. */
+ public final boolean _no_java;
+
/** Do not support non-standard syntax extensions. */
public final boolean _no_syntax_extensions;
+ /** Do not support typed arrays. */
+ public final boolean _no_typed_arrays;
+
/** Package to which generated class files are added */
public final String _package;
@@ -207,7 +213,9 @@ public final class ScriptEnvironment {
_fx = options.getBoolean("fx");
_lazy_compilation = options.getBoolean("lazy.compilation");
_loader_per_compile = options.getBoolean("loader.per.compile");
+ _no_java = options.getBoolean("no.java");
_no_syntax_extensions = options.getBoolean("no.syntax.extensions");
+ _no_typed_arrays = options.getBoolean("no.typed.arrays");
_package = options.getString("package");
_parse_only = options.getBoolean("parse.only");
_print_ast = options.getBoolean("print.ast");
diff --git a/nashorn/src/jdk/nashorn/internal/runtime/ScriptObject.java b/nashorn/src/jdk/nashorn/internal/runtime/ScriptObject.java
index 1a081a1b2d5..c56c32c7257 100644
--- a/nashorn/src/jdk/nashorn/internal/runtime/ScriptObject.java
+++ b/nashorn/src/jdk/nashorn/internal/runtime/ScriptObject.java
@@ -170,7 +170,7 @@ public abstract class ScriptObject extends PropertyListenerManager implements Pr
}
this.arrayData = ArrayData.EMPTY_ARRAY;
- this.setMap(map == null ? PropertyMap.newMap(getClass()) : map);
+ this.setMap(map == null ? PropertyMap.newMap() : map);
}
/**
@@ -188,7 +188,7 @@ public abstract class ScriptObject extends PropertyListenerManager implements Pr
}
this.arrayData = ArrayData.EMPTY_ARRAY;
- this.setMap(map == null ? PropertyMap.newMap(getClass()) : map);
+ this.setMap(map == null ? PropertyMap.newMap() : map);
this.proto = proto;
if (proto != null) {
@@ -213,7 +213,7 @@ public abstract class ScriptObject extends PropertyListenerManager implements Pr
final UserAccessorProperty prop = this.newUserAccessors(key, property.getFlags(), property.getGetterFunction(source), property.getSetterFunction(source));
newMap = newMap.addProperty(prop);
} else {
- newMap = newMap.newPropertyBind((AccessorProperty)property, source);
+ newMap = newMap.addPropertyBind((AccessorProperty)property, source);
}
}
}
@@ -1026,6 +1026,15 @@ public abstract class ScriptObject extends PropertyListenerManager implements Pr
return context;
}
+ /**
+ * Set the current context.
+ * @param ctx context instance to set
+ */
+ protected final void setContext(final Context ctx) {
+ ctx.getClass();
+ this.context = ctx;
+ }
+
/**
* Return the map of an object.
* @return PropertyMap object.
diff --git a/nashorn/src/jdk/nashorn/internal/runtime/ScriptRuntime.java b/nashorn/src/jdk/nashorn/internal/runtime/ScriptRuntime.java
index 15c915cf0e4..f0b68c52ddf 100644
--- a/nashorn/src/jdk/nashorn/internal/runtime/ScriptRuntime.java
+++ b/nashorn/src/jdk/nashorn/internal/runtime/ScriptRuntime.java
@@ -592,6 +592,8 @@ public final class ScriptRuntime {
throw typeError("cant.get.property", safeToString(property), "null");
} else if (JSType.isPrimitive(obj)) {
obj = ((ScriptObject)JSType.toScriptObject(obj)).get(property);
+ } else if (obj instanceof ScriptObjectMirror) {
+ obj = ((ScriptObjectMirror)obj).getMember(property.toString());
} else {
obj = UNDEFINED;
}
@@ -600,23 +602,6 @@ public final class ScriptRuntime {
return JSType.of(obj).typeName();
}
- /**
- * ECMA 11.4.2 - void operator
- *
- * @param object object to evaluate
- *
- * @return Undefined as the object type
- */
- public static Object VOID(final Object object) {
- if (object instanceof Number) {
- if (Double.isNaN(((Number)object).doubleValue())) {
- return Double.NaN;
- }
- }
-
- return UNDEFINED;
- }
-
/**
* Throw ReferenceError when LHS of assignment or increment/decrement
* operator is not an assignable node (say a literal)
diff --git a/nashorn/src/jdk/nashorn/internal/runtime/StructureLoader.java b/nashorn/src/jdk/nashorn/internal/runtime/StructureLoader.java
index ff6973a9fc1..bdc40eddcc9 100644
--- a/nashorn/src/jdk/nashorn/internal/runtime/StructureLoader.java
+++ b/nashorn/src/jdk/nashorn/internal/runtime/StructureLoader.java
@@ -25,30 +25,19 @@
package jdk.nashorn.internal.runtime;
-import static jdk.nashorn.internal.codegen.Compiler.OBJECTS_PACKAGE;
import static jdk.nashorn.internal.codegen.Compiler.SCRIPTS_PACKAGE;
import static jdk.nashorn.internal.codegen.Compiler.binaryName;
import static jdk.nashorn.internal.codegen.CompilerConstants.JS_OBJECT_PREFIX;
-import java.io.IOException;
-import java.io.InputStream;
-import java.net.URL;
-import java.security.AccessController;
-import java.security.CodeSigner;
-import java.security.CodeSource;
-import java.security.PrivilegedActionException;
-import java.security.PrivilegedExceptionAction;
import java.security.ProtectionDomain;
import jdk.nashorn.internal.codegen.ObjectClassGenerator;
/**
- * Responsible for on the fly construction of structure classes as well
- * as loading jdk.nashorn.internal.objects.* classes.
+ * Responsible for on the fly construction of structure classes.
*
*/
final class StructureLoader extends NashornLoader {
private static final String JS_OBJECT_PREFIX_EXTERNAL = binaryName(SCRIPTS_PACKAGE) + '.' + JS_OBJECT_PREFIX.symbolName();
- private static final String OBJECTS_PACKAGE_EXTERNAL = binaryName(OBJECTS_PACKAGE);
/**
* Constructor.
@@ -68,45 +57,9 @@ final class StructureLoader extends NashornLoader {
return loadedClass;
}
- if (name.startsWith(binaryName(OBJECTS_PACKAGE_EXTERNAL))) {
- try {
- return AccessController.doPrivileged(new PrivilegedExceptionAction>() {
- @Override
- public Class> run() throws ClassNotFoundException {
- final String source = name.replace('.','/') + ".clazz";
- final URL url = getResource(source);
- try (final InputStream is = getResourceAsStream(source)) {
- if (is == null) {
- throw new ClassNotFoundException(name);
- }
-
- byte[] code;
- try {
- code = Source.readBytes(is);
- } catch (final IOException e) {
- Context.printStackTrace(e);
- throw new ClassNotFoundException(name, e);
- }
-
- final Class> cl = defineClass(name, code, 0, code.length, new CodeSource(url, (CodeSigner[])null));
- if (resolve) {
- resolveClass(cl);
- }
- return cl;
- } catch (final IOException e) {
- throw new RuntimeException(e);
- }
- }
- });
- } catch (final PrivilegedActionException e) {
- throw new ClassNotFoundException(name, e);
- }
- }
-
return super.loadClassTrusted(name, resolve);
}
-
@Override
protected Class> findClass(final String name) throws ClassNotFoundException {
if (name.startsWith(JS_OBJECT_PREFIX_EXTERNAL)) {
diff --git a/nashorn/src/jdk/nashorn/internal/runtime/arrays/ObjectArrayData.java b/nashorn/src/jdk/nashorn/internal/runtime/arrays/ObjectArrayData.java
index 4b1f58a430a..41c4d5ced30 100644
--- a/nashorn/src/jdk/nashorn/internal/runtime/arrays/ObjectArrayData.java
+++ b/nashorn/src/jdk/nashorn/internal/runtime/arrays/ObjectArrayData.java
@@ -146,7 +146,7 @@ final class ObjectArrayData extends ArrayData {
@Override
public ArrayData setEmpty(final long lo, final long hi) {
- Arrays.fill(array, (int)Math.max(lo, 0L), (int)Math.min(hi, (long)Integer.MAX_VALUE), ScriptRuntime.EMPTY);
+ Arrays.fill(array, (int)Math.max(lo, 0L), (int)Math.min(hi, Integer.MAX_VALUE), ScriptRuntime.EMPTY);
return this;
}
diff --git a/nashorn/src/jdk/nashorn/internal/runtime/linker/Bootstrap.java b/nashorn/src/jdk/nashorn/internal/runtime/linker/Bootstrap.java
index 6b55656ba17..3f3c2a5b8b3 100644
--- a/nashorn/src/jdk/nashorn/internal/runtime/linker/Bootstrap.java
+++ b/nashorn/src/jdk/nashorn/internal/runtime/linker/Bootstrap.java
@@ -78,7 +78,7 @@ public final class Bootstrap {
* @return CallSite with MethodHandle to appropriate method or null if not found.
*/
public static CallSite bootstrap(final Lookup lookup, final String opDesc, final MethodType type, final int flags) {
- return dynamicLinker.link(LinkerCallSite.newLinkerCallSite(opDesc, type, flags));
+ return dynamicLinker.link(LinkerCallSite.newLinkerCallSite(lookup, opDesc, type, flags));
}
/**
@@ -94,12 +94,12 @@ public final class Bootstrap {
return new RuntimeCallSite(type, initialName);
}
-
/**
- * Returns a dynamic invoker for a specified dynamic operation. You can use this method to create a method handle
- * that when invoked acts completely as if it were a Nashorn-linked call site. An overview of available dynamic
- * operations can be found in the Dynalink User Guide,
- * but we'll show few examples here:
+ * Returns a dynamic invoker for a specified dynamic operation using the public lookup. You can use this method to
+ * create a method handle that when invoked acts completely as if it were a Nashorn-linked call site. An overview of
+ * available dynamic operations can be found in the
+ * Dynalink User Guide, but we'll show few
+ * examples here:
*