sun.reflect.CallerSensitive Java Examples

The following examples show how to use sun.reflect.CallerSensitive. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SerialJavaObject.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Returns an array of <code>Field</code> objects that contains each
 * field of the object that this helper class is serializing.
 *
 * @return an array of <code>Field</code> objects
 * @throws SerialException if an error is encountered accessing
 * the serialized object
 * @throws  SecurityException  If a security manager, <i>s</i>, is present
 * and the caller's class loader is not the same as or an
 * ancestor of the class loader for the class of the
 * {@linkplain #getObject object} being serialized
 * and invocation of {@link SecurityManager#checkPackageAccess
 * s.checkPackageAccess()} denies access to the package
 * of that class.
 * @see Class#getFields
 */
@CallerSensitive
public Field[] getFields() throws SerialException {
    if (fields != null) {
        Class<?> c = this.obj.getClass();
        SecurityManager sm = System.getSecurityManager();
        if (sm != null) {
            /*
             * Check if the caller is allowed to access the specified class's package.
             * If access is denied, throw a SecurityException.
             */
            Class<?> caller = sun.reflect.Reflection.getCallerClass();
            if (ReflectUtil.needsPackageAccessCheck(caller.getClassLoader(),
                                                    c.getClassLoader())) {
                ReflectUtil.checkPackageAccess(c);
            }
        }
        return c.getFields();
    } else {
        throw new SerialException("SerialJavaObject does not contain" +
            " a serialized object instance");
    }
}
 
Example #2
Source File: SerialJavaObject.java    From jdk1.8-source-analysis with Apache License 2.0 6 votes vote down vote up
/**
 * Returns an array of <code>Field</code> objects that contains each
 * field of the object that this helper class is serializing.
 *
 * @return an array of <code>Field</code> objects
 * @throws SerialException if an error is encountered accessing
 * the serialized object
 * @throws  SecurityException  If a security manager, <i>s</i>, is present
 * and the caller's class loader is not the same as or an
 * ancestor of the class loader for the class of the
 * {@linkplain #getObject object} being serialized
 * and invocation of {@link SecurityManager#checkPackageAccess
 * s.checkPackageAccess()} denies access to the package
 * of that class.
 * @see Class#getFields
 */
@CallerSensitive
public Field[] getFields() throws SerialException {
    if (fields != null) {
        Class<?> c = this.obj.getClass();
        SecurityManager sm = System.getSecurityManager();
        if (sm != null) {
            /*
             * Check if the caller is allowed to access the specified class's package.
             * If access is denied, throw a SecurityException.
             */
            Class<?> caller = sun.reflect.Reflection.getCallerClass();
            if (ReflectUtil.needsPackageAccessCheck(caller.getClassLoader(),
                                                    c.getClassLoader())) {
                ReflectUtil.checkPackageAccess(c);
            }
        }
        return c.getFields();
    } else {
        throw new SerialException("SerialJavaObject does not contain" +
            " a serialized object instance");
    }
}
 
Example #3
Source File: DriverManager.java    From jdk1.8-source-analysis with Apache License 2.0 6 votes vote down vote up
/**
 * Retrieves an Enumeration with all of the currently loaded JDBC drivers
 * to which the current caller has access.
 *
 * <P><B>Note:</B> The classname of a driver can be found using
 * <CODE>d.getClass().getName()</CODE>
 *
 * @return the list of JDBC Drivers loaded by the caller's class loader
 */
@CallerSensitive
public static java.util.Enumeration<Driver> getDrivers() {
    java.util.Vector<Driver> result = new java.util.Vector<>();

    Class<?> callerClass = Reflection.getCallerClass();

    // Walk through the loaded registeredDrivers.
    for(DriverInfo aDriver : registeredDrivers) {
        // If the caller does not have permission to load the driver then
        // skip it.
        if(isDriverAllowed(aDriver.driver, callerClass)) {
            result.addElement(aDriver.driver);
        } else {
            println("    skipping: " + aDriver.getClass().getName());
        }
    }
    return (result.elements());
}
 
Example #4
Source File: GetCallerClassTest.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
private static void ensureAnnotationPresent(Class<?> c, String name, boolean cs)
    throws NoSuchMethodException
{
    Method m = c.getDeclaredMethod(name);
    if (!m.isAnnotationPresent(CallerSensitive.class)) {
        throw new RuntimeException("@CallerSensitive not present in method " + m);
    }
    if (Reflection.isCallerSensitive(m) != cs) {
        throw new RuntimeException("Unexpected: isCallerSensitive returns " +
            Reflection.isCallerSensitive(m));
    }
}
 
Example #5
Source File: Class.java    From jdk1.8-source-analysis with Apache License 2.0 5 votes vote down vote up
/**
 * Returns an array containing {@code Class} objects representing all
 * the public classes and interfaces that are members of the class
 * represented by this {@code Class} object.  This includes public
 * class and interface members inherited from superclasses and public class
 * and interface members declared by the class.  This method returns an
 * array of length 0 if this {@code Class} object has no public member
 * classes or interfaces.  This method also returns an array of length 0 if
 * this {@code Class} object represents a primitive type, an array
 * class, or void.
 *
 * @return the array of {@code Class} objects representing the public
 *         members of this class
 * @throws SecurityException
 *         If a security manager, <i>s</i>, is present and
 *         the caller's class loader is not the same as or an
 *         ancestor of the class loader for the current class and
 *         invocation of {@link SecurityManager#checkPackageAccess
 *         s.checkPackageAccess()} denies access to the package
 *         of this class.
 *
 * @since JDK1.1
 */
@CallerSensitive
public Class<?>[] getClasses() {
    checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), false);

    // Privileged so this implementation can look at DECLARED classes,
    // something the caller might not have privilege to do.  The code here
    // is allowed to look at DECLARED classes because (1) it does not hand
    // out anything other than public members and (2) public member access
    // has already been ok'd by the SecurityManager.

    return java.security.AccessController.doPrivileged(
        new java.security.PrivilegedAction<Class<?>[]>() {
            public Class<?>[] run() {
                List<Class<?>> list = new ArrayList<>();
                Class<?> currentClass = Class.this;
                while (currentClass != null) {
                    Class<?>[] members = currentClass.getDeclaredClasses();
                    for (int i = 0; i < members.length; i++) {
                        if (Modifier.isPublic(members[i].getModifiers())) {
                            list.add(members[i]);
                        }
                    }
                    currentClass = currentClass.getSuperclass();
                }
                return list.toArray(new Class<?>[0]);
            }
        });
}
 
Example #6
Source File: MethodHandleImpl.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
@CallerSensitive
private static boolean checkCallerClass(Class<?> expected, Class<?> expected2) {
    // This method is called via MH_checkCallerClass and so it's
    // correct to ask for the immediate caller here.
    Class<?> actual = Reflection.getCallerClass();
    if (actual != expected && actual != expected2)
        throw new InternalError("found "+actual.getName()+", expected "+expected.getName()
                                +(expected == expected2 ? "" : ", or else "+expected2.getName()));
    return true;
}
 
Example #7
Source File: DriverManager.java    From jdk1.8-source-analysis with Apache License 2.0 5 votes vote down vote up
/**
 * Attempts to locate a driver that understands the given URL.
 * The <code>DriverManager</code> attempts to select an appropriate driver from
 * the set of registered JDBC drivers.
 *
 * @param url a database URL of the form
 *     <code>jdbc:<em>subprotocol</em>:<em>subname</em></code>
 * @return a <code>Driver</code> object representing a driver
 * that can connect to the given URL
 * @exception SQLException if a database access error occurs
 */
@CallerSensitive
public static Driver getDriver(String url)
    throws SQLException {

    println("DriverManager.getDriver(\"" + url + "\")");

    Class<?> callerClass = Reflection.getCallerClass();

    // Walk through the loaded registeredDrivers attempting to locate someone
    // who understands the given URL.
    for (DriverInfo aDriver : registeredDrivers) {
        // If the caller does not have permission to load the driver then
        // skip it.
        if(isDriverAllowed(aDriver.driver, callerClass)) {
            try {
                if(aDriver.driver.acceptsURL(url)) {
                    // Success!
                    println("getDriver returning " + aDriver.driver.getClass().getName());
                return (aDriver.driver);
                }

            } catch(SQLException sqe) {
                // Drop through and try the next driver.
            }
        } else {
            println("    skipping: " + aDriver.driver.getClass().getName());
        }

    }

    println("getDriver: no suitable driver");
    throw new SQLException("No suitable driver", "08001");
}
 
Example #8
Source File: Class.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Returns an array containing {@code Class} objects representing all
 * the public classes and interfaces that are members of the class
 * represented by this {@code Class} object.  This includes public
 * class and interface members inherited from superclasses and public class
 * and interface members declared by the class.  This method returns an
 * array of length 0 if this {@code Class} object has no public member
 * classes or interfaces.  This method also returns an array of length 0 if
 * this {@code Class} object represents a primitive type, an array
 * class, or void.
 *
 * @return the array of {@code Class} objects representing the public
 *         members of this class
 * @throws SecurityException
 *         If a security manager, <i>s</i>, is present and
 *         the caller's class loader is not the same as or an
 *         ancestor of the class loader for the current class and
 *         invocation of {@link SecurityManager#checkPackageAccess
 *         s.checkPackageAccess()} denies access to the package
 *         of this class.
 *
 * @since JDK1.1
 */
@CallerSensitive
public Class<?>[] getClasses() {
    checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), false);

    // Privileged so this implementation can look at DECLARED classes,
    // something the caller might not have privilege to do.  The code here
    // is allowed to look at DECLARED classes because (1) it does not hand
    // out anything other than public members and (2) public member access
    // has already been ok'd by the SecurityManager.

    return java.security.AccessController.doPrivileged(
        new java.security.PrivilegedAction<Class<?>[]>() {
            public Class<?>[] run() {
                List<Class<?>> list = new ArrayList<>();
                Class<?> currentClass = Class.this;
                while (currentClass != null) {
                    Class<?>[] members = currentClass.getDeclaredClasses();
                    for (int i = 0; i < members.length; i++) {
                        if (Modifier.isPublic(members[i].getModifiers())) {
                            list.add(members[i]);
                        }
                    }
                    currentClass = currentClass.getSuperclass();
                }
                return list.toArray(new Class<?>[0]);
            }
        });
}
 
Example #9
Source File: Class.java    From dragonwell8_jdk with GNU General Public License v2.0 4 votes vote down vote up
/**
 * If this {@code Class} object represents a local or anonymous
 * class within a method, returns a {@link
 * java.lang.reflect.Method Method} object representing the
 * immediately enclosing method of the underlying class. Returns
 * {@code null} otherwise.
 *
 * In particular, this method returns {@code null} if the underlying
 * class is a local or anonymous class immediately enclosed by a type
 * declaration, instance initializer or static initializer.
 *
 * @return the immediately enclosing method of the underlying class, if
 *     that class is a local or anonymous class; otherwise {@code null}.
 *
 * @throws SecurityException
 *         If a security manager, <i>s</i>, is present and any of the
 *         following conditions is met:
 *
 *         <ul>
 *
 *         <li> the caller's class loader is not the same as the
 *         class loader of the enclosing class and invocation of
 *         {@link SecurityManager#checkPermission
 *         s.checkPermission} method with
 *         {@code RuntimePermission("accessDeclaredMembers")}
 *         denies access to the methods within the enclosing class
 *
 *         <li> the caller's class loader is not the same as or an
 *         ancestor of the class loader for the enclosing class and
 *         invocation of {@link SecurityManager#checkPackageAccess
 *         s.checkPackageAccess()} denies access to the package
 *         of the enclosing class
 *
 *         </ul>
 * @since 1.5
 */
@CallerSensitive
public Method getEnclosingMethod() throws SecurityException {
    EnclosingMethodInfo enclosingInfo = getEnclosingMethodInfo();

    if (enclosingInfo == null)
        return null;
    else {
        if (!enclosingInfo.isMethod())
            return null;

        MethodRepository typeInfo = MethodRepository.make(enclosingInfo.getDescriptor(),
                                                          getFactory());
        Class<?>   returnType       = toClass(typeInfo.getReturnType());
        Type []    parameterTypes   = typeInfo.getParameterTypes();
        Class<?>[] parameterClasses = new Class<?>[parameterTypes.length];

        // Convert Types to Classes; returned types *should*
        // be class objects since the methodDescriptor's used
        // don't have generics information
        for(int i = 0; i < parameterClasses.length; i++)
            parameterClasses[i] = toClass(parameterTypes[i]);

        // Perform access check
        Class<?> enclosingCandidate = enclosingInfo.getEnclosingClass();
        enclosingCandidate.checkMemberAccess(Member.DECLARED,
                                             Reflection.getCallerClass(), true);
        /*
         * Loop over all declared methods; match method name,
         * number of and type of parameters, *and* return
         * type.  Matching return type is also necessary
         * because of covariant returns, etc.
         */
        for(Method m: enclosingCandidate.getDeclaredMethods()) {
            if (m.getName().equals(enclosingInfo.getName()) ) {
                Class<?>[] candidateParamClasses = m.getParameterTypes();
                if (candidateParamClasses.length == parameterClasses.length) {
                    boolean matches = true;
                    for(int i = 0; i < candidateParamClasses.length; i++) {
                        if (!candidateParamClasses[i].equals(parameterClasses[i])) {
                            matches = false;
                            break;
                        }
                    }

                    if (matches) { // finally, check return type
                        if (m.getReturnType().equals(returnType) )
                            return m;
                    }
                }
            }
        }

        throw new InternalError("Enclosing method not found");
    }
}
 
Example #10
Source File: AccessController.java    From jdk1.8-source-analysis with Apache License 2.0 4 votes vote down vote up
/**
 * Performs the specified {@code PrivilegedExceptionAction} with
 * privileges enabled and restricted by the specified
 * {@code AccessControlContext} and with a privilege scope limited by
 * specified {@code Permission} arguments.
 *
 * The action is performed with the intersection of the permissions
 * possessed by the caller's protection domain, and those possessed
 * by the domains represented by the specified
 * {@code AccessControlContext}.
 * <p>
 * If the action's {@code run} method throws an (unchecked) exception,
 * it will propagate through this method.
 *
 * <p> This method preserves the current AccessControlContext's
 * DomainCombiner (which may be null) while the action is performed.
 * <p>
 * If a security manager is installed and the specified
 * {@code AccessControlContext} was not created by system code and the
 * caller's {@code ProtectionDomain} has not been granted the
 * {@literal "createAccessControlContext"}
 * {@link java.security.SecurityPermission}, then the action is performed
 * with no permissions.
 *
 * @param <T> the type of the value returned by the
 *                  PrivilegedExceptionAction's {@code run} method.
 * @param action the action to be performed.
 * @param context an <i>access control context</i>
 *                representing the restriction to be applied to the
 *                caller's domain's privileges before performing
 *                the specified action.  If the context is
 *                {@code null},
 *                then no additional restriction is applied.
 * @param perms the {@code Permission} arguments which limit the
 *              scope of the caller's privileges. The number of arguments
 *              is variable.
 *
 * @return the value returned by the action's {@code run} method.
 *
 * @throws PrivilegedActionException if the specified action's
 *         {@code run} method threw a <i>checked</i> exception
 * @throws NullPointerException if action or perms or any element of
 *         perms is {@code null}
 *
 * @see #doPrivileged(PrivilegedAction)
 * @see #doPrivileged(PrivilegedAction,AccessControlContext)
 * @see java.security.DomainCombiner
 *
 * @since 1.8
 */
@CallerSensitive
public static <T> T doPrivilegedWithCombiner(PrivilegedExceptionAction<T> action,
                                             AccessControlContext context,
                                             Permission... perms)
    throws PrivilegedActionException
{
    AccessControlContext parent = getContext();
    DomainCombiner dc = parent.getCombiner();
    if (dc == null && context != null) {
        dc = context.getCombiner();
    }
    if (perms == null) {
        throw new NullPointerException("null permissions parameter");
    }
    Class <?> caller = Reflection.getCallerClass();
    return AccessController.doPrivileged(action, createWrapper(dc, caller,
        parent, context, perms));
}
 
Example #11
Source File: Class.java    From jdk1.8-source-analysis with Apache License 2.0 4 votes vote down vote up
/**
 * Returns the {@code Class} object associated with the class or
 * interface with the given string name, using the given class loader.
 * Given the fully qualified name for a class or interface (in the same
 * format returned by {@code getName}) this method attempts to
 * locate, load, and link the class or interface.  The specified class
 * loader is used to load the class or interface.  If the parameter
 * {@code loader} is null, the class is loaded through the bootstrap
 * class loader.  The class is initialized only if the
 * {@code initialize} parameter is {@code true} and if it has
 * not been initialized earlier.
 *
 * <p> If {@code name} denotes a primitive type or void, an attempt
 * will be made to locate a user-defined class in the unnamed package whose
 * name is {@code name}. Therefore, this method cannot be used to
 * obtain any of the {@code Class} objects representing primitive
 * types or void.
 *
 * <p> If {@code name} denotes an array class, the component type of
 * the array class is loaded but not initialized.
 *
 * <p> For example, in an instance method the expression:
 *
 * <blockquote>
 *  {@code Class.forName("Foo")}
 * </blockquote>
 *
 * is equivalent to:
 *
 * <blockquote>
 *  {@code Class.forName("Foo", true, this.getClass().getClassLoader())}
 * </blockquote>
 *
 * Note that this method throws errors related to loading, linking or
 * initializing as specified in Sections 12.2, 12.3 and 12.4 of <em>The
 * Java Language Specification</em>.
 * Note that this method does not check whether the requested class
 * is accessible to its caller.
 *
 * <p> If the {@code loader} is {@code null}, and a security
 * manager is present, and the caller's class loader is not null, then this
 * method calls the security manager's {@code checkPermission} method
 * with a {@code RuntimePermission("getClassLoader")} permission to
 * ensure it's ok to access the bootstrap class loader.
 *
 * @param name       fully qualified name of the desired class
 * @param initialize if {@code true} the class will be initialized.
 *                   See Section 12.4 of <em>The Java Language Specification</em>.
 * @param loader     class loader from which the class must be loaded
 * @return           class object representing the desired class
 *
 * @exception LinkageError if the linkage fails
 * @exception ExceptionInInitializerError if the initialization provoked
 *            by this method fails
 * @exception ClassNotFoundException if the class cannot be located by
 *            the specified class loader
 *
 * @see       java.lang.Class#forName(String)
 * @see       java.lang.ClassLoader
 * @since     1.2
 */
@CallerSensitive
public static Class<?> forName(String name, boolean initialize,
                               ClassLoader loader)
    throws ClassNotFoundException
{
    Class<?> caller = null;
    SecurityManager sm = System.getSecurityManager();
    if (sm != null) {
        // Reflective call to get caller class is only needed if a security manager
        // is present.  Avoid the overhead of making this call otherwise.
        caller = Reflection.getCallerClass();
        if (sun.misc.VM.isSystemDomainLoader(loader)) {
            ClassLoader ccl = ClassLoader.getClassLoader(caller);
            if (!sun.misc.VM.isSystemDomainLoader(ccl)) {
                sm.checkPermission(
                    SecurityConstants.GET_CLASSLOADER_PERMISSION);
            }
        }
    }
    return forName0(name, initialize, loader, caller);
}
 
Example #12
Source File: Logger.java    From jdk1.8-source-analysis with Apache License 2.0 4 votes vote down vote up
/**
 * Find or create a logger for a named subsystem.  If a logger has
 * already been created with the given name it is returned.  Otherwise
 * a new logger is created.
 * <p>
 * If a new logger is created its log level will be configured
 * based on the LogManager configuration and it will configured
 * to also send logging output to its parent's Handlers.  It will
 * be registered in the LogManager global namespace.
 * <p>
 * Note: The LogManager may only retain a weak reference to the newly
 * created Logger. It is important to understand that a previously
 * created Logger with the given name may be garbage collected at any
 * time if there is no strong reference to the Logger. In particular,
 * this means that two back-to-back calls like
 * {@code getLogger("MyLogger").log(...)} may use different Logger
 * objects named "MyLogger" if there is no strong reference to the
 * Logger named "MyLogger" elsewhere in the program.
 *
 * @param   name            A name for the logger.  This should
 *                          be a dot-separated name and should normally
 *                          be based on the package name or class name
 *                          of the subsystem, such as java.net
 *                          or javax.swing
 * @return a suitable Logger
 * @throws NullPointerException if the name is null.
 */

// Synchronization is not required here. All synchronization for
// adding a new Logger object is handled by LogManager.addLogger().
@CallerSensitive
public static Logger getLogger(String name) {
    // This method is intentionally not a wrapper around a call
    // to getLogger(name, resourceBundleName). If it were then
    // this sequence:
    //
    //     getLogger("Foo", "resourceBundleForFoo");
    //     getLogger("Foo");
    //
    // would throw an IllegalArgumentException in the second call
    // because the wrapper would result in an attempt to replace
    // the existing "resourceBundleForFoo" with null.
    return demandLogger(name, null, Reflection.getCallerClass());
}
 
Example #13
Source File: Constructor.java    From TencentKona-8 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Uses the constructor represented by this {@code Constructor} object to
 * create and initialize a new instance of the constructor's
 * declaring class, with the specified initialization parameters.
 * Individual parameters are automatically unwrapped to match
 * primitive formal parameters, and both primitive and reference
 * parameters are subject to method invocation conversions as necessary.
 *
 * <p>If the number of formal parameters required by the underlying constructor
 * is 0, the supplied {@code initargs} array may be of length 0 or null.
 *
 * <p>If the constructor's declaring class is an inner class in a
 * non-static context, the first argument to the constructor needs
 * to be the enclosing instance; see section 15.9.3 of
 * <cite>The Java&trade; Language Specification</cite>.
 *
 * <p>If the required access and argument checks succeed and the
 * instantiation will proceed, the constructor's declaring class
 * is initialized if it has not already been initialized.
 *
 * <p>If the constructor completes normally, returns the newly
 * created and initialized instance.
 *
 * @param initargs array of objects to be passed as arguments to
 * the constructor call; values of primitive types are wrapped in
 * a wrapper object of the appropriate type (e.g. a {@code float}
 * in a {@link java.lang.Float Float})
 *
 * @return a new object created by calling the constructor
 * this object represents
 *
 * @exception IllegalAccessException    if this {@code Constructor} object
 *              is enforcing Java language access control and the underlying
 *              constructor is inaccessible.
 * @exception IllegalArgumentException  if the number of actual
 *              and formal parameters differ; if an unwrapping
 *              conversion for primitive arguments fails; or if,
 *              after possible unwrapping, a parameter value
 *              cannot be converted to the corresponding formal
 *              parameter type by a method invocation conversion; if
 *              this constructor pertains to an enum type.
 * @exception InstantiationException    if the class that declares the
 *              underlying constructor represents an abstract class.
 * @exception InvocationTargetException if the underlying constructor
 *              throws an exception.
 * @exception ExceptionInInitializerError if the initialization provoked
 *              by this method fails.
 */
@CallerSensitive
public T newInstance(Object ... initargs)
    throws InstantiationException, IllegalAccessException,
           IllegalArgumentException, InvocationTargetException
{
    if (!override) {
        if (!Reflection.quickCheckMemberAccess(clazz, modifiers)) {
            Class<?> caller = Reflection.getCallerClass();
            checkAccess(caller, clazz, null, modifiers);
        }
    }
    if ((clazz.getModifiers() & Modifier.ENUM) != 0)
        throw new IllegalArgumentException("Cannot reflectively create enum objects");
    ConstructorAccessor ca = constructorAccessor;   // read volatile
    if (ca == null) {
        ca = acquireConstructorAccessor();
    }
    @SuppressWarnings("unchecked")
    T inst = (T) ca.newInstance(initargs);
    return inst;
}
 
Example #14
Source File: JavaAdapterBytecodeGenerator.java    From TencentKona-8 with GNU General Public License v2.0 4 votes vote down vote up
private static boolean isCallerSensitive(final AccessibleObject e) {
    return e.isAnnotationPresent(CallerSensitive.class);
}
 
Example #15
Source File: SecurityManager.java    From dragonwell8_jdk with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Throws a <code>SecurityException</code> if the
 * calling thread is not allowed to access members.
 * <p>
 * The default policy is to allow access to PUBLIC members, as well
 * as access to classes that have the same class loader as the caller.
 * In all other cases, this method calls <code>checkPermission</code>
 * with the <code>RuntimePermission("accessDeclaredMembers")
 * </code> permission.
 * <p>
 * If this method is overridden, then a call to
 * <code>super.checkMemberAccess</code> cannot be made,
 * as the default implementation of <code>checkMemberAccess</code>
 * relies on the code being checked being at a stack depth of
 * 4.
 *
 * @param clazz the class that reflection is to be performed on.
 *
 * @param which type of access, PUBLIC or DECLARED.
 *
 * @exception  SecurityException if the caller does not have
 *             permission to access members.
 * @exception  NullPointerException if the <code>clazz</code> argument is
 *             <code>null</code>.
 *
 * @deprecated This method relies on the caller being at a stack depth
 *             of 4 which is error-prone and cannot be enforced by the runtime.
 *             Users of this method should instead invoke {@link #checkPermission}
 *             directly.  This method will be changed in a future release
 *             to check the permission {@code java.security.AllPermission}.
 *
 * @see java.lang.reflect.Member
 * @since JDK1.1
 * @see        #checkPermission(java.security.Permission) checkPermission
 */
@Deprecated
@CallerSensitive
public void checkMemberAccess(Class<?> clazz, int which) {
    if (clazz == null) {
        throw new NullPointerException("class can't be null");
    }
    if (which != Member.PUBLIC) {
        Class<?> stack[] = getClassContext();
        /*
         * stack depth of 4 should be the caller of one of the
         * methods in java.lang.Class that invoke checkMember
         * access. The stack should look like:
         *
         * someCaller                        [3]
         * java.lang.Class.someReflectionAPI [2]
         * java.lang.Class.checkMemberAccess [1]
         * SecurityManager.checkMemberAccess [0]
         *
         */
        if ((stack.length<4) ||
            (stack[3].getClassLoader() != clazz.getClassLoader())) {
            checkPermission(SecurityConstants.CHECK_MEMBER_ACCESS_PERMISSION);
        }
    }
}
 
Example #16
Source File: Logger.java    From dragonwell8_jdk with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Find or create a logger for a named subsystem.  If a logger has
 * already been created with the given name it is returned.  Otherwise
 * a new logger is created.
 * <p>
 * If a new logger is created its log level will be configured
 * based on the LogManager and it will configured to also send logging
 * output to its parent's Handlers.  It will be registered in
 * the LogManager global namespace.
 * <p>
 * Note: The LogManager may only retain a weak reference to the newly
 * created Logger. It is important to understand that a previously
 * created Logger with the given name may be garbage collected at any
 * time if there is no strong reference to the Logger. In particular,
 * this means that two back-to-back calls like
 * {@code getLogger("MyLogger", ...).log(...)} may use different Logger
 * objects named "MyLogger" if there is no strong reference to the
 * Logger named "MyLogger" elsewhere in the program.
 * <p>
 * If the named Logger already exists and does not yet have a
 * localization resource bundle then the given resource bundle
 * name is used.  If the named Logger already exists and has
 * a different resource bundle name then an IllegalArgumentException
 * is thrown.
 * <p>
 * @param   name    A name for the logger.  This should
 *                          be a dot-separated name and should normally
 *                          be based on the package name or class name
 *                          of the subsystem, such as java.net
 *                          or javax.swing
 * @param   resourceBundleName  name of ResourceBundle to be used for localizing
 *                          messages for this logger. May be {@code null}
 *                          if none of the messages require localization.
 * @return a suitable Logger
 * @throws MissingResourceException if the resourceBundleName is non-null and
 *             no corresponding resource can be found.
 * @throws IllegalArgumentException if the Logger already exists and uses
 *             a different resource bundle name; or if
 *             {@code resourceBundleName} is {@code null} but the named
 *             logger has a resource bundle set.
 * @throws NullPointerException if the name is null.
 */

// Synchronization is not required here. All synchronization for
// adding a new Logger object is handled by LogManager.addLogger().
@CallerSensitive
public static Logger getLogger(String name, String resourceBundleName) {
    Class<?> callerClass = Reflection.getCallerClass();
    Logger result = demandLogger(name, resourceBundleName, callerClass);

    // MissingResourceException or IllegalArgumentException can be
    // thrown by setupResourceInfo().
    // We have to set the callers ClassLoader here in case demandLogger
    // above found a previously created Logger.  This can happen, for
    // example, if Logger.getLogger(name) is called and subsequently
    // Logger.getLogger(name, resourceBundleName) is called.  In this case
    // we won't necessarily have the correct classloader saved away, so
    // we need to set it here, too.

    result.setupResourceInfo(resourceBundleName, callerClass);
    return result;
}
 
Example #17
Source File: AccessController.java    From TencentKona-8 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Performs the specified {@code PrivilegedAction} with privileges
 * enabled and restricted by the specified
 * {@code AccessControlContext} and with a privilege scope limited
 * by specified {@code Permission} arguments.
 *
 * The action is performed with the intersection of the permissions
 * possessed by the caller's protection domain, and those possessed
 * by the domains represented by the specified
 * {@code AccessControlContext}.
 * <p>
 * If the action's {@code run} method throws an (unchecked) exception,
 * it will propagate through this method.
 *
 * <p> This method preserves the current AccessControlContext's
 * DomainCombiner (which may be null) while the action is performed.
 * <p>
 * If a security manager is installed and the specified
 * {@code AccessControlContext} was not created by system code and the
 * caller's {@code ProtectionDomain} has not been granted the
 * {@literal "createAccessControlContext"}
 * {@link java.security.SecurityPermission}, then the action is performed
 * with no permissions.
 *
 * @param <T> the type of the value returned by the PrivilegedAction's
 *                  {@code run} method.
 * @param action the action to be performed.
 * @param context an <i>access control context</i>
 *                representing the restriction to be applied to the
 *                caller's domain's privileges before performing
 *                the specified action.  If the context is
 *                {@code null},
 *                then no additional restriction is applied.
 * @param perms the {@code Permission} arguments which limit the
 *              scope of the caller's privileges. The number of arguments
 *              is variable.
 *
 * @return the value returned by the action's {@code run} method.
 *
 * @throws NullPointerException if action or perms or any element of
 *         perms is {@code null}
 *
 * @see #doPrivileged(PrivilegedAction)
 * @see #doPrivileged(PrivilegedExceptionAction,AccessControlContext)
 * @see java.security.DomainCombiner
 *
 * @since 1.8
 */
@CallerSensitive
public static <T> T doPrivilegedWithCombiner(PrivilegedAction<T> action,
    AccessControlContext context, Permission... perms) {

    AccessControlContext parent = getContext();
    DomainCombiner dc = parent.getCombiner();
    if (dc == null && context != null) {
        dc = context.getCombiner();
    }
    if (perms == null) {
        throw new NullPointerException("null permissions parameter");
    }
    Class <?> caller = Reflection.getCallerClass();
    return AccessController.doPrivileged(action, createWrapper(dc, caller,
        parent, context, perms));
}
 
Example #18
Source File: AccessController.java    From dragonwell8_jdk with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Performs the specified {@code PrivilegedAction} with privileges
 * enabled and restricted by the specified
 * {@code AccessControlContext} and with a privilege scope limited
 * by specified {@code Permission} arguments.
 *
 * The action is performed with the intersection of the permissions
 * possessed by the caller's protection domain, and those possessed
 * by the domains represented by the specified
 * {@code AccessControlContext}.
 * <p>
 * If the action's {@code run} method throws an (unchecked) exception,
 * it will propagate through this method.
 *
 * <p> This method preserves the current AccessControlContext's
 * DomainCombiner (which may be null) while the action is performed.
 * <p>
 * If a security manager is installed and the specified
 * {@code AccessControlContext} was not created by system code and the
 * caller's {@code ProtectionDomain} has not been granted the
 * {@literal "createAccessControlContext"}
 * {@link java.security.SecurityPermission}, then the action is performed
 * with no permissions.
 *
 * @param <T> the type of the value returned by the PrivilegedAction's
 *                  {@code run} method.
 * @param action the action to be performed.
 * @param context an <i>access control context</i>
 *                representing the restriction to be applied to the
 *                caller's domain's privileges before performing
 *                the specified action.  If the context is
 *                {@code null},
 *                then no additional restriction is applied.
 * @param perms the {@code Permission} arguments which limit the
 *              scope of the caller's privileges. The number of arguments
 *              is variable.
 *
 * @return the value returned by the action's {@code run} method.
 *
 * @throws NullPointerException if action or perms or any element of
 *         perms is {@code null}
 *
 * @see #doPrivileged(PrivilegedAction)
 * @see #doPrivileged(PrivilegedExceptionAction,AccessControlContext)
 * @see java.security.DomainCombiner
 *
 * @since 1.8
 */
@CallerSensitive
public static <T> T doPrivilegedWithCombiner(PrivilegedAction<T> action,
    AccessControlContext context, Permission... perms) {

    AccessControlContext parent = getContext();
    DomainCombiner dc = parent.getCombiner();
    if (dc == null && context != null) {
        dc = context.getCombiner();
    }
    if (perms == null) {
        throw new NullPointerException("null permissions parameter");
    }
    Class <?> caller = Reflection.getCallerClass();
    return AccessController.doPrivileged(action, createWrapper(dc, caller,
        parent, context, perms));
}
 
Example #19
Source File: Constructor.java    From dragonwell8_jdk with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Uses the constructor represented by this {@code Constructor} object to
 * create and initialize a new instance of the constructor's
 * declaring class, with the specified initialization parameters.
 * Individual parameters are automatically unwrapped to match
 * primitive formal parameters, and both primitive and reference
 * parameters are subject to method invocation conversions as necessary.
 *
 * <p>If the number of formal parameters required by the underlying constructor
 * is 0, the supplied {@code initargs} array may be of length 0 or null.
 *
 * <p>If the constructor's declaring class is an inner class in a
 * non-static context, the first argument to the constructor needs
 * to be the enclosing instance; see section 15.9.3 of
 * <cite>The Java&trade; Language Specification</cite>.
 *
 * <p>If the required access and argument checks succeed and the
 * instantiation will proceed, the constructor's declaring class
 * is initialized if it has not already been initialized.
 *
 * <p>If the constructor completes normally, returns the newly
 * created and initialized instance.
 *
 * @param initargs array of objects to be passed as arguments to
 * the constructor call; values of primitive types are wrapped in
 * a wrapper object of the appropriate type (e.g. a {@code float}
 * in a {@link java.lang.Float Float})
 *
 * @return a new object created by calling the constructor
 * this object represents
 *
 * @exception IllegalAccessException    if this {@code Constructor} object
 *              is enforcing Java language access control and the underlying
 *              constructor is inaccessible.
 * @exception IllegalArgumentException  if the number of actual
 *              and formal parameters differ; if an unwrapping
 *              conversion for primitive arguments fails; or if,
 *              after possible unwrapping, a parameter value
 *              cannot be converted to the corresponding formal
 *              parameter type by a method invocation conversion; if
 *              this constructor pertains to an enum type.
 * @exception InstantiationException    if the class that declares the
 *              underlying constructor represents an abstract class.
 * @exception InvocationTargetException if the underlying constructor
 *              throws an exception.
 * @exception ExceptionInInitializerError if the initialization provoked
 *              by this method fails.
 */
@CallerSensitive
public T newInstance(Object ... initargs)
    throws InstantiationException, IllegalAccessException,
           IllegalArgumentException, InvocationTargetException
{
    if (!override) {
        if (!Reflection.quickCheckMemberAccess(clazz, modifiers)) {
            Class<?> caller = Reflection.getCallerClass();
            checkAccess(caller, clazz, null, modifiers);
        }
    }
    if ((clazz.getModifiers() & Modifier.ENUM) != 0)
        throw new IllegalArgumentException("Cannot reflectively create enum objects");
    ConstructorAccessor ca = constructorAccessor;   // read volatile
    if (ca == null) {
        ca = acquireConstructorAccessor();
    }
    @SuppressWarnings("unchecked")
    T inst = (T) ca.newInstance(initargs);
    return inst;
}
 
Example #20
Source File: Logger.java    From TencentKona-8 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Find or create a logger for a named subsystem.  If a logger has
 * already been created with the given name it is returned.  Otherwise
 * a new logger is created.
 * <p>
 * If a new logger is created its log level will be configured
 * based on the LogManager configuration and it will configured
 * to also send logging output to its parent's Handlers.  It will
 * be registered in the LogManager global namespace.
 * <p>
 * Note: The LogManager may only retain a weak reference to the newly
 * created Logger. It is important to understand that a previously
 * created Logger with the given name may be garbage collected at any
 * time if there is no strong reference to the Logger. In particular,
 * this means that two back-to-back calls like
 * {@code getLogger("MyLogger").log(...)} may use different Logger
 * objects named "MyLogger" if there is no strong reference to the
 * Logger named "MyLogger" elsewhere in the program.
 *
 * @param   name            A name for the logger.  This should
 *                          be a dot-separated name and should normally
 *                          be based on the package name or class name
 *                          of the subsystem, such as java.net
 *                          or javax.swing
 * @return a suitable Logger
 * @throws NullPointerException if the name is null.
 */

// Synchronization is not required here. All synchronization for
// adding a new Logger object is handled by LogManager.addLogger().
@CallerSensitive
public static Logger getLogger(String name) {
    // This method is intentionally not a wrapper around a call
    // to getLogger(name, resourceBundleName). If it were then
    // this sequence:
    //
    //     getLogger("Foo", "resourceBundleForFoo");
    //     getLogger("Foo");
    //
    // would throw an IllegalArgumentException in the second call
    // because the wrapper would result in an attempt to replace
    // the existing "resourceBundleForFoo" with null.
    return demandLogger(name, null, Reflection.getCallerClass());
}
 
Example #21
Source File: Field.java    From TencentKona-8 with GNU General Public License v2.0 3 votes vote down vote up
/**
 * Gets the value of a static or instance field of type
 * {@code char} or of another primitive type convertible to
 * type {@code char} via a widening conversion.
 *
 * @param obj the object to extract the {@code char} value
 * from
 * @return the value of the field converted to type {@code char}
 *
 * @exception IllegalAccessException    if this {@code Field} object
 *              is enforcing Java language access control and the underlying
 *              field is inaccessible.
 * @exception IllegalArgumentException  if the specified object is not
 *              an instance of the class or interface declaring the
 *              underlying field (or a subclass or implementor
 *              thereof), or if the field value cannot be
 *              converted to the type {@code char} by a
 *              widening conversion.
 * @exception NullPointerException      if the specified object is null
 *              and the field is an instance field.
 * @exception ExceptionInInitializerError if the initialization provoked
 *              by this method fails.
 * @see Field#get
 */
@CallerSensitive
public char getChar(Object obj)
    throws IllegalArgumentException, IllegalAccessException
{
    if (!override) {
        if (!Reflection.quickCheckMemberAccess(clazz, modifiers)) {
            Class<?> caller = Reflection.getCallerClass();
            checkAccess(caller, clazz, obj, modifiers);
        }
    }
    return getFieldAccessor(obj).getChar(obj);
}
 
Example #22
Source File: Field.java    From jdk1.8-source-analysis with Apache License 2.0 3 votes vote down vote up
/**
 * Gets the value of a static or instance field of type
 * {@code short} or of another primitive type convertible to
 * type {@code short} via a widening conversion.
 *
 * @param obj the object to extract the {@code short} value
 * from
 * @return the value of the field converted to type {@code short}
 *
 * @exception IllegalAccessException    if this {@code Field} object
 *              is enforcing Java language access control and the underlying
 *              field is inaccessible.
 * @exception IllegalArgumentException  if the specified object is not
 *              an instance of the class or interface declaring the
 *              underlying field (or a subclass or implementor
 *              thereof), or if the field value cannot be
 *              converted to the type {@code short} by a
 *              widening conversion.
 * @exception NullPointerException      if the specified object is null
 *              and the field is an instance field.
 * @exception ExceptionInInitializerError if the initialization provoked
 *              by this method fails.
 * @see       Field#get
 */
@CallerSensitive
public short getShort(Object obj)
    throws IllegalArgumentException, IllegalAccessException
{
    if (!override) {
        if (!Reflection.quickCheckMemberAccess(clazz, modifiers)) {
            Class<?> caller = Reflection.getCallerClass();
            checkAccess(caller, clazz, obj, modifiers);
        }
    }
    return getFieldAccessor(obj).getShort(obj);
}
 
Example #23
Source File: Field.java    From jdk1.8-source-analysis with Apache License 2.0 3 votes vote down vote up
/**
 * Gets the value of a static or instance {@code byte} field.
 *
 * @param obj the object to extract the {@code byte} value
 * from
 * @return the value of the {@code byte} field
 *
 * @exception IllegalAccessException    if this {@code Field} object
 *              is enforcing Java language access control and the underlying
 *              field is inaccessible.
 * @exception IllegalArgumentException  if the specified object is not
 *              an instance of the class or interface declaring the
 *              underlying field (or a subclass or implementor
 *              thereof), or if the field value cannot be
 *              converted to the type {@code byte} by a
 *              widening conversion.
 * @exception NullPointerException      if the specified object is null
 *              and the field is an instance field.
 * @exception ExceptionInInitializerError if the initialization provoked
 *              by this method fails.
 * @see       Field#get
 */
@CallerSensitive
public byte getByte(Object obj)
    throws IllegalArgumentException, IllegalAccessException
{
    if (!override) {
        if (!Reflection.quickCheckMemberAccess(clazz, modifiers)) {
            Class<?> caller = Reflection.getCallerClass();
            checkAccess(caller, clazz, obj, modifiers);
        }
    }
    return getFieldAccessor(obj).getByte(obj);
}
 
Example #24
Source File: Field.java    From TencentKona-8 with GNU General Public License v2.0 3 votes vote down vote up
/**
 * Sets the value of a field as a {@code boolean} on the specified object.
 * This method is equivalent to
 * {@code set(obj, zObj)},
 * where {@code zObj} is a {@code Boolean} object and
 * {@code zObj.booleanValue() == z}.
 *
 * @param obj the object whose field should be modified
 * @param z   the new value for the field of {@code obj}
 * being modified
 *
 * @exception IllegalAccessException    if this {@code Field} object
 *              is enforcing Java language access control and the underlying
 *              field is either inaccessible or final.
 * @exception IllegalArgumentException  if the specified object is not an
 *              instance of the class or interface declaring the underlying
 *              field (or a subclass or implementor thereof),
 *              or if an unwrapping conversion fails.
 * @exception NullPointerException      if the specified object is null
 *              and the field is an instance field.
 * @exception ExceptionInInitializerError if the initialization provoked
 *              by this method fails.
 * @see       Field#set
 */
@CallerSensitive
public void setBoolean(Object obj, boolean z)
    throws IllegalArgumentException, IllegalAccessException
{
    if (!override) {
        if (!Reflection.quickCheckMemberAccess(clazz, modifiers)) {
            Class<?> caller = Reflection.getCallerClass();
            checkAccess(caller, clazz, obj, modifiers);
        }
    }
    getFieldAccessor(obj).setBoolean(obj, z);
}
 
Example #25
Source File: Field.java    From TencentKona-8 with GNU General Public License v2.0 3 votes vote down vote up
/**
 * Gets the value of a static or instance field of type
 * {@code float} or of another primitive type convertible to
 * type {@code float} via a widening conversion.
 *
 * @param obj the object to extract the {@code float} value
 * from
 * @return the value of the field converted to type {@code float}
 *
 * @exception IllegalAccessException    if this {@code Field} object
 *              is enforcing Java language access control and the underlying
 *              field is inaccessible.
 * @exception IllegalArgumentException  if the specified object is not
 *              an instance of the class or interface declaring the
 *              underlying field (or a subclass or implementor
 *              thereof), or if the field value cannot be
 *              converted to the type {@code float} by a
 *              widening conversion.
 * @exception NullPointerException      if the specified object is null
 *              and the field is an instance field.
 * @exception ExceptionInInitializerError if the initialization provoked
 *              by this method fails.
 * @see Field#get
 */
@CallerSensitive
public float getFloat(Object obj)
    throws IllegalArgumentException, IllegalAccessException
{
    if (!override) {
        if (!Reflection.quickCheckMemberAccess(clazz, modifiers)) {
            Class<?> caller = Reflection.getCallerClass();
            checkAccess(caller, clazz, obj, modifiers);
        }
    }
    return getFieldAccessor(obj).getFloat(obj);
}
 
Example #26
Source File: DriverManager.java    From dragonwell8_jdk with GNU General Public License v2.0 3 votes vote down vote up
/**
 * Attempts to establish a connection to the given database URL.
 * The <code>DriverManager</code> attempts to select an appropriate driver from
 * the set of registered JDBC drivers.
 *<p>
 * <B>Note:</B> If a property is specified as part of the {@code url} and
 * is also specified in the {@code Properties} object, it is
 * implementation-defined as to which value will take precedence.
 * For maximum portability, an application should only specify a
 * property once.
 *
 * @param url a database url of the form
 * <code> jdbc:<em>subprotocol</em>:<em>subname</em></code>
 * @param info a list of arbitrary string tag/value pairs as
 * connection arguments; normally at least a "user" and
 * "password" property should be included
 * @return a Connection to the URL
 * @exception SQLException if a database access error occurs or the url is
 * {@code null}
 * @throws SQLTimeoutException  when the driver has determined that the
 * timeout value specified by the {@code setLoginTimeout} method
 * has been exceeded and has at least tried to cancel the
 * current database connection attempt
 */
@CallerSensitive
public static Connection getConnection(String url,
    java.util.Properties info) throws SQLException {

    return (getConnection(url, info, Reflection.getCallerClass()));
}
 
Example #27
Source File: AtomicLongFieldUpdater.java    From TencentKona-8 with GNU General Public License v2.0 3 votes vote down vote up
/**
 * Creates and returns an updater for objects with the given field.
 * The Class argument is needed to check that reflective types and
 * generic types match.
 *
 * @param tclass the class of the objects holding the field
 * @param fieldName the name of the field to be updated
 * @param <U> the type of instances of tclass
 * @return the updater
 * @throws IllegalArgumentException if the field is not a
 * volatile long type
 * @throws RuntimeException with a nested reflection-based
 * exception if the class does not hold field or is the wrong type,
 * or the field is inaccessible to the caller according to Java language
 * access control
 */
@CallerSensitive
public static <U> AtomicLongFieldUpdater<U> newUpdater(Class<U> tclass,
                                                       String fieldName) {
    Class<?> caller = Reflection.getCallerClass();
    if (AtomicLong.VM_SUPPORTS_LONG_CAS)
        return new CASUpdater<U>(tclass, fieldName, caller);
    else
        return new LockedUpdater<U>(tclass, fieldName, caller);
}
 
Example #28
Source File: Field.java    From dragonwell8_jdk with GNU General Public License v2.0 3 votes vote down vote up
/**
 * Sets the value of a field as a {@code boolean} on the specified object.
 * This method is equivalent to
 * {@code set(obj, zObj)},
 * where {@code zObj} is a {@code Boolean} object and
 * {@code zObj.booleanValue() == z}.
 *
 * @param obj the object whose field should be modified
 * @param z   the new value for the field of {@code obj}
 * being modified
 *
 * @exception IllegalAccessException    if this {@code Field} object
 *              is enforcing Java language access control and the underlying
 *              field is either inaccessible or final.
 * @exception IllegalArgumentException  if the specified object is not an
 *              instance of the class or interface declaring the underlying
 *              field (or a subclass or implementor thereof),
 *              or if an unwrapping conversion fails.
 * @exception NullPointerException      if the specified object is null
 *              and the field is an instance field.
 * @exception ExceptionInInitializerError if the initialization provoked
 *              by this method fails.
 * @see       Field#set
 */
@CallerSensitive
public void setBoolean(Object obj, boolean z)
    throws IllegalArgumentException, IllegalAccessException
{
    if (!override) {
        if (!Reflection.quickCheckMemberAccess(clazz, modifiers)) {
            Class<?> caller = Reflection.getCallerClass();
            checkAccess(caller, clazz, obj, modifiers);
        }
    }
    getFieldAccessor(obj).setBoolean(obj, z);
}
 
Example #29
Source File: AccessController.java    From dragonwell8_jdk with GNU General Public License v2.0 3 votes vote down vote up
/**
 * Performs the specified {@code PrivilegedAction} with privileges
 * enabled and restricted by the specified
 * {@code AccessControlContext} and with a privilege scope limited
 * by specified {@code Permission} arguments.
 *
 * The action is performed with the intersection of the permissions
 * possessed by the caller's protection domain, and those possessed
 * by the domains represented by the specified
 * {@code AccessControlContext}.
 * <p>
 * If the action's {@code run} method throws an (unchecked) exception,
 * it will propagate through this method.
 * <p>
 * If a security manager is installed and the specified
 * {@code AccessControlContext} was not created by system code and the
 * caller's {@code ProtectionDomain} has not been granted the
 * {@literal "createAccessControlContext"}
 * {@link java.security.SecurityPermission}, then the action is performed
 * with no permissions.
 *
 * @param <T> the type of the value returned by the PrivilegedAction's
 *                  {@code run} method.
 * @param action the action to be performed.
 * @param context an <i>access control context</i>
 *                representing the restriction to be applied to the
 *                caller's domain's privileges before performing
 *                the specified action.  If the context is
 *                {@code null},
 *                then no additional restriction is applied.
 * @param perms the {@code Permission} arguments which limit the
 *              scope of the caller's privileges. The number of arguments
 *              is variable.
 *
 * @return the value returned by the action's {@code run} method.
 *
 * @throws NullPointerException if action or perms or any element of
 *         perms is {@code null}
 *
 * @see #doPrivileged(PrivilegedAction)
 * @see #doPrivileged(PrivilegedExceptionAction,AccessControlContext)
 *
 * @since 1.8
 */
@CallerSensitive
public static <T> T doPrivileged(PrivilegedAction<T> action,
    AccessControlContext context, Permission... perms) {

    AccessControlContext parent = getContext();
    if (perms == null) {
        throw new NullPointerException("null permissions parameter");
    }
    Class <?> caller = Reflection.getCallerClass();
    DomainCombiner dc = (context == null) ? null : context.getCombiner();
    return AccessController.doPrivileged(action, createWrapper(dc,
        caller, parent, context, perms));
}
 
Example #30
Source File: Field.java    From jdk1.8-source-analysis with Apache License 2.0 3 votes vote down vote up
/**
 * Gets the value of a static or instance field of type
 * {@code int} or of another primitive type convertible to
 * type {@code int} via a widening conversion.
 *
 * @param obj the object to extract the {@code int} value
 * from
 * @return the value of the field converted to type {@code int}
 *
 * @exception IllegalAccessException    if this {@code Field} object
 *              is enforcing Java language access control and the underlying
 *              field is inaccessible.
 * @exception IllegalArgumentException  if the specified object is not
 *              an instance of the class or interface declaring the
 *              underlying field (or a subclass or implementor
 *              thereof), or if the field value cannot be
 *              converted to the type {@code int} by a
 *              widening conversion.
 * @exception NullPointerException      if the specified object is null
 *              and the field is an instance field.
 * @exception ExceptionInInitializerError if the initialization provoked
 *              by this method fails.
 * @see       Field#get
 */
@CallerSensitive
public int getInt(Object obj)
    throws IllegalArgumentException, IllegalAccessException
{
    if (!override) {
        if (!Reflection.quickCheckMemberAccess(clazz, modifiers)) {
            Class<?> caller = Reflection.getCallerClass();
            checkAccess(caller, clazz, obj, modifiers);
        }
    }
    return getFieldAccessor(obj).getInt(obj);
}