Imported Upstream version 3.6.0

Former-commit-id: da6be194a6b1221998fc28233f2503bd61dd9d14
This commit is contained in:
Jo Shields
2014-08-13 10:39:27 +01:00
commit a575963da9
50588 changed files with 8155799 additions and 0 deletions

View File

@@ -0,0 +1,41 @@
/*
* Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package sun.reflect;
import java.lang.annotation.*;
import static java.lang.annotation.ElementType.*;
/**
* A method annotated @CallerSensitive is sensitive to its calling class,
* via {@link sun.reflect.Reflection#getCallerClass Reflection.getCallerClass},
* or via some equivalent.
*
* @author John R. Rose
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({METHOD})
public @interface CallerSensitive {
}

View File

@@ -0,0 +1,40 @@
/*
* Copyright (c) 2001, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package sun.reflect;
import java.lang.reflect.InvocationTargetException;
/** This interface provides the declaration for
java.lang.reflect.Method.invoke(). Each Method object is
configured with a (possibly dynamically-generated) class which
implements this interface.
*/
public interface MethodAccessor {
/** Matches specification in {@link java.lang.reflect.Method} */
public Object invoke(Object obj, Object[] args, ikvm.internal.CallerID callerID)
throws IllegalArgumentException, InvocationTargetException;
}

View File

@@ -0,0 +1,355 @@
/*
* Copyright (c) 2001, 2006, 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.
*/
/*IKVM*/
/* Modified for IKVM by Jeroen Frijters
*
* May 27, 2007 Added support for @ikvm.lang.Internal access modifier
*
*/
/*IKVM*/
package sun.reflect;
import java.lang.reflect.*;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
/** Common utility routines used by both java.lang and
java.lang.reflect */
public class Reflection {
/** Used to filter out fields and methods from certain classes from public
view, where they are sensitive or they may contain VM-internal objects.
These Maps are updated very rarely. Rather than synchronize on
each access, we use copy-on-write */
private static volatile Map<Class,String[]> fieldFilterMap;
private static volatile Map<Class,String[]> methodFilterMap;
static {
Map<Class,String[]> map = new HashMap<Class,String[]>();
map.put(Reflection.class,
new String[] {"fieldFilterMap", "methodFilterMap"});
map.put(System.class, new String[] {"security"});
fieldFilterMap = map;
methodFilterMap = new HashMap<Class,String[]>();
// [IKVM] to avoid initialization order issues, we actually add
// Unsafe.getUnsafe() here, instead of in Unsafe's class initializer
methodFilterMap.put(sun.misc.Unsafe.class, new String[] {"getUnsafe"});
}
/** Returns the class of the caller of the method calling this method,
ignoring frames associated with java.lang.reflect.Method.invoke()
and its implementation. */
@CallerSensitive
public static Class getCallerClass() {
return getCallerClass(2);
}
/** Returns the class of the method <code>realFramesToSkip</code>
frames up the stack (zero-based), ignoring frames associated
with java.lang.reflect.Method.invoke() and its implementation.
The first frame is that associated with this method, so
<code>getCallerClass(0)</code> returns the Class object for
sun.reflect.Reflection. Frames associated with
java.lang.reflect.Method.invoke() and its implementation are
completely ignored and do not count toward the number of "real"
frames skipped. */
@CallerSensitive
public static native Class getCallerClass(int realFramesToSkip);
/** Retrieves the access flags written to the class file. For
inner classes these flags may differ from those returned by
Class.getModifiers(), which searches the InnerClasses
attribute to find the source-level access flags. This is used
instead of Class.getModifiers() for run-time access checks due
to compatibility reasons; see 4471811. Only the values of the
low 13 bits (i.e., a mask of 0x1FFF) are guaranteed to be
valid. */
private static native int getClassAccessFlags(Class c);
/** A quick "fast-path" check to try to avoid getCallerClass()
calls. */
public static boolean quickCheckMemberAccess(Class memberClass,
int modifiers)
{
return Modifier.isPublic(getClassAccessFlags(memberClass) & modifiers);
}
public static void ensureMemberAccess(Class currentClass,
Class memberClass,
Object target,
int modifiers)
throws IllegalAccessException
{
if (currentClass == null || memberClass == null) {
throw new InternalError();
}
if (!verifyMemberAccess(currentClass, memberClass, target, modifiers)) {
throw new IllegalAccessException("Class " + currentClass.getName() +
" can not access a member of class " +
memberClass.getName() +
" with modifiers \"" +
Modifier.toString(modifiers) +
"\"");
}
}
/*IKVM*/
private static native boolean checkInternalAccess(Class currentClass, Class memberClass);
public static boolean verifyMemberAccess(Class currentClass,
// Declaring class of field
// or method
Class memberClass,
// May be NULL in case of statics
Object target,
int modifiers)
{
// Verify that currentClass can access a field, method, or
// constructor of memberClass, where that member's access bits are
// "modifiers".
boolean gotIsSameClassPackage = false;
boolean isSameClassPackage = false;
if (currentClass == memberClass) {
// Always succeeds
return true;
}
if (!Modifier.isPublic(getClassAccessFlags(memberClass))) {
isSameClassPackage = isSameClassPackage(currentClass, memberClass);
gotIsSameClassPackage = true;
/*IKVM*/
if (!isSameClassPackage && !checkInternalAccess(currentClass, memberClass)) {
return false;
}
}
// At this point we know that currentClass can access memberClass.
if (Modifier.isPublic(modifiers)) {
return true;
}
/*IKVM*/
// Is the member @ikvm.lang.Internal accessible?
if ((modifiers & 0x40000000) != 0) {
return currentClass.getClassLoader() == memberClass.getClassLoader();
}
boolean successSoFar = false;
if (Modifier.isProtected(modifiers)) {
// See if currentClass is a subclass of memberClass
if (isSubclassOf(currentClass, memberClass)) {
successSoFar = true;
}
}
if (!successSoFar && !Modifier.isPrivate(modifiers)) {
if (!gotIsSameClassPackage) {
isSameClassPackage = isSameClassPackage(currentClass,
memberClass);
gotIsSameClassPackage = true;
}
if (isSameClassPackage) {
successSoFar = true;
}
}
if (!successSoFar) {
return false;
}
if (Modifier.isProtected(modifiers)) {
// Additional test for protected members: JLS 6.6.2
Class targetClass = (target == null ? memberClass : target.getClass());
if (targetClass != currentClass) {
if (!gotIsSameClassPackage) {
isSameClassPackage = isSameClassPackage(currentClass, memberClass);
gotIsSameClassPackage = true;
}
if (!isSameClassPackage) {
if (!isSubclassOf(targetClass, currentClass)) {
return false;
}
}
}
}
return true;
}
private static boolean isSameClassPackage(Class c1, Class c2) {
return isSameClassPackage(c1.getClassLoader(), c1.getName(),
c2.getClassLoader(), c2.getName());
}
/** Returns true if two classes are in the same package; classloader
and classname information is enough to determine a class's package */
private static boolean isSameClassPackage(ClassLoader loader1, String name1,
ClassLoader loader2, String name2)
{
if (loader1 != loader2) {
return false;
} else {
int lastDot1 = name1.lastIndexOf('.');
int lastDot2 = name2.lastIndexOf('.');
if ((lastDot1 == -1) || (lastDot2 == -1)) {
// One of the two doesn't have a package. Only return true
// if the other one also doesn't have a package.
return (lastDot1 == lastDot2);
} else {
int idx1 = 0;
int idx2 = 0;
// Skip over '['s
if (name1.charAt(idx1) == '[') {
do {
idx1++;
} while (name1.charAt(idx1) == '[');
if (name1.charAt(idx1) != 'L') {
// Something is terribly wrong. Shouldn't be here.
throw new InternalError("Illegal class name " + name1);
}
}
if (name2.charAt(idx2) == '[') {
do {
idx2++;
} while (name2.charAt(idx2) == '[');
if (name2.charAt(idx2) != 'L') {
// Something is terribly wrong. Shouldn't be here.
throw new InternalError("Illegal class name " + name2);
}
}
// Check that package part is identical
int length1 = lastDot1 - idx1;
int length2 = lastDot2 - idx2;
if (length1 != length2) {
return false;
}
return name1.regionMatches(false, idx1, name2, idx2, length1);
}
}
}
static boolean isSubclassOf(Class queryClass,
Class ofClass)
{
while (queryClass != null) {
if (queryClass == ofClass) {
return true;
}
queryClass = queryClass.getSuperclass();
}
return false;
}
// fieldNames must contain only interned Strings
public static synchronized void registerFieldsToFilter(Class containingClass,
String ... fieldNames) {
fieldFilterMap =
registerFilter(fieldFilterMap, containingClass, fieldNames);
}
// methodNames must contain only interned Strings
public static synchronized void registerMethodsToFilter(Class containingClass,
String ... methodNames) {
methodFilterMap =
registerFilter(methodFilterMap, containingClass, methodNames);
}
private static Map<Class,String[]> registerFilter(Map<Class,String[]> map,
Class containingClass, String ... names) {
if (map.get(containingClass) != null) {
throw new IllegalArgumentException
("Filter already registered: " + containingClass);
}
map = new HashMap<Class,String[]>(map);
map.put(containingClass, names);
return map;
}
public static Field[] filterFields(Class containingClass,
Field[] fields) {
if (fieldFilterMap == null) {
// Bootstrapping
return fields;
}
return (Field[])filter(fields, fieldFilterMap.get(containingClass));
}
public static Method[] filterMethods(Class containingClass, Method[] methods) {
if (methodFilterMap == null) {
// Bootstrapping
return methods;
}
return (Method[])filter(methods, methodFilterMap.get(containingClass));
}
private static Member[] filter(Member[] members, String[] filteredNames) {
if ((filteredNames == null) || (members.length == 0)) {
return members;
}
int numNewMembers = 0;
for (Member member : members) {
boolean shouldSkip = false;
for (String filteredName : filteredNames) {
if (member.getName() == filteredName) {
shouldSkip = true;
break;
}
}
if (!shouldSkip) {
++numNewMembers;
}
}
Member[] newMembers =
(Member[])Array.newInstance(members[0].getClass(), numNewMembers);
int destIdx = 0;
for (Member member : members) {
boolean shouldSkip = false;
for (String filteredName : filteredNames) {
if (member.getName() == filteredName) {
shouldSkip = true;
break;
}
}
if (!shouldSkip) {
newMembers[destIdx++] = member;
}
}
return newMembers;
}
}

View File

@@ -0,0 +1,310 @@
/*
* Copyright (c) 2001, 2008, 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.
*/
/*IKVM*/
/*
* May 29, 2007 Modified for IKVM.NET by Jeroen Frijters
*
*/
package sun.reflect;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Constructor;
import java.lang.reflect.Modifier;
import java.security.AccessController;
import java.security.Permission;
import java.security.PrivilegedAction;
/** <P> The master factory for all reflective objects, both those in
java.lang.reflect (Fields, Methods, Constructors) as well as their
delegates (FieldAccessors, MethodAccessors, ConstructorAccessors).
</P>
<P> The methods in this class are extremely unsafe and can cause
subversion of both the language and the verifier. For this reason,
they are all instance methods, and access to the constructor of
this factory is guarded by a security check, in similar style to
{@link sun.misc.Unsafe}. </P>
*/
public class ReflectionFactory {
private static Permission reflectionFactoryAccessPerm
= new RuntimePermission("reflectionFactoryAccess");
private static ReflectionFactory soleInstance = new ReflectionFactory();
// Provides access to package-private mechanisms in java.lang.reflect
private static volatile LangReflectAccess langReflectAccess;
private ReflectionFactory() {
}
/**
* A convenience class for acquiring the capability to instantiate
* reflective objects. Use this instead of a raw call to {@link
* #getReflectionFactory} in order to avoid being limited by the
* permissions of your callers.
*
* <p>An instance of this class can be used as the argument of
* <code>AccessController.doPrivileged</code>.
*/
public static final class GetReflectionFactoryAction
implements PrivilegedAction<ReflectionFactory> {
public ReflectionFactory run() {
return getReflectionFactory();
}
}
/**
* Provides the caller with the capability to instantiate reflective
* objects.
*
* <p> First, if there is a security manager, its
* <code>checkPermission</code> method is called with a {@link
* java.lang.RuntimePermission} with target
* <code>"reflectionFactoryAccess"</code>. This may result in a
* security exception.
*
* <p> The returned <code>ReflectionFactory</code> object should be
* carefully guarded by the caller, since it can be used to read and
* write private data and invoke private methods, as well as to load
* unverified bytecodes. It must never be passed to untrusted code.
*
* @exception SecurityException if a security manager exists and its
* <code>checkPermission</code> method doesn't allow
* access to the RuntimePermission "reflectionFactoryAccess". */
public static ReflectionFactory getReflectionFactory() {
SecurityManager security = System.getSecurityManager();
if (security != null) {
// TO DO: security.checkReflectionFactoryAccess();
security.checkPermission(reflectionFactoryAccessPerm);
}
return soleInstance;
}
//--------------------------------------------------------------------------
//
// Routines used by java.lang.reflect
//
//
/** Called only by java.lang.reflect.Modifier's static initializer */
public void setLangReflectAccess(LangReflectAccess access) {
langReflectAccess = access;
}
/**
* Note: this routine can cause the declaring class for the field
* be initialized and therefore must not be called until the
* first get/set of this field.
* @param field the field
* @param override true if caller has overridden aaccessibility
*/
public native FieldAccessor newFieldAccessor(Field field, boolean override);
public native MethodAccessor newMethodAccessor(Method method);
private native ConstructorAccessor newConstructorAccessor0(Constructor c);
public ConstructorAccessor newConstructorAccessor(Constructor c) {
Class<?> declaringClass = c.getDeclaringClass();
if (Modifier.isAbstract(declaringClass.getModifiers())) {
return new InstantiationExceptionConstructorAccessorImpl(null);
}
if (declaringClass == Class.class) {
return new InstantiationExceptionConstructorAccessorImpl
("Can not instantiate java.lang.Class");
}
return newConstructorAccessor0(c);
}
//--------------------------------------------------------------------------
//
// Routines used by java.lang
//
//
/** Creates a new java.lang.reflect.Field. Access checks as per
java.lang.reflect.AccessibleObject are not overridden. */
public Field newField(Class<?> declaringClass,
String name,
Class<?> type,
int modifiers,
int slot,
String signature,
byte[] annotations)
{
return langReflectAccess().newField(declaringClass,
name,
type,
modifiers,
slot,
signature,
annotations);
}
/** Creates a new java.lang.reflect.Method. Access checks as per
java.lang.reflect.AccessibleObject are not overridden. */
public Method newMethod(Class<?> declaringClass,
String name,
Class<?>[] parameterTypes,
Class<?> returnType,
Class<?>[] checkedExceptions,
int modifiers,
int slot,
String signature,
byte[] annotations,
byte[] parameterAnnotations,
byte[] annotationDefault)
{
return langReflectAccess().newMethod(declaringClass,
name,
parameterTypes,
returnType,
checkedExceptions,
modifiers,
slot,
signature,
annotations,
parameterAnnotations,
annotationDefault);
}
/** Creates a new java.lang.reflect.Constructor. Access checks as
per java.lang.reflect.AccessibleObject are not overridden. */
public Constructor newConstructor(Class<?> declaringClass,
Class<?>[] parameterTypes,
Class<?>[] checkedExceptions,
int modifiers,
int slot,
String signature,
byte[] annotations,
byte[] parameterAnnotations)
{
return langReflectAccess().newConstructor(declaringClass,
parameterTypes,
checkedExceptions,
modifiers,
slot,
signature,
annotations,
parameterAnnotations);
}
/** Gets the MethodAccessor object for a java.lang.reflect.Method */
public MethodAccessor getMethodAccessor(Method m) {
return langReflectAccess().getMethodAccessor(m);
}
/** Sets the MethodAccessor object for a java.lang.reflect.Method */
public void setMethodAccessor(Method m, MethodAccessor accessor) {
langReflectAccess().setMethodAccessor(m, accessor);
}
/** Gets the ConstructorAccessor object for a
java.lang.reflect.Constructor */
public ConstructorAccessor getConstructorAccessor(Constructor c) {
return langReflectAccess().getConstructorAccessor(c);
}
/** Sets the ConstructorAccessor object for a
java.lang.reflect.Constructor */
public void setConstructorAccessor(Constructor c,
ConstructorAccessor accessor)
{
langReflectAccess().setConstructorAccessor(c, accessor);
}
/** Makes a copy of the passed method. The returned method is a
"child" of the passed one; see the comments in Method.java for
details. */
public Method copyMethod(Method arg) {
return langReflectAccess().copyMethod(arg);
}
/** Makes a copy of the passed field. The returned field is a
"child" of the passed one; see the comments in Field.java for
details. */
public Field copyField(Field arg) {
return langReflectAccess().copyField(arg);
}
/** Makes a copy of the passed constructor. The returned
constructor is a "child" of the passed one; see the comments
in Constructor.java for details. */
public <T> Constructor<T> copyConstructor(Constructor<T> arg) {
return langReflectAccess().copyConstructor(arg);
}
//--------------------------------------------------------------------------
//
// Routines used by serialization
//
//
private static native ConstructorAccessor newConstructorAccessorForSerialization(Class classToInstantiate, Constructor constructorToCall);
public Constructor newConstructorForSerialization
(Class<?> classToInstantiate, Constructor constructorToCall)
{
// Fast path
if (constructorToCall.getDeclaringClass() == classToInstantiate) {
return constructorToCall;
}
ConstructorAccessor acc = newConstructorAccessorForSerialization(classToInstantiate, constructorToCall);
Constructor c = newConstructor(constructorToCall.getDeclaringClass(),
constructorToCall.getParameterTypes(),
constructorToCall.getExceptionTypes(),
constructorToCall.getModifiers(),
langReflectAccess().
getConstructorSlot(constructorToCall),
langReflectAccess().
getConstructorSignature(constructorToCall),
langReflectAccess().
getConstructorAnnotations(constructorToCall),
langReflectAccess().
getConstructorParameterAnnotations(constructorToCall));
setConstructorAccessor(c, acc);
return c;
}
//--------------------------------------------------------------------------
//
// Internals only below this point
//
private static LangReflectAccess langReflectAccess() {
if (langReflectAccess == null) {
// Call a static method to get class java.lang.reflect.Modifier
// initialized. Its static initializer will cause
// setLangReflectAccess() to be called from the context of the
// java.lang.reflect package.
Modifier.isPublic(Modifier.PUBLIC);
}
return langReflectAccess;
}
}

View File

@@ -0,0 +1,252 @@
/*
* Copyright (c) 2005, 2013 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package sun.reflect.misc;
import java.lang.reflect.Modifier;
import java.lang.reflect.Proxy;
import sun.reflect.Reflection;
public final class ReflectUtil {
private ReflectUtil() {
}
public static Class forName(String name)
throws ClassNotFoundException {
checkPackageAccess(name);
return Class.forName(name);
}
public static Object newInstance(Class cls)
throws InstantiationException, IllegalAccessException {
checkPackageAccess(cls);
return cls.newInstance();
}
/*
* Reflection.ensureMemberAccess is overly-restrictive
* due to a bug. We awkwardly work around it for now.
*/
public static void ensureMemberAccess(Class currentClass,
Class memberClass,
Object target,
int modifiers)
throws IllegalAccessException
{
if (target == null && Modifier.isProtected(modifiers)) {
int mods = modifiers;
mods = mods & (~Modifier.PROTECTED);
mods = mods | Modifier.PUBLIC;
/*
* See if we fail because of class modifiers
*/
Reflection.ensureMemberAccess(currentClass,
memberClass,
target,
mods);
try {
/*
* We're still here so class access was ok.
* Now try with default field access.
*/
mods = mods & (~Modifier.PUBLIC);
Reflection.ensureMemberAccess(currentClass,
memberClass,
target,
mods);
/*
* We're still here so access is ok without
* checking for protected.
*/
return;
} catch (IllegalAccessException e) {
/*
* Access failed but we're 'protected' so
* if the test below succeeds then we're ok.
*/
if (isSubclassOf(currentClass, memberClass)) {
return;
} else {
throw e;
}
}
} else {
Reflection.ensureMemberAccess(currentClass,
memberClass,
target,
modifiers);
}
}
private static boolean isSubclassOf(Class queryClass,
Class ofClass)
{
while (queryClass != null) {
if (queryClass == ofClass) {
return true;
}
queryClass = queryClass.getSuperclass();
}
return false;
}
/**
* Checks package access on the given class.
*
* If it is a {@link Proxy#isProxyClass(java.lang.Class)} that implements
* a non-public interface (i.e. may be in a non-restricted package),
* also check the package access on the proxy interfaces.
*/
public static void checkPackageAccess(Class<?> clazz) {
checkPackageAccess(clazz.getName());
if (isNonPublicProxyClass(clazz)) {
checkProxyPackageAccess(clazz);
}
}
/**
* Checks package access on the given classname.
* This method is typically called when the Class instance is not
* available and the caller attempts to load a class on behalf
* the true caller (application).
*/
public static void checkPackageAccess(String name) {
SecurityManager s = System.getSecurityManager();
if (s != null) {
String cname = name.replace('/', '.');
if (cname.startsWith("[")) {
int b = cname.lastIndexOf('[') + 2;
if (b > 1 && b < cname.length()) {
cname = cname.substring(b);
}
}
int i = cname.lastIndexOf('.');
if (i != -1) {
s.checkPackageAccess(cname.substring(0, i));
}
}
}
public static boolean isPackageAccessible(Class clazz) {
try {
checkPackageAccess(clazz);
} catch (SecurityException e) {
return false;
}
return true;
}
// Returns true if p is an ancestor of cl i.e. class loader 'p' can
// be found in the cl's delegation chain
private static boolean isAncestor(ClassLoader p, ClassLoader cl) {
ClassLoader acl = cl;
do {
acl = acl.getParent();
if (p == acl) {
return true;
}
} while (acl != null);
return false;
}
/**
* Returns true if package access check is needed for reflective
* access from a class loader 'from' to classes or members in
* a class defined by class loader 'to'. This method returns true
* if 'from' is not the same as or an ancestor of 'to'. All code
* in a system domain are granted with all permission and so this
* method returns false if 'from' class loader is a class loader
* loading system classes. On the other hand, if a class loader
* attempts to access system domain classes, it requires package
* access check and this method will return true.
*/
public static boolean needsPackageAccessCheck(ClassLoader from, ClassLoader to) {
if (from == null || from == to)
return false;
if (to == null)
return true;
return !isAncestor(from, to);
}
/**
* Check package access on the proxy interfaces that the given proxy class
* implements.
*
* @param clazz Proxy class object
*/
public static void checkProxyPackageAccess(Class<?> clazz) {
SecurityManager s = System.getSecurityManager();
if (s != null) {
// check proxy interfaces if the given class is a proxy class
if (Proxy.isProxyClass(clazz)) {
for (Class<?> intf : clazz.getInterfaces()) {
checkPackageAccess(intf);
}
}
}
}
/**
* Access check on the interfaces that a proxy class implements and throw
* {@code SecurityException} if it accesses a restricted package from
* the caller's class loader.
*
* @param ccl the caller's class loader
* @param interfaces the list of interfaces that a proxy class implements
*/
public static void checkProxyPackageAccess(ClassLoader ccl,
Class<?>... interfaces)
{
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
for (Class<?> intf : interfaces) {
ClassLoader cl = intf.getClassLoader();
if (needsPackageAccessCheck(ccl, cl)) {
checkPackageAccess(intf);
}
}
}
}
public static final String PROXY_PACKAGE = "com.sun.proxy";
/**
* Test if the given class is a proxy class that implements
* non-public interface. Such proxy class may be in a non-restricted
* package that bypasses checkPackageAccess.
*/
public static boolean isNonPublicProxyClass(Class<?> cls) {
String name = cls.getName();
int i = name.lastIndexOf('.');
String pkg = (i != -1) ? name.substring(0, i) : "";
return Proxy.isProxyClass(cls) && !pkg.equals(PROXY_PACKAGE);
}
}