# HG changeset patch
# User lana
# Date 1374540026 25200
# Node ID 12baff1ad7a08b5fc56934689dea622aeff306a1
# Parent d0545441225ecc50e34de62d1f7dfa49e7184fad# Parent 42107475be8da6dc816331490864495d1d61d896
Merge
diff -r d0545441225e -r 12baff1ad7a0 nashorn/buildtools/nasgen/build.xml
--- a/nashorn/buildtools/nasgen/build.xml Thu Jul 18 03:39:39 2013 -0700
+++ b/nashorn/buildtools/nasgen/build.xml Mon Jul 22 17:40:26 2013 -0700
@@ -42,7 +42,8 @@
destdir="${build.classes.dir}"
classpath="${javac.classpath}"
debug="${javac.debug}"
- includeantruntime="false">
+ includeantruntime="false" fork="true">
+
diff -r d0545441225e -r 12baff1ad7a0 nashorn/buildtools/nasgen/src/jdk/nashorn/internal/tools/nasgen/ClassGenerator.java
--- a/nashorn/buildtools/nasgen/src/jdk/nashorn/internal/tools/nasgen/ClassGenerator.java Thu Jul 18 03:39:39 2013 -0700
+++ b/nashorn/buildtools/nasgen/src/jdk/nashorn/internal/tools/nasgen/ClassGenerator.java Mon Jul 22 17:40:26 2013 -0700
@@ -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.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 @@
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 @@
}
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 @@
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 @@
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 @@
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 -r d0545441225e -r 12baff1ad7a0 nashorn/buildtools/nasgen/src/jdk/nashorn/internal/tools/nasgen/ConstructorGenerator.java
--- a/nashorn/buildtools/nasgen/src/jdk/nashorn/internal/tools/nasgen/ConstructorGenerator.java Thu Jul 18 03:39:39 2013 -0700
+++ b/nashorn/buildtools/nasgen/src/jdk/nashorn/internal/tools/nasgen/ConstructorGenerator.java Mon Jul 22 17:40:26 2013 -0700
@@ -32,11 +32,11 @@
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 @@
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 @@
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 -r d0545441225e -r 12baff1ad7a0 nashorn/buildtools/nasgen/src/jdk/nashorn/internal/tools/nasgen/MethodGenerator.java
--- a/nashorn/buildtools/nasgen/src/jdk/nashorn/internal/tools/nasgen/MethodGenerator.java Thu Jul 18 03:39:39 2013 -0700
+++ b/nashorn/buildtools/nasgen/src/jdk/nashorn/internal/tools/nasgen/MethodGenerator.java Mon Jul 22 17:40:26 2013 -0700
@@ -57,6 +57,7 @@
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 @@
}
// 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 -r d0545441225e -r 12baff1ad7a0 nashorn/buildtools/nasgen/src/jdk/nashorn/internal/tools/nasgen/PrototypeGenerator.java
--- a/nashorn/buildtools/nasgen/src/jdk/nashorn/internal/tools/nasgen/PrototypeGenerator.java Thu Jul 18 03:39:39 2013 -0700
+++ b/nashorn/buildtools/nasgen/src/jdk/nashorn/internal/tools/nasgen/PrototypeGenerator.java Mon Jul 22 17:40:26 2013 -0700
@@ -30,11 +30,11 @@
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 @@
// add
emitStaticInitializer();
}
+
// add
emitConstructor();
@@ -106,7 +107,7 @@
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 @@
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 -r d0545441225e -r 12baff1ad7a0 nashorn/buildtools/nasgen/src/jdk/nashorn/internal/tools/nasgen/ScriptClassInstrumentor.java
--- a/nashorn/buildtools/nasgen/src/jdk/nashorn/internal/tools/nasgen/ScriptClassInstrumentor.java Thu Jul 18 03:39:39 2013 -0700
+++ b/nashorn/buildtools/nasgen/src/jdk/nashorn/internal/tools/nasgen/ScriptClassInstrumentor.java Mon Jul 22 17:40:26 2013 -0700
@@ -37,10 +37,7 @@
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 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 @@
}
// 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 -r d0545441225e -r 12baff1ad7a0 nashorn/buildtools/nasgen/src/jdk/nashorn/internal/tools/nasgen/StringConstants.java
--- a/nashorn/buildtools/nasgen/src/jdk/nashorn/internal/tools/nasgen/StringConstants.java Thu Jul 18 03:39:39 2013 -0700
+++ b/nashorn/buildtools/nasgen/src/jdk/nashorn/internal/tools/nasgen/StringConstants.java Mon Jul 22 17:40:26 2013 -0700
@@ -27,10 +27,14 @@
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 @@
*/
@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 @@
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 -r d0545441225e -r 12baff1ad7a0 nashorn/docs/JavaScriptingProgrammersGuide.html
--- a/nashorn/docs/JavaScriptingProgrammersGuide.html Thu Jul 18 03:39:39 2013 -0700
+++ b/nashorn/docs/JavaScriptingProgrammersGuide.html Mon Jul 22 17:40:26 2013 -0700
@@ -501,14 +501,19 @@
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 -r d0545441225e -r 12baff1ad7a0 nashorn/make/build-nasgen.xml
--- a/nashorn/make/build-nasgen.xml Thu Jul 18 03:39:39 2013 -0700
+++ b/nashorn/make/build-nasgen.xml Mon Jul 22 17:40:26 2013 -0700
@@ -42,11 +42,6 @@
-
-
-
-
-
@@ -66,7 +61,6 @@
-
@@ -75,7 +69,6 @@
-
diff -r d0545441225e -r 12baff1ad7a0 nashorn/make/build.xml
--- a/nashorn/make/build.xml Thu Jul 18 03:39:39 2013 -0700
+++ b/nashorn/make/build.xml Mon Jul 22 17:40:26 2013 -0700
@@ -100,7 +100,8 @@
target="${javac.target}"
debug="${javac.debug}"
encoding="${javac.encoding}"
- includeantruntime="false">
+ includeantruntime="false" fork="true">
+
@@ -218,8 +219,10 @@
target="${javac.target}"
debug="${javac.debug}"
encoding="${javac.encoding}"
- includeantruntime="false">
-
+ includeantruntime="false" fork="true">
+
+
+
@@ -235,44 +238,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 -r d0545441225e -r 12baff1ad7a0 nashorn/make/code_coverage.xml
--- a/nashorn/make/code_coverage.xml Thu Jul 18 03:39:39 2013 -0700
+++ b/nashorn/make/code_coverage.xml Mon Jul 22 17:40:26 2013 -0700
@@ -60,16 +60,8 @@
-
-
-
-
-
-
-
-
diff -r d0545441225e -r 12baff1ad7a0 nashorn/make/project.properties
--- a/nashorn/make/project.properties Thu Jul 18 03:39:39 2013 -0700
+++ b/nashorn/make/project.properties Mon Jul 22 17:40:26 2013 -0700
@@ -200,6 +200,9 @@
# 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 -r d0545441225e -r 12baff1ad7a0 nashorn/makefiles/BuildNashorn.gmk
--- a/nashorn/makefiles/BuildNashorn.gmk Thu Jul 18 03:39:39 2013 -0700
+++ b/nashorn/makefiles/BuildNashorn.gmk Mon Jul 22 17:40:26 2013 -0700
@@ -71,7 +71,6 @@
$(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 @@
$(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 @@
$(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 -r d0545441225e -r 12baff1ad7a0 nashorn/src/jdk/internal/dynalink/DynamicLinker.java
--- a/nashorn/src/jdk/internal/dynalink/DynamicLinker.java Thu Jul 18 03:39:39 2013 -0700
+++ b/nashorn/src/jdk/internal/dynalink/DynamicLinker.java Mon Jul 22 17:40:26 2013 -0700
@@ -144,6 +144,9 @@
private static final String CLASS_NAME = DynamicLinker.class.getName();
private static final String RELINK_METHOD_NAME = "relink";
+ private static final String INITIAL_LINK_CLASS_NAME = "java.lang.invoke.MethodHandleNatives";
+ private static final String INITIAL_LINK_METHOD_NAME = "linkCallSite";
+
private final LinkerServices linkerServices;
private final int runtimeContextArgCount;
private final boolean syncOnRelink;
@@ -262,20 +265,54 @@
}
/**
- * Returns a stack trace element describing the location of the call site currently being relinked on the current
+ * Returns a stack trace element describing the location of the call site currently being linked on the current
* thread. The operation internally creates a Throwable object and inspects its stack trace, so it's potentially
* expensive. The recommended usage for it is in writing diagnostics code.
- * @return a stack trace element describing the location of the call site currently being relinked, or null if it is
- * not invoked while a call site is being relinked.
+ * @return a stack trace element describing the location of the call site currently being linked, or null if it is
+ * not invoked while a call site is being linked.
*/
- public static StackTraceElement getRelinkedCallSiteLocation() {
+ public static StackTraceElement getLinkedCallSiteLocation() {
final StackTraceElement[] trace = new Throwable().getStackTrace();
for(int i = 0; i < trace.length - 1; ++i) {
final StackTraceElement frame = trace[i];
- if(RELINK_METHOD_NAME.equals(frame.getMethodName()) && CLASS_NAME.equals(frame.getClassName())) {
+ if(isRelinkFrame(frame) || isInitialLinkFrame(frame)) {
return trace[i + 1];
}
}
return null;
}
+
+ /**
+ * Deprecated because of not precise name.
+ * @deprecated Use {@link #getLinkedCallSiteLocation()} instead.
+ * @return see non-deprecated method
+ */
+ @Deprecated
+ public static StackTraceElement getRelinkedCallSiteLocation() {
+ return getLinkedCallSiteLocation();
+ }
+
+ /**
+ * Returns true if the frame represents {@code MethodHandleNatives.linkCallSite()}, the frame immediately on top of
+ * the call site frame when the call site is being linked for the first time.
+ * @param frame the frame
+ * @return true if this frame represents {@code MethodHandleNatives.linkCallSite()}
+ */
+ private static boolean isInitialLinkFrame(final StackTraceElement frame) {
+ return testFrame(frame, INITIAL_LINK_METHOD_NAME, INITIAL_LINK_CLASS_NAME);
+ }
+
+ /**
+ * Returns true if the frame represents {@code DynamicLinker.relink()}, the frame immediately on top of the call
+ * site frame when the call site is being relinked (linked for second and subsequent times).
+ * @param frame the frame
+ * @return true if this frame represents {@code DynamicLinker.relink()}
+ */
+ private static boolean isRelinkFrame(final StackTraceElement frame) {
+ return testFrame(frame, RELINK_METHOD_NAME, CLASS_NAME);
+ }
+
+ private static boolean testFrame(final StackTraceElement frame, final String methodName, final String className) {
+ return methodName.equals(frame.getMethodName()) && className.equals(frame.getClassName());
+ }
}
diff -r d0545441225e -r 12baff1ad7a0 nashorn/src/jdk/internal/dynalink/beans/AbstractJavaLinker.java
--- a/nashorn/src/jdk/internal/dynalink/beans/AbstractJavaLinker.java Thu Jul 18 03:39:39 2013 -0700
+++ b/nashorn/src/jdk/internal/dynalink/beans/AbstractJavaLinker.java Mon Jul 22 17:40:26 2013 -0700
@@ -86,9 +86,14 @@
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.Collection;
+import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@@ -109,10 +114,11 @@
* @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 +135,19 @@
// 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 +159,8 @@
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 +196,135 @@
abstract FacetIntrospector createFacetIntrospector();
- void setPropertyGetter(String name, MethodHandle handle, ValidationType validationType) {
- propertyGetters.put(name, new AnnotatedMethodHandle(handle, validationType));
+ Collection getReadablePropertyNames() {
+ return getUnmodifiableKeys(propertyGetters);
+ }
+
+ Collection getWritablePropertyNames() {
+ return getUnmodifiableKeys(propertySetters);
+ }
+
+ Collection getMethodNames() {
+ return getUnmodifiableKeys(methods);
+ }
+
+ private static Collection getUnmodifiableKeys(Map m) {
+ return Collections.unmodifiableCollection(m.keySet());
+ }
+
+ /**
+ * 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 +397,7 @@
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 +406,16 @@
}
}
- 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 +423,13 @@
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 +478,8 @@
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 +516,8 @@
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 +535,13 @@
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 +554,20 @@
// 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 +575,19 @@
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 +597,13 @@
// 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 +611,7 @@
// 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 +727,15 @@
// 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 +794,24 @@
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 -r d0545441225e -r 12baff1ad7a0 nashorn/src/jdk/internal/dynalink/beans/ApplicableOverloadedMethods.java
--- a/nashorn/src/jdk/internal/dynalink/beans/ApplicableOverloadedMethods.java Thu Jul 18 03:39:39 2013 -0700
+++ b/nashorn/src/jdk/internal/dynalink/beans/ApplicableOverloadedMethods.java Mon Jul 22 17:40:26 2013 -0700
@@ -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 @@
* @author Attila Szegedi
*/
class ApplicableOverloadedMethods {
- private final List methods;
+ private final List methods;
private final boolean varArgs;
/**
@@ -106,10 +105,10 @@
* @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 @@
*
* @return list of all methods.
*/
- List getMethods() {
+ List getMethods() {
return methods;
}
@@ -131,12 +130,12 @@
*
* @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 @@
*/
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 @@
*/
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 @@
*/
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 -r d0545441225e -r 12baff1ad7a0 nashorn/src/jdk/internal/dynalink/beans/BeansLinker.java
--- a/nashorn/src/jdk/internal/dynalink/beans/BeansLinker.java Thu Jul 18 03:39:39 2013 -0700
+++ b/nashorn/src/jdk/internal/dynalink/beans/BeansLinker.java Mon Jul 22 17:40:26 2013 -0700
@@ -84,6 +84,8 @@
package jdk.internal.dynalink.beans;
import java.lang.invoke.MethodHandles;
+import java.util.Collection;
+import java.util.Collections;
import jdk.internal.dynalink.CallSiteDescriptor;
import jdk.internal.dynalink.DynamicLinkerFactory;
import jdk.internal.dynalink.linker.GuardedInvocation;
@@ -166,6 +168,72 @@
return obj instanceof DynamicMethod;
}
+ /**
+ * Returns a collection of names of all readable instance properties of a class.
+ * @param clazz the class
+ * @return a collection of names of all readable instance properties of a class.
+ */
+ public static Collection getReadableInstancePropertyNames(Class> clazz) {
+ TypeBasedGuardingDynamicLinker linker = getLinkerForClass(clazz);
+ if(linker instanceof BeanLinker) {
+ return ((BeanLinker)linker).getReadablePropertyNames();
+ }
+ return Collections.emptySet();
+ }
+
+ /**
+ * Returns a collection of names of all writable instance properties of a class.
+ * @param clazz the class
+ * @return a collection of names of all writable instance properties of a class.
+ */
+ public static Collection getWritableInstancePropertyNames(Class> clazz) {
+ TypeBasedGuardingDynamicLinker linker = getLinkerForClass(clazz);
+ if(linker instanceof BeanLinker) {
+ return ((BeanLinker)linker).getWritablePropertyNames();
+ }
+ return Collections.emptySet();
+ }
+
+ /**
+ * Returns a collection of names of all instance methods of a class.
+ * @param clazz the class
+ * @return a collection of names of all instance methods of a class.
+ */
+ public static Collection getInstanceMethodNames(Class> clazz) {
+ TypeBasedGuardingDynamicLinker linker = getLinkerForClass(clazz);
+ if(linker instanceof BeanLinker) {
+ return ((BeanLinker)linker).getMethodNames();
+ }
+ return Collections.emptySet();
+ }
+
+ /**
+ * Returns a collection of names of all readable static properties of a class.
+ * @param clazz the class
+ * @return a collection of names of all readable static properties of a class.
+ */
+ public static Collection getReadableStaticPropertyNames(Class> clazz) {
+ return StaticClassLinker.getReadableStaticPropertyNames(clazz);
+ }
+
+ /**
+ * Returns a collection of names of all writable static properties of a class.
+ * @param clazz the class
+ * @return a collection of names of all writable static properties of a class.
+ */
+ public static Collection getWritableStaticPropertyNames(Class> clazz) {
+ return StaticClassLinker.getWritableStaticPropertyNames(clazz);
+ }
+
+ /**
+ * Returns a collection of names of all static methods of a class.
+ * @param clazz the class
+ * @return a collection of names of all static methods of a class.
+ */
+ public static Collection getStaticMethodNames(Class> clazz) {
+ return StaticClassLinker.getStaticMethodNames(clazz);
+ }
+
@Override
public GuardedInvocation getGuardedInvocation(LinkRequest request, final LinkerServices linkerServices)
throws Exception {
diff -r d0545441225e -r 12baff1ad7a0 nashorn/src/jdk/internal/dynalink/beans/CallerSensitiveDetector.java
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/nashorn/src/jdk/internal/dynalink/beans/CallerSensitiveDetector.java Mon Jul 22 17:40:26 2013 -0700
@@ -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 -r d0545441225e -r 12baff1ad7a0 nashorn/src/jdk/internal/dynalink/beans/CallerSensitiveDynamicMethod.java
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/nashorn/src/jdk/internal/dynalink/beans/CallerSensitiveDynamicMethod.java Mon Jul 22 17:40:26 2013 -0700
@@ -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 -r d0545441225e -r 12baff1ad7a0 nashorn/src/jdk/internal/dynalink/beans/ClassString.java
--- a/nashorn/src/jdk/internal/dynalink/beans/ClassString.java Thu Jul 18 03:39:39 2013 -0700
+++ b/nashorn/src/jdk/internal/dynalink/beans/ClassString.java Mon Jul 22 17:40:26 2013 -0700
@@ -155,8 +155,8 @@
}
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 -r d0545441225e -r 12baff1ad7a0 nashorn/src/jdk/internal/dynalink/beans/DynamicMethod.java
--- a/nashorn/src/jdk/internal/dynalink/beans/DynamicMethod.java Thu Jul 18 03:39:39 2013 -0700
+++ b/nashorn/src/jdk/internal/dynalink/beans/DynamicMethod.java Mon Jul 22 17:40:26 2013 -0700
@@ -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 @@
* 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 -r d0545441225e -r 12baff1ad7a0 nashorn/src/jdk/internal/dynalink/beans/DynamicMethodLinker.java
--- a/nashorn/src/jdk/internal/dynalink/beans/DynamicMethodLinker.java Thu Jul 18 03:39:39 2013 -0700
+++ b/nashorn/src/jdk/internal/dynalink/beans/DynamicMethodLinker.java Mon Jul 22 17:40:26 2013 -0700
@@ -85,12 +85,12 @@
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 @@
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 -r d0545441225e -r 12baff1ad7a0 nashorn/src/jdk/internal/dynalink/beans/FacetIntrospector.java
--- a/nashorn/src/jdk/internal/dynalink/beans/FacetIntrospector.java Thu Jul 18 03:39:39 2013 -0700
+++ b/nashorn/src/jdk/internal/dynalink/beans/FacetIntrospector.java Mon Jul 22 17:40:26 2013 -0700
@@ -167,10 +167,6 @@
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 -r d0545441225e -r 12baff1ad7a0 nashorn/src/jdk/internal/dynalink/beans/MaximallySpecific.java
--- a/nashorn/src/jdk/internal/dynalink/beans/MaximallySpecific.java Thu Jul 18 03:39:39 2013 -0700
+++ b/nashorn/src/jdk/internal/dynalink/beans/MaximallySpecific.java Mon Jul 22 17:40:26 2013 -0700
@@ -105,10 +105,58 @@
* @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 @@
* @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 -r d0545441225e -r 12baff1ad7a0 nashorn/src/jdk/internal/dynalink/beans/OverloadedDynamicMethod.java
--- a/nashorn/src/jdk/internal/dynalink/beans/OverloadedDynamicMethod.java Thu Jul 18 03:39:39 2013 -0700
+++ b/nashorn/src/jdk/internal/dynalink/beans/OverloadedDynamicMethod.java Mon Jul 22 17:40:26 2013 -0700
@@ -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 @@
/**
* Holds a list of all methods.
*/
- private final LinkedList methods;
+ private final LinkedList methods;
private final ClassLoader classLoader;
/**
@@ -111,21 +116,22 @@
* @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 @@
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 @@
}
@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 @@
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 @@
// (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 @@
}
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();
@@ -301,20 +298,11 @@
}
/**
- * 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 -r d0545441225e -r 12baff1ad7a0 nashorn/src/jdk/internal/dynalink/beans/OverloadedMethod.java
--- a/nashorn/src/jdk/internal/dynalink/beans/OverloadedMethod.java Thu Jul 18 03:39:39 2013 -0700
+++ b/nashorn/src/jdk/internal/dynalink/beans/OverloadedMethod.java Mon Jul 22 17:40:26 2013 -0700
@@ -135,7 +135,7 @@
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 @@
break;
}
case 1: {
- method = new SimpleDynamicMethod(methods.get(0)).getInvocation(callSiteType, linkerServices);
+ method = SingleDynamicMethod.getInvocation(methods.get(0), callSiteType, linkerServices);
break;
}
default: {
diff -r d0545441225e -r 12baff1ad7a0 nashorn/src/jdk/internal/dynalink/beans/SimpleDynamicMethod.java
--- a/nashorn/src/jdk/internal/dynalink/beans/SimpleDynamicMethod.java Thu Jul 18 03:39:39 2013 -0700
+++ b/nashorn/src/jdk/internal/dynalink/beans/SimpleDynamicMethod.java Mon Jul 22 17:40:26 2013 -0700
@@ -84,29 +84,22 @@
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 @@
* @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));
- }
-
- 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);
- }
-
- /**
- * Returns the target of this dynamic method
- *
- * @return the target of this dynamic method
- */
- MethodHandle getTarget() {
- return target;
+ return getMethodNameWithSignature(target.type(), getClassAndMethodName(clazz, name));
}
@Override
- SimpleDynamicMethod getMethodForExactParamTypes(String paramTypes) {
- return typeMatchesDescription(paramTypes, target.type()) ? this : null;
+ boolean isVarArgs() {
+ return target.isVarargsCollector();
}
@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);
+ MethodType getMethodType() {
+ return target.type();
}
@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);
+ MethodHandle getTarget(Lookup lookup) {
+ return target;
}
}
diff -r d0545441225e -r 12baff1ad7a0 nashorn/src/jdk/internal/dynalink/beans/SingleDynamicMethod.java
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/nashorn/src/jdk/internal/dynalink/beans/SingleDynamicMethod.java Mon Jul 22 17:40:26 2013 -0700
@@ -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 -r d0545441225e -r 12baff1ad7a0 nashorn/src/jdk/internal/dynalink/beans/StaticClassIntrospector.java
--- a/nashorn/src/jdk/internal/dynalink/beans/StaticClassIntrospector.java Thu Jul 18 03:39:39 2013 -0700
+++ b/nashorn/src/jdk/internal/dynalink/beans/StaticClassIntrospector.java Mon Jul 22 17:40:26 2013 -0700
@@ -106,10 +106,18 @@
@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 -r d0545441225e -r 12baff1ad7a0 nashorn/src/jdk/internal/dynalink/beans/StaticClassLinker.java
--- a/nashorn/src/jdk/internal/dynalink/beans/StaticClassLinker.java Thu Jul 18 03:39:39 2013 -0700
+++ b/nashorn/src/jdk/internal/dynalink/beans/StaticClassLinker.java Mon Jul 22 17:40:26 2013 -0700
@@ -87,13 +87,11 @@
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 java.util.Collection;
import jdk.internal.dynalink.CallSiteDescriptor;
import jdk.internal.dynalink.beans.GuardedInvocationComponent.ValidationType;
import jdk.internal.dynalink.linker.GuardedInvocation;
-import jdk.internal.dynalink.linker.GuardingDynamicLinker;
import jdk.internal.dynalink.linker.LinkRequest;
import jdk.internal.dynalink.linker.LinkerServices;
import jdk.internal.dynalink.linker.TypeBasedGuardingDynamicLinker;
@@ -104,9 +102,9 @@
* @author Attila Szegedi
*/
class StaticClassLinker implements TypeBasedGuardingDynamicLinker {
- private final ClassValue linkers = new ClassValue() {
+ private static final ClassValue linkers = new ClassValue() {
@Override
- protected GuardingDynamicLinker computeValue(Class> clazz) {
+ protected SingleClassStaticsLinker computeValue(Class> clazz) {
return new SingleClassStaticsLinker(clazz);
}
};
@@ -131,20 +129,11 @@
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,17 +150,28 @@
}
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;
}
}
+ static Collection getReadableStaticPropertyNames(Class> clazz) {
+ return linkers.get(clazz).getReadablePropertyNames();
+ }
+
+ static Collection getWritableStaticPropertyNames(Class> clazz) {
+ return linkers.get(clazz).getWritablePropertyNames();
+ }
+
+ static Collection getStaticMethodNames(Class> clazz) {
+ return linkers.get(clazz).getMethodNames();
+ }
+
@Override
public GuardedInvocation getGuardedInvocation(LinkRequest request, LinkerServices linkerServices) throws Exception {
final Object receiver = request.getReceiver();
diff -r d0545441225e -r 12baff1ad7a0 nashorn/src/jdk/internal/dynalink/support/AbstractCallSiteDescriptor.java
--- a/nashorn/src/jdk/internal/dynalink/support/AbstractCallSiteDescriptor.java Thu Jul 18 03:39:39 2013 -0700
+++ b/nashorn/src/jdk/internal/dynalink/support/AbstractCallSiteDescriptor.java Mon Jul 22 17:40:26 2013 -0700
@@ -139,8 +139,9 @@
@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 -r d0545441225e -r 12baff1ad7a0 nashorn/src/jdk/internal/dynalink/support/Lookup.java
--- a/nashorn/src/jdk/internal/dynalink/support/Lookup.java Thu Jul 18 03:39:39 2013 -0700
+++ b/nashorn/src/jdk/internal/dynalink/support/Lookup.java Mon Jul 22 17:40:26 2013 -0700
@@ -122,6 +122,18 @@
* @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 @@
}
}
-
/**
* Performs a {@link java.lang.invoke.MethodHandles.Lookup#unreflectGetter(Field)}, converting any encountered
* {@link IllegalAccessException} into an {@link IllegalAccessError}.
@@ -202,6 +213,18 @@
* @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 -r d0545441225e -r 12baff1ad7a0 nashorn/src/jdk/nashorn/api/scripting/NashornException.java
--- a/nashorn/src/jdk/nashorn/api/scripting/NashornException.java Thu Jul 18 03:39:39 2013 -0700
+++ b/nashorn/src/jdk/nashorn/api/scripting/NashornException.java Mon Jul 22 17:40:26 2013 -0700
@@ -146,7 +146,7 @@
* @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 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 -r d0545441225e -r 12baff1ad7a0 nashorn/src/jdk/nashorn/api/scripting/NashornScriptEngine.java
--- a/nashorn/src/jdk/nashorn/api/scripting/NashornScriptEngine.java Thu Jul 18 03:39:39 2013 -0700
+++ b/nashorn/src/jdk/nashorn/api/scripting/NashornScriptEngine.java Mon Jul 22 17:40:26 2013 -0700
@@ -33,6 +33,7 @@
import java.io.InputStreamReader;
import java.io.Reader;
import java.lang.reflect.Method;
+import java.lang.reflect.Modifier;
import java.net.URL;
import java.nio.charset.Charset;
import java.security.AccessController;
@@ -184,6 +185,19 @@
}
private T getInterfaceInner(final Object self, final Class clazz) {
+ if (clazz == null || !clazz.isInterface()) {
+ throw new IllegalArgumentException("interface Class expected");
+ }
+
+ // perform security access check as early as possible
+ final SecurityManager sm = System.getSecurityManager();
+ if (sm != null) {
+ if (! Modifier.isPublic(clazz.getModifiers())) {
+ throw new SecurityException("attempt to implement non-public interfce: " + clazz);
+ }
+ Context.checkPackageAccess(clazz.getName());
+ }
+
final ScriptObject realSelf;
final ScriptObject ctxtGlobal = getNashornGlobalFrom(context);
if(self == null) {
@@ -193,6 +207,7 @@
} else {
realSelf = (ScriptObject)self;
}
+
try {
final ScriptObject oldGlobal = getNashornGlobal();
try {
diff -r d0545441225e -r 12baff1ad7a0 nashorn/src/jdk/nashorn/api/scripting/ScriptObjectMirror.java
--- a/nashorn/src/jdk/nashorn/api/scripting/ScriptObjectMirror.java Thu Jul 18 03:39:39 2013 -0700
+++ b/nashorn/src/jdk/nashorn/api/scripting/ScriptObjectMirror.java Mon Jul 22 17:40:26 2013 -0700
@@ -52,11 +52,6 @@
private final ScriptObject sobj;
private final ScriptObject global;
- ScriptObjectMirror(final ScriptObject sobj, final ScriptObject global) {
- this.sobj = sobj;
- this.global = global;
- }
-
@Override
public boolean equals(final Object other) {
if (other instanceof ScriptObjectMirror) {
@@ -81,25 +76,6 @@
});
}
- private V inGlobal(final Callable callable) {
- final ScriptObject oldGlobal = NashornScriptEngine.getNashornGlobal();
- final boolean globalChanged = (oldGlobal != global);
- if (globalChanged) {
- NashornScriptEngine.setNashornGlobal(global);
- }
- try {
- return callable.call();
- } catch (final RuntimeException e) {
- throw e;
- } catch (final Exception e) {
- throw new AssertionError("Cannot happen", e);
- } finally {
- if (globalChanged) {
- NashornScriptEngine.setNashornGlobal(oldGlobal);
- }
- }
- }
-
// JSObject methods
@Override
public Object call(final String functionName, final Object... args) {
@@ -212,6 +188,8 @@
});
}
+ // javax.script.Bindings methods
+
@Override
public void clear() {
inGlobal(new Callable