8174222: LambdaMetafactory: validate inputs and improve documentation

Reviewed-by: mchung
This commit is contained in:
Dan Smith 2021-06-07 23:21:24 +00:00
parent 5e557d8650
commit fc08af58cb
8 changed files with 800 additions and 436 deletions

View file

@ -1,5 +1,5 @@
/*
* Copyright (c) 2012, 2020, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2012, 2021, 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
@ -53,20 +53,20 @@ import static sun.invoke.util.Wrapper.isWrapperType;
*/
final MethodHandles.Lookup caller; // The caller's lookup context
final Class<?> targetClass; // The class calling the meta-factory via invokedynamic "class X"
final MethodType invokedType; // The type of the invoked method "(CC)II"
final Class<?> samBase; // The type of the returned instance "interface JJ"
final String samMethodName; // Name of the SAM method "foo"
final MethodType samMethodType; // Type of the SAM method "(Object)Object"
final MethodHandle implMethod; // Raw method handle for the implementation method
final MethodType implMethodType; // Type of the implMethod MethodHandle "(CC,int)String"
final MethodType factoryType; // The type of the invoked method "(CC)II"
final Class<?> interfaceClass; // The type of the returned instance "interface JJ"
final String interfaceMethodName; // Name of the method to implement "foo"
final MethodType interfaceMethodType; // Type of the method to implement "(Object)Object"
final MethodHandle implementation; // Raw method handle for the implementation method
final MethodType implMethodType; // Type of the implementation MethodHandle "(CC,int)String"
final MethodHandleInfo implInfo; // Info about the implementation method handle "MethodHandleInfo[5 CC.impl(int)String]"
final int implKind; // Invocation kind for implementation "5"=invokevirtual
final boolean implIsInstanceMethod; // Is the implementation an instance method "true"
final Class<?> implClass; // Class for referencing the implementation method "class CC"
final MethodType instantiatedMethodType; // Instantiated erased functional interface method type "(Integer)Object"
final MethodType dynamicMethodType; // Dynamically checked method type "(Integer)Object"
final boolean isSerializable; // Should the returned instance be serializable
final Class<?>[] markerInterfaces; // Additional marker interfaces to be implemented
final MethodType[] additionalBridges; // Signatures of additional methods to bridge
final Class<?>[] altInterfaces; // Additional interfaces to be implemented
final MethodType[] altMethods; // Signatures of additional methods to bridge
/**
@ -74,65 +74,72 @@ import static sun.invoke.util.Wrapper.isWrapperType;
*
* @param caller Stacked automatically by VM; represents a lookup context
* with the accessibility privileges of the caller.
* @param invokedType Stacked automatically by VM; the signature of the
* @param factoryType Stacked automatically by VM; the signature of the
* invoked method, which includes the expected static
* type of the returned lambda object, and the static
* types of the captured arguments for the lambda. In
* the event that the implementation method is an
* instance method, the first argument in the invocation
* signature will correspond to the receiver.
* @param samMethodName Name of the method in the functional interface to
* which the lambda or method reference is being
* converted, represented as a String.
* @param samMethodType Type of the method in the functional interface to
* which the lambda or method reference is being
* converted, represented as a MethodType.
* @param implMethod The implementation method which should be called
* (with suitable adaptation of argument types, return
* types, and adjustment for captured arguments) when
* methods of the resulting functional interface instance
* are invoked.
* @param instantiatedMethodType The signature of the primary functional
* interface method after type variables are
* substituted with their instantiation from
* the capture site
* @param interfaceMethodName Name of the method in the functional interface to
* which the lambda or method reference is being
* converted, represented as a String.
* @param interfaceMethodType Type of the method in the functional interface to
* which the lambda or method reference is being
* converted, represented as a MethodType.
* @param implementation The implementation method which should be called
* (with suitable adaptation of argument types, return
* types, and adjustment for captured arguments) when
* methods of the resulting functional interface instance
* are invoked.
* @param dynamicMethodType The signature of the primary functional
* interface method after type variables are
* substituted with their instantiation from
* the capture site
* @param isSerializable Should the lambda be made serializable? If set,
* either the target type or one of the additional SAM
* types must extend {@code Serializable}.
* @param markerInterfaces Additional interfaces which the lambda object
* should implement.
* @param additionalBridges Method types for additional signatures to be
* bridged to the implementation method
* @param altInterfaces Additional interfaces which the lambda object
* should implement.
* @param altMethods Method types for additional signatures to be
* implemented by invoking the implementation method
* @throws LambdaConversionException If any of the meta-factory protocol
* invariants are violated
* invariants are violated
* @throws SecurityException If a security manager is present, and it
* <a href="MethodHandles.Lookup.html#secmgr">denies access</a>
* from {@code caller} to the package of {@code implementation}.
*/
AbstractValidatingLambdaMetafactory(MethodHandles.Lookup caller,
MethodType invokedType,
String samMethodName,
MethodType samMethodType,
MethodHandle implMethod,
MethodType instantiatedMethodType,
boolean isSerializable,
Class<?>[] markerInterfaces,
MethodType[] additionalBridges)
MethodType factoryType,
String interfaceMethodName,
MethodType interfaceMethodType,
MethodHandle implementation,
MethodType dynamicMethodType,
boolean isSerializable,
Class<?>[] altInterfaces,
MethodType[] altMethods)
throws LambdaConversionException {
if ((caller.lookupModes() & MethodHandles.Lookup.PRIVATE) == 0) {
if (!caller.hasFullPrivilegeAccess()) {
throw new LambdaConversionException(String.format(
"Invalid caller: %s",
caller.lookupClass().getName()));
}
this.caller = caller;
this.targetClass = caller.lookupClass();
this.invokedType = invokedType;
this.factoryType = factoryType;
this.samBase = invokedType.returnType();
this.interfaceClass = factoryType.returnType();
this.samMethodName = samMethodName;
this.samMethodType = samMethodType;
this.interfaceMethodName = interfaceMethodName;
this.interfaceMethodType = interfaceMethodType;
this.implMethod = implMethod;
this.implMethodType = implMethod.type();
this.implInfo = caller.revealDirect(implMethod);
this.implementation = implementation;
this.implMethodType = implementation.type();
try {
this.implInfo = caller.revealDirect(implementation); // may throw SecurityException
} catch (IllegalArgumentException e) {
throw new LambdaConversionException(implementation + " is not direct or cannot be cracked");
}
switch (implInfo.getReferenceKind()) {
case REF_invokeVirtual:
case REF_invokeInterface:
@ -171,33 +178,33 @@ import static sun.invoke.util.Wrapper.isWrapperType;
throw new LambdaConversionException(String.format("Unsupported MethodHandle kind: %s", implInfo));
}
this.instantiatedMethodType = instantiatedMethodType;
this.dynamicMethodType = dynamicMethodType;
this.isSerializable = isSerializable;
this.markerInterfaces = markerInterfaces;
this.additionalBridges = additionalBridges;
this.altInterfaces = altInterfaces;
this.altMethods = altMethods;
if (samMethodName.isEmpty() ||
samMethodName.indexOf('.') >= 0 ||
samMethodName.indexOf(';') >= 0 ||
samMethodName.indexOf('[') >= 0 ||
samMethodName.indexOf('/') >= 0 ||
samMethodName.indexOf('<') >= 0 ||
samMethodName.indexOf('>') >= 0) {
if (interfaceMethodName.isEmpty() ||
interfaceMethodName.indexOf('.') >= 0 ||
interfaceMethodName.indexOf(';') >= 0 ||
interfaceMethodName.indexOf('[') >= 0 ||
interfaceMethodName.indexOf('/') >= 0 ||
interfaceMethodName.indexOf('<') >= 0 ||
interfaceMethodName.indexOf('>') >= 0) {
throw new LambdaConversionException(String.format(
"Method name '%s' is not legal",
samMethodName));
interfaceMethodName));
}
if (!samBase.isInterface()) {
if (!interfaceClass.isInterface()) {
throw new LambdaConversionException(String.format(
"Functional interface %s is not an interface",
samBase.getName()));
"%s is not an interface",
interfaceClass.getName()));
}
for (Class<?> c : markerInterfaces) {
for (Class<?> c : altInterfaces) {
if (!c.isInterface()) {
throw new LambdaConversionException(String.format(
"Marker interface %s is not an interface",
"%s is not an interface",
c.getName()));
}
}
@ -220,26 +227,26 @@ import static sun.invoke.util.Wrapper.isWrapperType;
void validateMetafactoryArgs() throws LambdaConversionException {
// Check arity: captured + SAM == impl
final int implArity = implMethodType.parameterCount();
final int capturedArity = invokedType.parameterCount();
final int samArity = samMethodType.parameterCount();
final int instantiatedArity = instantiatedMethodType.parameterCount();
final int capturedArity = factoryType.parameterCount();
final int samArity = interfaceMethodType.parameterCount();
final int dynamicArity = dynamicMethodType.parameterCount();
if (implArity != capturedArity + samArity) {
throw new LambdaConversionException(
String.format("Incorrect number of parameters for %s method %s; %d captured parameters, %d functional interface method parameters, %d implementation parameters",
implIsInstanceMethod ? "instance" : "static", implInfo,
capturedArity, samArity, implArity));
}
if (instantiatedArity != samArity) {
if (dynamicArity != samArity) {
throw new LambdaConversionException(
String.format("Incorrect number of parameters for %s method %s; %d instantiated parameters, %d functional interface method parameters",
String.format("Incorrect number of parameters for %s method %s; %d dynamic parameters, %d functional interface method parameters",
implIsInstanceMethod ? "instance" : "static", implInfo,
instantiatedArity, samArity));
dynamicArity, samArity));
}
for (MethodType bridgeMT : additionalBridges) {
for (MethodType bridgeMT : altMethods) {
if (bridgeMT.parameterCount() != samArity) {
throw new LambdaConversionException(
String.format("Incorrect number of parameters for bridge signature %s; incompatible with %s",
bridgeMT, samMethodType));
bridgeMT, interfaceMethodType));
}
}
@ -254,12 +261,12 @@ import static sun.invoke.util.Wrapper.isWrapperType;
// receiver is function parameter
capturedStart = 0;
samStart = 1;
receiverClass = instantiatedMethodType.parameterType(0);
receiverClass = dynamicMethodType.parameterType(0);
} else {
// receiver is a captured variable
capturedStart = 1;
samStart = capturedArity;
receiverClass = invokedType.parameterType(0);
receiverClass = factoryType.parameterType(0);
}
// check receiver type
@ -277,7 +284,7 @@ import static sun.invoke.util.Wrapper.isWrapperType;
// Check for exact match on non-receiver captured arguments
for (int i=capturedStart; i<capturedArity; i++) {
Class<?> implParamType = implMethodType.parameterType(i);
Class<?> capturedParamType = invokedType.parameterType(i);
Class<?> capturedParamType = factoryType.parameterType(i);
if (!capturedParamType.equals(implParamType)) {
throw new LambdaConversionException(
String.format("Type mismatch in captured lambda parameter %d: expecting %s, found %s",
@ -287,16 +294,16 @@ import static sun.invoke.util.Wrapper.isWrapperType;
// Check for adaptation match on non-receiver SAM arguments
for (int i=samStart; i<implArity; i++) {
Class<?> implParamType = implMethodType.parameterType(i);
Class<?> instantiatedParamType = instantiatedMethodType.parameterType(i - capturedArity);
if (!isAdaptableTo(instantiatedParamType, implParamType, true)) {
Class<?> dynamicParamType = dynamicMethodType.parameterType(i - capturedArity);
if (!isAdaptableTo(dynamicParamType, implParamType, true)) {
throw new LambdaConversionException(
String.format("Type mismatch for lambda argument %d: %s is not convertible to %s",
i, instantiatedParamType, implParamType));
i, dynamicParamType, implParamType));
}
}
// Adaptation match: return type
Class<?> expectedType = instantiatedMethodType.returnType();
Class<?> expectedType = dynamicMethodType.returnType();
Class<?> actualReturnType = implMethodType.returnType();
if (!isAdaptableToAsReturn(actualReturnType, expectedType)) {
throw new LambdaConversionException(
@ -305,29 +312,29 @@ import static sun.invoke.util.Wrapper.isWrapperType;
}
// Check descriptors of generated methods
checkDescriptor(samMethodType);
for (MethodType bridgeMT : additionalBridges) {
checkDescriptor(interfaceMethodType);
for (MethodType bridgeMT : altMethods) {
checkDescriptor(bridgeMT);
}
}
/** Validate that the given descriptor's types are compatible with {@code instantiatedMethodType} **/
/** Validate that the given descriptor's types are compatible with {@code dynamicMethodType} **/
private void checkDescriptor(MethodType descriptor) throws LambdaConversionException {
for (int i = 0; i < instantiatedMethodType.parameterCount(); i++) {
Class<?> instantiatedParamType = instantiatedMethodType.parameterType(i);
for (int i = 0; i < dynamicMethodType.parameterCount(); i++) {
Class<?> dynamicParamType = dynamicMethodType.parameterType(i);
Class<?> descriptorParamType = descriptor.parameterType(i);
if (!descriptorParamType.isAssignableFrom(instantiatedParamType)) {
String msg = String.format("Type mismatch for instantiated parameter %d: %s is not a subtype of %s",
i, instantiatedParamType, descriptorParamType);
if (!descriptorParamType.isAssignableFrom(dynamicParamType)) {
String msg = String.format("Type mismatch for dynamic parameter %d: %s is not a subtype of %s",
i, dynamicParamType, descriptorParamType);
throw new LambdaConversionException(msg);
}
}
Class<?> instantiatedReturnType = instantiatedMethodType.returnType();
Class<?> dynamicReturnType = dynamicMethodType.returnType();
Class<?> descriptorReturnType = descriptor.returnType();
if (!isAdaptableToAsReturnStrict(instantiatedReturnType, descriptorReturnType)) {
if (!isAdaptableToAsReturnStrict(dynamicReturnType, descriptorReturnType)) {
String msg = String.format("Type mismatch for lambda expected return: %s is not convertible to %s",
instantiatedReturnType, descriptorReturnType);
dynamicReturnType, descriptorReturnType);
throw new LambdaConversionException(msg);
}
}

View file

@ -128,65 +128,68 @@ import static jdk.internal.org.objectweb.asm.Opcodes.*;
*
* @param caller Stacked automatically by VM; represents a lookup context
* with the accessibility privileges of the caller.
* @param invokedType Stacked automatically by VM; the signature of the
* @param factoryType Stacked automatically by VM; the signature of the
* invoked method, which includes the expected static
* type of the returned lambda object, and the static
* types of the captured arguments for the lambda. In
* the event that the implementation method is an
* instance method, the first argument in the invocation
* signature will correspond to the receiver.
* @param samMethodName Name of the method in the functional interface to
* which the lambda or method reference is being
* converted, represented as a String.
* @param samMethodType Type of the method in the functional interface to
* which the lambda or method reference is being
* converted, represented as a MethodType.
* @param implMethod The implementation method which should be called (with
* suitable adaptation of argument types, return types,
* and adjustment for captured arguments) when methods of
* the resulting functional interface instance are invoked.
* @param instantiatedMethodType The signature of the primary functional
* interface method after type variables are
* substituted with their instantiation from
* the capture site
* @param interfaceMethodName Name of the method in the functional interface to
* which the lambda or method reference is being
* converted, represented as a String.
* @param interfaceMethodType Type of the method in the functional interface to
* which the lambda or method reference is being
* converted, represented as a MethodType.
* @param implementation The implementation method which should be called (with
* suitable adaptation of argument types, return types,
* and adjustment for captured arguments) when methods of
* the resulting functional interface instance are invoked.
* @param dynamicMethodType The signature of the primary functional
* interface method after type variables are
* substituted with their instantiation from
* the capture site
* @param isSerializable Should the lambda be made serializable? If set,
* either the target type or one of the additional SAM
* types must extend {@code Serializable}.
* @param markerInterfaces Additional interfaces which the lambda object
* should implement.
* @param additionalBridges Method types for additional signatures to be
* bridged to the implementation method
* @param altInterfaces Additional interfaces which the lambda object
* should implement.
* @param altMethods Method types for additional signatures to be
* implemented by invoking the implementation method
* @throws LambdaConversionException If any of the meta-factory protocol
* invariants are violated
* invariants are violated
* @throws SecurityException If a security manager is present, and it
* <a href="MethodHandles.Lookup.html#secmgr">denies access</a>
* from {@code caller} to the package of {@code implementation}.
*/
public InnerClassLambdaMetafactory(MethodHandles.Lookup caller,
MethodType invokedType,
String samMethodName,
MethodType samMethodType,
MethodHandle implMethod,
MethodType instantiatedMethodType,
MethodType factoryType,
String interfaceMethodName,
MethodType interfaceMethodType,
MethodHandle implementation,
MethodType dynamicMethodType,
boolean isSerializable,
Class<?>[] markerInterfaces,
MethodType[] additionalBridges)
Class<?>[] altInterfaces,
MethodType[] altMethods)
throws LambdaConversionException {
super(caller, invokedType, samMethodName, samMethodType,
implMethod, instantiatedMethodType,
isSerializable, markerInterfaces, additionalBridges);
super(caller, factoryType, interfaceMethodName, interfaceMethodType,
implementation, dynamicMethodType,
isSerializable, altInterfaces, altMethods);
implMethodClassName = implClass.getName().replace('.', '/');
implMethodName = implInfo.getName();
implMethodDesc = implInfo.getMethodType().toMethodDescriptorString();
constructorType = invokedType.changeReturnType(Void.TYPE);
constructorType = factoryType.changeReturnType(Void.TYPE);
lambdaClassName = lambdaClassName(targetClass);
useImplMethodHandle = !Modifier.isPublic(implInfo.getModifiers()) &&
!VerifyAccess.isSamePackage(implClass, implInfo.getDeclaringClass());
cw = new ClassWriter(ClassWriter.COMPUTE_MAXS);
int parameterCount = invokedType.parameterCount();
int parameterCount = factoryType.parameterCount();
if (parameterCount > 0) {
argNames = new String[parameterCount];
argDescs = new String[parameterCount];
for (int i = 0; i < parameterCount; i++) {
argNames[i] = "arg$" + (i + 1);
argDescs[i] = BytecodeDescriptor.unparse(invokedType.parameterType(i));
argDescs[i] = BytecodeDescriptor.unparse(factoryType.parameterType(i));
}
} else {
argNames = argDescs = EMPTY_STRING_ARRAY;
@ -216,13 +219,13 @@ import static jdk.internal.org.objectweb.asm.Opcodes.*;
@Override
CallSite buildCallSite() throws LambdaConversionException {
final Class<?> innerClass = spinInnerClass();
if (invokedType.parameterCount() == 0) {
if (factoryType.parameterCount() == 0) {
// In the case of a non-capturing lambda, we optimize linkage by pre-computing a single instance,
// unless we've suppressed eager initialization
if (disableEagerInitialization) {
try {
return new ConstantCallSite(caller.findStaticGetter(innerClass, LAMBDA_INSTANCE_FIELD,
invokedType.returnType()));
factoryType.returnType()));
} catch (ReflectiveOperationException e) {
throw new LambdaConversionException(
"Exception finding " + LAMBDA_INSTANCE_FIELD + " static field", e);
@ -249,15 +252,15 @@ import static jdk.internal.org.objectweb.asm.Opcodes.*;
try {
Object inst = ctrs[0].newInstance();
return new ConstantCallSite(MethodHandles.constant(samBase, inst));
return new ConstantCallSite(MethodHandles.constant(interfaceClass, inst));
} catch (ReflectiveOperationException e) {
throw new LambdaConversionException("Exception instantiating lambda object", e);
}
}
} else {
try {
MethodHandle mh = caller.findConstructor(innerClass, invokedType.changeReturnType(void.class));
return new ConstantCallSite(mh.asType(invokedType));
MethodHandle mh = caller.findConstructor(innerClass, constructorType);
return new ConstantCallSite(mh.asType(factoryType));
} catch (ReflectiveOperationException e) {
throw new LambdaConversionException("Exception finding constructor", e);
}
@ -278,28 +281,28 @@ import static jdk.internal.org.objectweb.asm.Opcodes.*;
if (CDS.isDumpingArchive()) {
Class<?> innerClass = generateInnerClass();
LambdaProxyClassArchive.register(targetClass,
samMethodName,
invokedType,
samMethodType,
implMethod,
instantiatedMethodType,
interfaceMethodName,
factoryType,
interfaceMethodType,
implementation,
dynamicMethodType,
isSerializable,
markerInterfaces,
additionalBridges,
altInterfaces,
altMethods,
innerClass);
return innerClass;
}
// load from CDS archive if present
Class<?> innerClass = LambdaProxyClassArchive.find(targetClass,
samMethodName,
invokedType,
samMethodType,
implMethod,
instantiatedMethodType,
interfaceMethodName,
factoryType,
interfaceMethodType,
implementation,
dynamicMethodType,
isSerializable,
markerInterfaces,
additionalBridges);
altInterfaces,
altMethods);
if (innerClass != null) return innerClass;
}
return generateInnerClass();
@ -309,38 +312,31 @@ import static jdk.internal.org.objectweb.asm.Opcodes.*;
* Generate a class file which implements the functional
* interface, define and return the class.
*
* @implNote The class that is generated does not include signature
* information for exceptions that may be present on the SAM method.
* This is to reduce classfile size, and is harmless as checked exceptions
* are erased anyway, no one will ever compile against this classfile,
* and we make no guarantees about the reflective properties of lambda
* objects.
*
* @return a Class which implements the functional interface
* @throws LambdaConversionException If properly formed functional interface
* is not found
*/
@SuppressWarnings("removal")
private Class<?> generateInnerClass() throws LambdaConversionException {
String[] interfaces;
String samIntf = samBase.getName().replace('.', '/');
boolean accidentallySerializable = !isSerializable && Serializable.class.isAssignableFrom(samBase);
if (markerInterfaces.length == 0) {
interfaces = new String[]{samIntf};
String[] interfaceNames;
String interfaceName = interfaceClass.getName().replace('.', '/');
boolean accidentallySerializable = !isSerializable && Serializable.class.isAssignableFrom(interfaceClass);
if (altInterfaces.length == 0) {
interfaceNames = new String[]{interfaceName};
} else {
// Assure no duplicate interfaces (ClassFormatError)
Set<String> itfs = new LinkedHashSet<>(markerInterfaces.length + 1);
itfs.add(samIntf);
for (Class<?> markerInterface : markerInterfaces) {
itfs.add(markerInterface.getName().replace('.', '/'));
accidentallySerializable |= !isSerializable && Serializable.class.isAssignableFrom(markerInterface);
Set<String> itfs = new LinkedHashSet<>(altInterfaces.length + 1);
itfs.add(interfaceName);
for (Class<?> i : altInterfaces) {
itfs.add(i.getName().replace('.', '/'));
accidentallySerializable |= !isSerializable && Serializable.class.isAssignableFrom(i);
}
interfaces = itfs.toArray(new String[itfs.size()]);
interfaceNames = itfs.toArray(new String[itfs.size()]);
}
cw.visit(CLASSFILE_VERSION, ACC_SUPER + ACC_FINAL + ACC_SYNTHETIC,
lambdaClassName, null,
JAVA_LANG_OBJECT, interfaces);
JAVA_LANG_OBJECT, interfaceNames);
// Generate final fields to be filled in by constructor
for (int i = 0; i < argDescs.length; i++) {
@ -353,19 +349,19 @@ import static jdk.internal.org.objectweb.asm.Opcodes.*;
generateConstructor();
if (invokedType.parameterCount() == 0 && disableEagerInitialization) {
if (factoryType.parameterCount() == 0 && disableEagerInitialization) {
generateClassInitializer();
}
// Forward the SAM method
MethodVisitor mv = cw.visitMethod(ACC_PUBLIC, samMethodName,
samMethodType.toMethodDescriptorString(), null, null);
new ForwardingMethodGenerator(mv).generate(samMethodType);
MethodVisitor mv = cw.visitMethod(ACC_PUBLIC, interfaceMethodName,
interfaceMethodType.toMethodDescriptorString(), null, null);
new ForwardingMethodGenerator(mv).generate(interfaceMethodType);
// Forward the bridges
if (additionalBridges != null) {
for (MethodType mt : additionalBridges) {
mv = cw.visitMethod(ACC_PUBLIC|ACC_BRIDGE, samMethodName,
// Forward the altMethods
if (altMethods != null) {
for (MethodType mt : altMethods) {
mv = cw.visitMethod(ACC_PUBLIC, interfaceMethodName,
mt.toMethodDescriptorString(), null, null);
new ForwardingMethodGenerator(mv).generate(mt);
}
@ -403,9 +399,9 @@ import static jdk.internal.org.objectweb.asm.Opcodes.*;
// package, the target class does not have a bridge and this method reference
// has been changed from public to protected after the target class was compiled.
// This lambda proxy class has no access to the resolved method.
// So this workaround by passing the live implMethod method handle
// So this workaround by passing the live implementation method handle
// to the proxy class to invoke directly.
lookup = caller.defineHiddenClassWithClassData(classBytes, implMethod, !disableEagerInitialization,
lookup = caller.defineHiddenClassWithClassData(classBytes, implementation, !disableEagerInitialization,
NESTMATE, STRONG);
} else {
lookup = caller.defineHiddenClass(classBytes, !disableEagerInitialization, NESTMATE, STRONG);
@ -422,7 +418,7 @@ import static jdk.internal.org.objectweb.asm.Opcodes.*;
* Generate a static field and a static initializer that sets this field to an instance of the lambda
*/
private void generateClassInitializer() {
String lambdaTypeDescriptor = invokedType.returnType().descriptorString();
String lambdaTypeDescriptor = factoryType.returnType().descriptorString();
// Generate the static final field that holds the lambda singleton
FieldVisitor fv = cw.visitField(ACC_PRIVATE | ACC_STATIC | ACC_FINAL,
@ -435,7 +431,7 @@ import static jdk.internal.org.objectweb.asm.Opcodes.*;
clinit.visitTypeInsn(NEW, lambdaClassName);
clinit.visitInsn(Opcodes.DUP);
assert invokedType.parameterCount() == 0;
assert factoryType.parameterCount() == 0;
clinit.visitMethodInsn(INVOKESPECIAL, lambdaClassName, NAME_CTOR, constructorType.toMethodDescriptorString(), false);
clinit.visitFieldInsn(PUTSTATIC, lambdaClassName, LAMBDA_INSTANCE_FIELD, lambdaTypeDescriptor);
@ -455,10 +451,10 @@ import static jdk.internal.org.objectweb.asm.Opcodes.*;
ctor.visitVarInsn(ALOAD, 0);
ctor.visitMethodInsn(INVOKESPECIAL, JAVA_LANG_OBJECT, NAME_CTOR,
METHOD_DESCRIPTOR_VOID, false);
int parameterCount = invokedType.parameterCount();
int parameterCount = factoryType.parameterCount();
for (int i = 0, lvIndex = 0; i < parameterCount; i++) {
ctor.visitVarInsn(ALOAD, 0);
Class<?> argType = invokedType.parameterType(i);
Class<?> argType = factoryType.parameterType(i);
ctor.visitVarInsn(getLoadOpcode(argType), lvIndex + 1);
lvIndex += getParameterSize(argType);
ctor.visitFieldInsn(PUTFIELD, lambdaClassName, argNames[i], argDescs[i]);
@ -483,14 +479,14 @@ import static jdk.internal.org.objectweb.asm.Opcodes.*;
mv.visitTypeInsn(NEW, NAME_SERIALIZED_LAMBDA);
mv.visitInsn(DUP);
mv.visitLdcInsn(Type.getType(targetClass));
mv.visitLdcInsn(invokedType.returnType().getName().replace('.', '/'));
mv.visitLdcInsn(samMethodName);
mv.visitLdcInsn(samMethodType.toMethodDescriptorString());
mv.visitLdcInsn(factoryType.returnType().getName().replace('.', '/'));
mv.visitLdcInsn(interfaceMethodName);
mv.visitLdcInsn(interfaceMethodType.toMethodDescriptorString());
mv.visitLdcInsn(implInfo.getReferenceKind());
mv.visitLdcInsn(implInfo.getDeclaringClass().getName().replace('.', '/'));
mv.visitLdcInsn(implInfo.getName());
mv.visitLdcInsn(implInfo.getMethodType().toMethodDescriptorString());
mv.visitLdcInsn(instantiatedMethodType.toMethodDescriptorString());
mv.visitLdcInsn(dynamicMethodType.toMethodDescriptorString());
mv.iconst(argDescs.length);
mv.visitTypeInsn(ANEWARRAY, JAVA_LANG_OBJECT);
for (int i = 0; i < argDescs.length; i++) {
@ -592,12 +588,12 @@ import static jdk.internal.org.objectweb.asm.Opcodes.*;
private void convertArgumentTypes(MethodType samType) {
int lvIndex = 0;
int samParametersLength = samType.parameterCount();
int captureArity = invokedType.parameterCount();
int captureArity = factoryType.parameterCount();
for (int i = 0; i < samParametersLength; i++) {
Class<?> argType = samType.parameterType(i);
visitVarInsn(getLoadOpcode(argType), lvIndex + 1);
lvIndex += getParameterSize(argType);
convertType(argType, implMethodType.parameterType(captureArity + i), instantiatedMethodType.parameterType(i));
convertType(argType, implMethodType.parameterType(captureArity + i), dynamicMethodType.parameterType(i));
}
}

View file

@ -1,5 +1,5 @@
/*
* Copyright (c) 2012, 2017, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2012, 2021, 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
@ -27,6 +27,8 @@ package java.lang.invoke;
import java.io.Serializable;
import java.util.Arrays;
import java.lang.reflect.Array;
import java.util.Objects;
/**
* <p>Methods to facilitate the creation of simple "function objects" that
@ -39,41 +41,47 @@ import java.util.Arrays;
* <p>Indirect access to the behavior specified by the provided {@code MethodHandle}
* proceeds in order through three phases:
* <ul>
* <li><em>Linkage</em> occurs when the methods in this class are invoked.
* <li><p><em>Linkage</em> occurs when the methods in this class are invoked.
* They take as arguments an interface to be implemented (typically a
* <em>functional interface</em>, one with a single abstract method), a
* name and signature of a method from that interface to be implemented, a
* method handle describing the desired implementation behavior
* for that method, and possibly other additional metadata, and produce a
* {@link CallSite} whose target can be used to create suitable function
* objects. Linkage may involve dynamically loading a new class that
* implements the target interface. The {@code CallSite} can be considered a
* "factory" for function objects and so these linkage methods are referred
* to as "metafactories".</li>
* {@linkplain MethodHandleInfo direct method handle} describing the desired
* implementation behavior for that method, and possibly other additional
* metadata, and produce a {@link CallSite} whose target can be used to
* create suitable function objects.
*
* <li><em>Capture</em> occurs when the {@code CallSite}'s target is
* <p>Linkage may involve dynamically loading a new class that implements
* the target interface, or re-using a suitable existing class.
*
* <p>The {@code CallSite} can be considered a "factory" for function
* objects and so these linkage methods are referred to as
* "metafactories".</li>
*
* <li><p><em>Capture</em> occurs when the {@code CallSite}'s target is
* invoked, typically through an {@code invokedynamic} call site,
* producing a function object. This may occur many times for
* a single factory {@code CallSite}. Capture may involve allocation of a
* new function object, or may return an existing function object. The
* behavior {@code MethodHandle} may have additional parameters beyond those
* of the specified interface method; these are referred to as <em>captured
* parameters</em>, which must be provided as arguments to the
* {@code CallSite} target, and which may be early-bound to the behavior
* {@code MethodHandle}. The number of captured parameters and their types
* are determined during linkage.
* The identity of a function object produced by invoking the
* {@code CallSite}'s target is unpredictable, and therefore
* identity-sensitive operations (such as reference equality, object
* locking, and {@code System.identityHashCode()} may produce different
* results in different implementations, or even upon different invocations
* in the same implementation.</li>
* producing a function object. This may occur many times for
* a single factory {@code CallSite}.
*
* <li><em>Invocation</em> occurs when an implemented interface method
* is invoked on a function object. This may occur many times for a single
* function object. The method referenced by the behavior {@code MethodHandle}
* is invoked with the captured arguments and any additional arguments
* provided on invocation, as if by {@link MethodHandle#invoke(Object...)}.</li>
* <p>If the behavior {@code MethodHandle} has additional parameters beyond
* those of the specified interface method, these are referred to as
* <em>captured parameters</em>, which must be provided as arguments to the
* {@code CallSite} target. The expected number and types of captured
* parameters are determined during linkage.
*
* <p>Capture may involve allocation of a new function object, or may return
* a suitable existing function object. The identity of a function object
* produced by capture is unpredictable, and therefore identity-sensitive
* operations (such as reference equality, object locking, and {@code
* System.identityHashCode()}) may produce different results in different
* implementations, or even upon different invocations in the same
* implementation.</li>
*
* <li><p><em>Invocation</em> occurs when an implemented interface method is
* invoked on a function object. This may occur many times for a single
* function object. The method referenced by the implementation
* {@code MethodHandle} is invoked, passing to it the captured arguments and
* the invocation arguments. The result of the method is returned.
* </li>
* </ul>
*
* <p>It is sometimes useful to restrict the set of inputs or results permitted
@ -81,7 +89,7 @@ import java.util.Arrays;
* is parameterized as {@code Predicate<String>}, the input must be a
* {@code String}, even though the method to implement allows any {@code Object}.
* At linkage time, an additional {@link MethodType} parameter describes the
* "instantiated" method type; on invocation, the arguments and eventual result
* "dynamic" method type; on invocation, the arguments and eventual result
* are checked against this {@code MethodType}.
*
* <p>This class provides two forms of linkage methods: a standard version
@ -94,7 +102,7 @@ import java.util.Arrays;
* manage the following attributes of function objects:
*
* <ul>
* <li><em>Bridging.</em> It is sometimes useful to implement multiple
* <li><em>Multiple methods.</em> It is sometimes useful to implement multiple
* variations of the method signature, involving argument or return type
* adaptation. This occurs when multiple distinct VM signatures for a method
* are logically considered to be the same method by the language. The
@ -121,24 +129,22 @@ import java.util.Arrays;
*
* <p>Assume the linkage arguments are as follows:
* <ul>
* <li>{@code invokedType} (describing the {@code CallSite} signature) has
* <li>{@code factoryType} (describing the {@code CallSite} signature) has
* K parameters of types (D1..Dk) and return type Rd;</li>
* <li>{@code samMethodType} (describing the implemented method type) has N
* <li>{@code interfaceMethodType} (describing the implemented method type) has N
* parameters, of types (U1..Un) and return type Ru;</li>
* <li>{@code implMethod} (the {@code MethodHandle} providing the
* implementation has M parameters, of types (A1..Am) and return type Ra
* <li>{@code implementation} (the {@code MethodHandle} providing the
* implementation) has M parameters, of types (A1..Am) and return type Ra
* (if the method describes an instance method, the method type of this
* method handle already includes an extra first argument corresponding to
* the receiver);</li>
* <li>{@code instantiatedMethodType} (allowing restrictions on invocation)
* <li>{@code dynamicMethodType} (allowing restrictions on invocation)
* has N parameters, of types (T1..Tn) and return type Rt.</li>
* </ul>
*
* <p>Then the following linkage invariants must hold:
* <ul>
* <li>Rd is an interface</li>
* <li>{@code implMethod} is a <em>direct method handle</em></li>
* <li>{@code samMethodType} and {@code instantiatedMethodType} have the same
* <li>{@code interfaceMethodType} and {@code dynamicMethodType} have the same
* arity N, and for i=1..N, Ti and Ui are the same type, or Ti and Ui are
* both reference types and Ti is a subtype of Ui</li>
* <li>Either Rt and Ru are the same type, or both are reference types and
@ -150,7 +156,7 @@ import java.util.Arrays;
* adaptable to Rt</li>
* </ul>
*
* <p>Further, at capture time, if {@code implMethod} corresponds to an instance
* <p>Further, at capture time, if {@code implementation} corresponds to an instance
* method, and there are any capture arguments ({@code K > 0}), then the first
* capture argument (corresponding to the receiver) must be non-null.
*
@ -218,30 +224,30 @@ import java.util.Arrays;
* method signature describing the number and static types (but not the values)
* of the dynamic arguments and the static return type of the invokedynamic site.
*
* @implNote The implementation method is described with a method handle. In
* theory, any method handle could be used. Currently supported are direct method
* handles representing invocation of virtual, interface, constructor and static
* methods.
* <p>The implementation method is described with a direct method handle
* referencing a method or constructor. In theory, any method handle could be
* used, but this is not compatible with some implementation techniques and
* would complicate the work implementations must do.
*
* @since 1.8
*/
public final class LambdaMetafactory {
private LambdaMetafactory() {}
/** Flag for alternate metafactories indicating the lambda object
/** Flag for {@link #altMetafactory} indicating the lambda object
* must be serializable */
public static final int FLAG_SERIALIZABLE = 1 << 0;
/**
* Flag for alternate metafactories indicating the lambda object implements
* other marker interfaces
* besides Serializable
* Flag for {@link #altMetafactory} indicating the lambda object implements
* other interfaces besides {@code Serializable}
*/
public static final int FLAG_MARKERS = 1 << 1;
/**
* Flag for alternate metafactories indicating the lambda object requires
* additional bridge methods
* additional methods that invoke the {@code implementation}
*/
public static final int FLAG_BRIDGES = 1 << 2;
@ -249,7 +255,7 @@ public final class LambdaMetafactory {
private static final MethodType[] EMPTY_MT_ARRAY = new MethodType[0];
// LambdaMetafactory bootstrap methods are startup sensitive, and may be
// special cased in java.lang.invokeBootstrapMethodInvoker to ensure
// special cased in java.lang.invoke.BootstrapMethodInvoker to ensure
// methods are invoked with exact type information to avoid generating
// code for runtime checks. Take care any changes or additions here are
// reflected there as appropriate.
@ -269,9 +275,9 @@ public final class LambdaMetafactory {
*
* <p>When the target of the {@code CallSite} returned from this method is
* invoked, the resulting function objects are instances of a class which
* implements the interface named by the return type of {@code invokedType},
* declares a method with the name given by {@code invokedName} and the
* signature given by {@code samMethodType}. It may also override additional
* implements the interface named by the return type of {@code factoryType},
* declares a method with the name given by {@code interfaceMethodName} and the
* signature given by {@code interfaceMethodType}. It may also override additional
* methods from {@code Object}.
*
* @param caller Represents a lookup context with the accessibility
@ -280,50 +286,57 @@ public final class LambdaMetafactory {
* full privilege access}.
* When used with {@code invokedynamic}, this is stacked
* automatically by the VM.
* @param invokedName The name of the method to implement. When used with
* {@code invokedynamic}, this is provided by the
* {@code NameAndType} of the {@code InvokeDynamic}
* structure and is stacked automatically by the VM.
* @param invokedType The expected signature of the {@code CallSite}. The
* @param interfaceMethodName The name of the method to implement. When used with
* {@code invokedynamic}, this is provided by the
* {@code NameAndType} of the {@code InvokeDynamic}
* structure and is stacked automatically by the VM.
* @param factoryType The expected signature of the {@code CallSite}. The
* parameter types represent the types of capture variables;
* the return type is the interface to implement. When
* used with {@code invokedynamic}, this is provided by
* the {@code NameAndType} of the {@code InvokeDynamic}
* structure and is stacked automatically by the VM.
* In the event that the implementation method is an
* instance method and this signature has any parameters,
* the first parameter in the invocation signature must
* correspond to the receiver.
* @param samMethodType Signature and return type of method to be implemented
* by the function object.
* @param implMethod A direct method handle describing the implementation
* method which should be called (with suitable adaptation
* of argument types, return types, and with captured
* arguments prepended to the invocation arguments) at
* invocation time.
* @param instantiatedMethodType The signature and return type that should
* be enforced dynamically at invocation time.
* This may be the same as {@code samMethodType},
* or may be a specialization of it.
* @param interfaceMethodType Signature and return type of method to be
* implemented by the function object.
* @param implementation A direct method handle describing the implementation
* method which should be called (with suitable adaptation
* of argument types and return types, and with captured
* arguments prepended to the invocation arguments) at
* invocation time.
* @param dynamicMethodType The signature and return type that should
* be enforced dynamically at invocation time.
* In simple use cases this is the same as
* {@code interfaceMethodType}.
* @return a CallSite whose target can be used to perform capture, generating
* instances of the interface named by {@code invokedType}
* @throws LambdaConversionException If any of the linkage invariants
* described {@link LambdaMetafactory above}
* are violated, or the lookup context
* does not have private access privileges.
* instances of the interface named by {@code factoryType}
* @throws LambdaConversionException If {@code caller} does not have full privilege
* access, or if {@code interfaceMethodName} is not a valid JVM
* method name, or if the return type of {@code factoryType} is not
* an interface, or if {@code implementation} is not a direct method
* handle referencing a method or constructor, or if the linkage
* invariants are violated, as defined {@link LambdaMetafactory above}.
* @throws NullPointerException If any argument is {@code null}.
* @throws SecurityException If a security manager is present, and it
* <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
* from {@code caller} to the package of {@code implementation}.
*/
public static CallSite metafactory(MethodHandles.Lookup caller,
String invokedName,
MethodType invokedType,
MethodType samMethodType,
MethodHandle implMethod,
MethodType instantiatedMethodType)
String interfaceMethodName,
MethodType factoryType,
MethodType interfaceMethodType,
MethodHandle implementation,
MethodType dynamicMethodType)
throws LambdaConversionException {
AbstractValidatingLambdaMetafactory mf;
mf = new InnerClassLambdaMetafactory(caller, invokedType,
invokedName, samMethodType,
implMethod, instantiatedMethodType,
false, EMPTY_CLASS_ARRAY, EMPTY_MT_ARRAY);
mf = new InnerClassLambdaMetafactory(Objects.requireNonNull(caller),
Objects.requireNonNull(factoryType),
Objects.requireNonNull(interfaceMethodName),
Objects.requireNonNull(interfaceMethodType),
Objects.requireNonNull(implementation),
Objects.requireNonNull(dynamicMethodType),
false,
EMPTY_CLASS_ARRAY,
EMPTY_MT_ARRAY);
mf.validateMetafactoryArgs();
return mf.buildCallSite();
}
@ -350,8 +363,8 @@ public final class LambdaMetafactory {
*
* <pre>{@code
* CallSite altMetafactory(MethodHandles.Lookup caller,
* String invokedName,
* MethodType invokedType,
* String interfaceMethodName,
* MethodType factoryType,
* Object... args)
* }</pre>
*
@ -359,16 +372,16 @@ public final class LambdaMetafactory {
*
* <pre>{@code
* CallSite altMetafactory(MethodHandles.Lookup caller,
* String invokedName,
* MethodType invokedType,
* MethodType samMethodType,
* MethodHandle implMethod,
* MethodType instantiatedMethodType,
* String interfaceMethodName,
* MethodType factoryType,
* MethodType interfaceMethodType,
* MethodHandle implementation,
* MethodType dynamicMethodType,
* int flags,
* int markerInterfaceCount, // IF flags has MARKERS set
* Class... markerInterfaces, // IF flags has MARKERS set
* int bridgeCount, // IF flags has BRIDGES set
* MethodType... bridges // IF flags has BRIDGES set
* int altInterfaceCount, // IF flags has MARKERS set
* Class... altInterfaces, // IF flags has MARKERS set
* int altMethodCount, // IF flags has BRIDGES set
* MethodType... altMethods // IF flags has BRIDGES set
* )
* }</pre>
*
@ -380,25 +393,25 @@ public final class LambdaMetafactory {
* <li>{@code flags} indicates additional options; this is a bitwise
* OR of desired flags. Defined flags are {@link #FLAG_BRIDGES},
* {@link #FLAG_MARKERS}, and {@link #FLAG_SERIALIZABLE}.</li>
* <li>{@code markerInterfaceCount} is the number of additional interfaces
* <li>{@code altInterfaceCount} is the number of additional interfaces
* the function object should implement, and is present if and only if the
* {@code FLAG_MARKERS} flag is set.</li>
* <li>{@code markerInterfaces} is a variable-length list of additional
* interfaces to implement, whose length equals {@code markerInterfaceCount},
* <li>{@code altInterfaces} is a variable-length list of additional
* interfaces to implement, whose length equals {@code altInterfaceCount},
* and is present if and only if the {@code FLAG_MARKERS} flag is set.</li>
* <li>{@code bridgeCount} is the number of additional method signatures
* <li>{@code altMethodCount} is the number of additional method signatures
* the function object should implement, and is present if and only if
* the {@code FLAG_BRIDGES} flag is set.</li>
* <li>{@code bridges} is a variable-length list of additional
* methods signatures to implement, whose length equals {@code bridgeCount},
* <li>{@code altMethods} is a variable-length list of additional
* methods signatures to implement, whose length equals {@code altMethodCount},
* and is present if and only if the {@code FLAG_BRIDGES} flag is set.</li>
* </ul>
*
* <p>Each class named by {@code markerInterfaces} is subject to the same
* restrictions as {@code Rd}, the return type of {@code invokedType},
* <p>Each class named by {@code altInterfaces} is subject to the same
* restrictions as {@code Rd}, the return type of {@code factoryType},
* as described {@link LambdaMetafactory above}. Each {@code MethodType}
* named by {@code bridges} is subject to the same restrictions as
* {@code samMethodType}, as described {@link LambdaMetafactory above}.
* named by {@code altMethods} is subject to the same restrictions as
* {@code interfaceMethodType}, as described {@link LambdaMetafactory above}.
*
* <p>When FLAG_SERIALIZABLE is set in {@code flags}, the function objects
* will implement {@code Serializable}, and will have a {@code writeReplace}
@ -411,10 +424,10 @@ public final class LambdaMetafactory {
* the following properties:
* <ul>
* <li>The class implements the interface named by the return type
* of {@code invokedType} and any interfaces named by {@code markerInterfaces}</li>
* <li>The class declares methods with the name given by {@code invokedName},
* and the signature given by {@code samMethodType} and additional signatures
* given by {@code bridges}</li>
* of {@code factoryType} and any interfaces named by {@code altInterfaces}</li>
* <li>The class declares methods with the name given by {@code interfaceMethodName},
* and the signature given by {@code interfaceMethodType} and additional signatures
* given by {@code altMethods}</li>
* <li>The class may override methods from {@code Object}, and may
* implement methods related to serialization.</li>
* </ul>
@ -425,80 +438,122 @@ public final class LambdaMetafactory {
* full privilege access}.
* When used with {@code invokedynamic}, this is stacked
* automatically by the VM.
* @param invokedName The name of the method to implement. When used with
* {@code invokedynamic}, this is provided by the
* {@code NameAndType} of the {@code InvokeDynamic}
* structure and is stacked automatically by the VM.
* @param invokedType The expected signature of the {@code CallSite}. The
* @param interfaceMethodName The name of the method to implement. When used with
* {@code invokedynamic}, this is provided by the
* {@code NameAndType} of the {@code InvokeDynamic}
* structure and is stacked automatically by the VM.
* @param factoryType The expected signature of the {@code CallSite}. The
* parameter types represent the types of capture variables;
* the return type is the interface to implement. When
* used with {@code invokedynamic}, this is provided by
* the {@code NameAndType} of the {@code InvokeDynamic}
* structure and is stacked automatically by the VM.
* In the event that the implementation method is an
* instance method and this signature has any parameters,
* the first parameter in the invocation signature must
* correspond to the receiver.
* @param args An {@code Object[]} array containing the required
* arguments {@code samMethodType}, {@code implMethod},
* {@code instantiatedMethodType}, {@code flags}, and any
* optional arguments, as described
* {@link #altMetafactory(MethodHandles.Lookup, String, MethodType, Object...)} above}
* @param args An array of {@code Object} containing the required
* arguments {@code interfaceMethodType}, {@code implementation},
* {@code dynamicMethodType}, {@code flags}, and any
* optional arguments, as described above
* @return a CallSite whose target can be used to perform capture, generating
* instances of the interface named by {@code invokedType}
* @throws LambdaConversionException If any of the linkage invariants
* described {@link LambdaMetafactory above}
* are violated, or the lookup context
* does not have private access privileges.
* instances of the interface named by {@code factoryType}
* @throws LambdaConversionException If {@code caller} does not have full privilege
* access, or if {@code interfaceMethodName} is not a valid JVM
* method name, or if the return type of {@code factoryType} is not
* an interface, or if any of {@code altInterfaces} is not an
* interface, or if {@code implementation} is not a direct method
* handle referencing a method or constructor, or if the linkage
* invariants are violated, as defined {@link LambdaMetafactory above}.
* @throws NullPointerException If any argument, or any component of {@code args},
* is {@code null}.
* @throws IllegalArgumentException If the number or types of the components
* of {@code args} do not follow the above rules, or if
* {@code altInterfaceCount} or {@code altMethodCount} are negative
* integers.
* @throws SecurityException If a security manager is present, and it
* <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
* from {@code caller} to the package of {@code implementation}.
*/
public static CallSite altMetafactory(MethodHandles.Lookup caller,
String invokedName,
MethodType invokedType,
String interfaceMethodName,
MethodType factoryType,
Object... args)
throws LambdaConversionException {
MethodType samMethodType = (MethodType)args[0];
MethodHandle implMethod = (MethodHandle)args[1];
MethodType instantiatedMethodType = (MethodType)args[2];
int flags = (Integer) args[3];
Class<?>[] markerInterfaces;
MethodType[] bridges;
int argIndex = 4;
Objects.requireNonNull(caller);
Objects.requireNonNull(interfaceMethodName);
Objects.requireNonNull(factoryType);
Objects.requireNonNull(args);
int argIndex = 0;
MethodType interfaceMethodType = extractArg(args, argIndex++, MethodType.class);
MethodHandle implementation = extractArg(args, argIndex++, MethodHandle.class);
MethodType dynamicMethodType = extractArg(args, argIndex++, MethodType.class);
int flags = extractArg(args, argIndex++, Integer.class);
Class<?>[] altInterfaces = EMPTY_CLASS_ARRAY;
MethodType[] altMethods = EMPTY_MT_ARRAY;
if ((flags & FLAG_MARKERS) != 0) {
int markerCount = (Integer) args[argIndex++];
markerInterfaces = new Class<?>[markerCount];
System.arraycopy(args, argIndex, markerInterfaces, 0, markerCount);
argIndex += markerCount;
int altInterfaceCount = extractArg(args, argIndex++, Integer.class);
if (altInterfaceCount < 0) {
throw new IllegalArgumentException("negative argument count");
}
if (altInterfaceCount > 0) {
altInterfaces = extractArgs(args, argIndex, Class.class, altInterfaceCount);
argIndex += altInterfaceCount;
}
}
else
markerInterfaces = EMPTY_CLASS_ARRAY;
if ((flags & FLAG_BRIDGES) != 0) {
int bridgeCount = (Integer) args[argIndex++];
bridges = new MethodType[bridgeCount];
System.arraycopy(args, argIndex, bridges, 0, bridgeCount);
argIndex += bridgeCount;
int altMethodCount = extractArg(args, argIndex++, Integer.class);
if (altMethodCount < 0) {
throw new IllegalArgumentException("negative argument count");
}
if (altMethodCount > 0) {
altMethods = extractArgs(args, argIndex, MethodType.class, altMethodCount);
argIndex += altMethodCount;
}
}
if (argIndex < args.length) {
throw new IllegalArgumentException("too many arguments");
}
else
bridges = EMPTY_MT_ARRAY;
boolean isSerializable = ((flags & FLAG_SERIALIZABLE) != 0);
if (isSerializable) {
boolean foundSerializableSupertype = Serializable.class.isAssignableFrom(invokedType.returnType());
for (Class<?> c : markerInterfaces)
boolean foundSerializableSupertype = Serializable.class.isAssignableFrom(factoryType.returnType());
for (Class<?> c : altInterfaces)
foundSerializableSupertype |= Serializable.class.isAssignableFrom(c);
if (!foundSerializableSupertype) {
markerInterfaces = Arrays.copyOf(markerInterfaces, markerInterfaces.length + 1);
markerInterfaces[markerInterfaces.length-1] = Serializable.class;
altInterfaces = Arrays.copyOf(altInterfaces, altInterfaces.length + 1);
altInterfaces[altInterfaces.length-1] = Serializable.class;
}
}
AbstractValidatingLambdaMetafactory mf
= new InnerClassLambdaMetafactory(caller, invokedType,
invokedName, samMethodType,
implMethod,
instantiatedMethodType,
= new InnerClassLambdaMetafactory(caller,
factoryType,
interfaceMethodName,
interfaceMethodType,
implementation,
dynamicMethodType,
isSerializable,
markerInterfaces, bridges);
altInterfaces,
altMethods);
mf.validateMetafactoryArgs();
return mf.buildCallSite();
}
private static <T> T extractArg(Object[] args, int index, Class<T> type) {
if (index >= args.length) {
throw new IllegalArgumentException("missing argument");
}
Object result = Objects.requireNonNull(args[index]);
if (!type.isInstance(result)) {
throw new IllegalArgumentException("argument has wrong type");
}
return type.cast(result);
}
private static <T> T[] extractArgs(Object[] args, int index, Class<T> type, int count) {
@SuppressWarnings("unchecked")
T[] result = (T[]) Array.newInstance(type, count);
for (int i = 0; i < count; i++) {
result[i] = extractArg(args, index + i, type);
}
return result;
}
}

View file

@ -38,19 +38,19 @@ final class LambdaProxyClassArchive {
}
private static native void addToArchive(Class<?> caller,
String invokedName,
MethodType invokedType,
MethodType samMethodType,
MemberName implMethod,
MethodType instantiatedMethodType,
String interfaceMethodName,
MethodType factoryType,
MethodType interfaceMethodType,
MemberName implementationMember,
MethodType dynamicMethodType,
Class<?> lambdaProxyClass);
private static native Class<?> findFromArchive(Class<?> caller,
String invokedName,
MethodType invokedType,
MethodType samMethodType,
MemberName implMethod,
MethodType instantiatedMethodType);
String interfaceMethodName,
MethodType factoryType,
MethodType interfaceMethodType,
MemberName implementationMember,
MethodType dynamicMethodType);
/**
* Registers the lambdaProxyClass into CDS archive.
@ -62,22 +62,22 @@ final class LambdaProxyClassArchive {
* loaded by a built-in class loader.
*/
static boolean register(Class<?> caller,
String invokedName,
MethodType invokedType,
MethodType samMethodType,
MethodHandle implMethod,
MethodType instantiatedMethodType,
String interfaceMethodName,
MethodType factoryType,
MethodType interfaceMethodType,
MethodHandle implementation,
MethodType dynamicMethodType,
boolean isSerializable,
Class<?>[] markerInterfaces,
MethodType[] additionalBridges,
Class<?>[] altInterfaces,
MethodType[] altMethods,
Class<?> lambdaProxyClass) {
if (!CDS.isDumpingArchive())
throw new IllegalStateException("should only register lambda proxy class at dump time");
if (loadedByBuiltinLoader(caller) &&
!isSerializable && markerInterfaces.length == 0 && additionalBridges.length == 0) {
addToArchive(caller, invokedName, invokedType, samMethodType,
implMethod.internalMemberName(), instantiatedMethodType,
!isSerializable && altInterfaces.length == 0 && altMethods.length == 0) {
addToArchive(caller, interfaceMethodName, factoryType, interfaceMethodType,
implementation.internalMemberName(), dynamicMethodType,
lambdaProxyClass);
return true;
}
@ -93,22 +93,22 @@ final class LambdaProxyClassArchive {
* loaded by a built-in class loader.
*/
static Class<?> find(Class<?> caller,
String invokedName,
MethodType invokedType,
MethodType samMethodType,
MethodHandle implMethod,
MethodType instantiatedMethodType,
String interfaceMethodName,
MethodType factoryType,
MethodType interfaceMethodType,
MethodHandle implementation,
MethodType dynamicMethodType,
boolean isSerializable,
Class<?>[] markerInterfaces,
MethodType[] additionalBridges) {
Class<?>[] altInterfaces,
MethodType[] altMethods) {
if (CDS.isDumpingArchive())
throw new IllegalStateException("cannot load class from CDS archive at dump time");
if (!loadedByBuiltinLoader(caller) ||
!CDS.isSharingEnabled() || isSerializable || markerInterfaces.length > 0 || additionalBridges.length > 0)
!CDS.isSharingEnabled() || isSerializable || altInterfaces.length > 0 || altMethods.length > 0)
return null;
return findFromArchive(caller, invokedName, invokedType, samMethodType,
implMethod.internalMemberName(), instantiatedMethodType);
return findFromArchive(caller, interfaceMethodName, factoryType, interfaceMethodType,
implementation.internalMemberName(), dynamicMethodType);
}
}