Search in sources :

Example 1 with CallerSensitive

use of jdk.internal.reflect.CallerSensitive in project Bytecoder by mirkosertic.

the class Module method addUses.

// -- services --
/**
 * If the caller's module is this module then update this module to add a
 * service dependence on the given service type. This method is intended
 * for use by frameworks that invoke {@link java.util.ServiceLoader
 * ServiceLoader} on behalf of other modules or where the framework is
 * passed a reference to the service type by other code. This method is
 * a no-op when invoked on an unnamed module or an automatic module.
 *
 * <p> This method does not cause {@link Configuration#resolveAndBind
 * resolveAndBind} to be re-run. </p>
 *
 * @param  service
 *         The service type
 *
 * @return this module
 *
 * @throws IllegalCallerException
 *         If this is a named module and the caller's module is not this
 *         module
 *
 * @see #canUse(Class)
 * @see ModuleDescriptor#uses()
 */
@CallerSensitive
public Module addUses(Class<?> service) {
    Objects.requireNonNull(service);
    if (isNamed() && !descriptor.isAutomatic()) {
        Module caller = getCallerModule(Reflection.getCallerClass());
        if (caller != this) {
            throw new IllegalCallerException(caller + " != " + this);
        }
        implAddUses(service);
    }
    return this;
}
Also used : ResolvedModule(java.lang.module.ResolvedModule) CallerSensitive(jdk.internal.reflect.CallerSensitive)

Example 2 with CallerSensitive

use of jdk.internal.reflect.CallerSensitive in project Bytecoder by mirkosertic.

the class Constructor method newInstance.

/**
 * 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
// to ensure Reflection.getCallerClass optimization
@ForceInline
public T newInstance(Object... initargs) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
    if (!override) {
        Class<?> caller = Reflection.getCallerClass();
        checkAccess(caller, clazz, clazz, modifiers);
    }
    if ((clazz.getModifiers() & Modifier.ENUM) != 0)
        throw new IllegalArgumentException("Cannot reflectively create enum objects");
    // read volatile
    ConstructorAccessor ca = constructorAccessor;
    if (ca == null) {
        ca = acquireConstructorAccessor();
    }
    @SuppressWarnings("unchecked") T inst = (T) ca.newInstance(initargs);
    return inst;
}
Also used : ConstructorAccessor(jdk.internal.reflect.ConstructorAccessor) ForceInline(jdk.internal.vm.annotation.ForceInline) CallerSensitive(jdk.internal.reflect.CallerSensitive)

Example 3 with CallerSensitive

use of jdk.internal.reflect.CallerSensitive in project Bytecoder by mirkosertic.

the class Class method forName.

/**
 * Returns the {@code Class} with the given <a href="ClassLoader.html#name">
 * binary name</a> in the given module.
 *
 * <p> This method attempts to locate, load, and link the class or interface.
 * It does not run the class initializer.  If the class is not found, this
 * method returns {@code null}. </p>
 *
 * <p> If the class loader of the given module defines other modules and
 * the given name is a class defined in a different module, this method
 * returns {@code null} after the class is loaded. </p>
 *
 * <p> This method does not check whether the requested class is
 * accessible to its caller. </p>
 *
 * @apiNote
 * This method returns {@code null} on failure rather than
 * throwing a {@link ClassNotFoundException}, as is done by
 * the {@link #forName(String, boolean, ClassLoader)} method.
 * The security check is a stack-based permission check if the caller
 * loads a class in another module.
 *
 * @param  module   A module
 * @param  name     The <a href="ClassLoader.html#name">binary name</a>
 *                  of the class
 * @return {@code Class} object of the given name defined in the given module;
 *         {@code null} if not found.
 *
 * @throws NullPointerException if the given module or name is {@code null}
 *
 * @throws LinkageError if the linkage fails
 *
 * @throws SecurityException
 *         <ul>
 *         <li> if the caller is not the specified module and
 *         {@code RuntimePermission("getClassLoader")} permission is denied; or</li>
 *         <li> access to the module content is denied. For example,
 *         permission check will be performed when a class loader calls
 *         {@link ModuleReader#open(String)} to read the bytes of a class file
 *         in a module.</li>
 *         </ul>
 *
 * @since 9
 * @spec JPMS
 */
@CallerSensitive
public static Class<?> forName(Module module, String name) {
    Objects.requireNonNull(module);
    Objects.requireNonNull(name);
    ClassLoader cl;
    SecurityManager sm = System.getSecurityManager();
    if (sm != null) {
        Class<?> caller = Reflection.getCallerClass();
        if (caller != null && caller.getModule() != module) {
            // if caller is null, Class.forName is the last java frame on the stack.
            // java.base has all permissions
            sm.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION);
        }
        PrivilegedAction<ClassLoader> pa = module::getClassLoader;
        cl = AccessController.doPrivileged(pa);
    } else {
        cl = module.getClassLoader();
    }
    if (cl != null) {
        return cl.loadClass(module, name);
    } else {
        return BootLoader.loadClass(module, name);
    }
}
Also used : BuiltinClassLoader(jdk.internal.loader.BuiltinClassLoader) CallerSensitive(jdk.internal.reflect.CallerSensitive)

Example 4 with CallerSensitive

use of jdk.internal.reflect.CallerSensitive in project Bytecoder by mirkosertic.

the class Class method getResourceAsStream.

/**
 * Finds a resource with a given name.
 *
 * <p> If this class is in a named {@link Module Module} then this method
 * will attempt to find the resource in the module. This is done by
 * delegating to the module's class loader {@link
 * ClassLoader#findResource(String,String) findResource(String,String)}
 * method, invoking it with the module name and the absolute name of the
 * resource. Resources in named modules are subject to the rules for
 * encapsulation specified in the {@code Module} {@link
 * Module#getResourceAsStream getResourceAsStream} method and so this
 * method returns {@code null} when the resource is a
 * non-"{@code .class}" resource in a package that is not open to the
 * caller's module.
 *
 * <p> Otherwise, if this class is not in a named module then the rules for
 * searching resources associated with a given class are implemented by the
 * defining {@linkplain ClassLoader class loader} of the class.  This method
 * delegates to this object's class loader.  If this object was loaded by
 * the bootstrap class loader, the method delegates to {@link
 * ClassLoader#getSystemResourceAsStream}.
 *
 * <p> Before delegation, an absolute resource name is constructed from the
 * given resource name using this algorithm:
 *
 * <ul>
 *
 * <li> If the {@code name} begins with a {@code '/'}
 * (<code>'&#92;u002f'</code>), then the absolute name of the resource is the
 * portion of the {@code name} following the {@code '/'}.
 *
 * <li> Otherwise, the absolute name is of the following form:
 *
 * <blockquote>
 *   {@code modified_package_name/name}
 * </blockquote>
 *
 * <p> Where the {@code modified_package_name} is the package name of this
 * object with {@code '/'} substituted for {@code '.'}
 * (<code>'&#92;u002e'</code>).
 *
 * </ul>
 *
 * @param  name name of the desired resource
 * @return  A {@link java.io.InputStream} object; {@code null} if no
 *          resource with this name is found, the resource is in a package
 *          that is not {@link Module#isOpen(String, Module) open} to at
 *          least the caller module, or access to the resource is denied
 *          by the security manager.
 * @throws  NullPointerException If {@code name} is {@code null}
 *
 * @see Module#getResourceAsStream(String)
 * @since  1.1
 * @revised 9
 * @spec JPMS
 */
@CallerSensitive
public InputStream getResourceAsStream(String name) {
    name = resolveName(name);
    Module thisModule = getModule();
    if (thisModule.isNamed()) {
        // check if resource can be located by caller
        if (Resources.canEncapsulate(name) && !isOpenToCaller(name, Reflection.getCallerClass())) {
            return null;
        }
        // resource not encapsulated or in package open to caller
        String mn = thisModule.getName();
        ClassLoader cl = getClassLoader0();
        try {
            // need for a URL connection
            if (cl == null) {
                return BootLoader.findResourceAsStream(mn, name);
            } else if (cl instanceof BuiltinClassLoader) {
                return ((BuiltinClassLoader) cl).findResourceAsStream(mn, name);
            } else {
                URL url = cl.findResource(mn, name);
                return (url != null) ? url.openStream() : null;
            }
        } catch (IOException | SecurityException e) {
            return null;
        }
    }
    // unnamed module
    ClassLoader cl = getClassLoader0();
    if (cl == null) {
        return ClassLoader.getSystemResourceAsStream(name);
    } else {
        return cl.getResourceAsStream(name);
    }
}
Also used : BuiltinClassLoader(jdk.internal.loader.BuiltinClassLoader) BuiltinClassLoader(jdk.internal.loader.BuiltinClassLoader) IOException(java.io.IOException) URL(java.net.URL) CallerSensitive(jdk.internal.reflect.CallerSensitive)

Example 5 with CallerSensitive

use of jdk.internal.reflect.CallerSensitive in project Bytecoder by mirkosertic.

the class Class method getDeclaredField.

/**
 * Returns a {@code Field} object that reflects the specified declared
 * field of the class or interface represented by this {@code Class}
 * object. The {@code name} parameter is a {@code String} that specifies
 * the simple name of the desired field.
 *
 * <p> If this {@code Class} object represents an array type, then this
 * method does not find the {@code length} field of the array type.
 *
 * @param name the name of the field
 * @return  the {@code Field} object for the specified field in this
 *          class
 * @throws  NoSuchFieldException if a field with the specified name is
 *          not found.
 * @throws  NullPointerException if {@code name} is {@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 this class and invocation of
 *          {@link SecurityManager#checkPermission
 *          s.checkPermission} method with
 *          {@code RuntimePermission("accessDeclaredMembers")}
 *          denies access to the declared field
 *
 *          <li> 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
 *
 *          </ul>
 *
 * @since 1.1
 * @jls 8.2 Class Members
 * @jls 8.3 Field Declarations
 */
@CallerSensitive
public Field getDeclaredField(String name) throws NoSuchFieldException, SecurityException {
    Objects.requireNonNull(name);
    SecurityManager sm = System.getSecurityManager();
    if (sm != null) {
        checkMemberAccess(sm, Member.DECLARED, Reflection.getCallerClass(), true);
    }
    Field field = searchFields(privateGetDeclaredFields(false), name);
    if (field == null) {
        throw new NoSuchFieldException(name);
    }
    return getReflectionFactory().copyField(field);
}
Also used : ObjectStreamField(java.io.ObjectStreamField) Field(java.lang.reflect.Field) CallerSensitive(jdk.internal.reflect.CallerSensitive)

Aggregations

CallerSensitive (jdk.internal.reflect.CallerSensitive)20 BuiltinClassLoader (jdk.internal.loader.BuiltinClassLoader)6 ResolvedModule (java.lang.module.ResolvedModule)5 Method (java.lang.reflect.Method)3 ForceInline (jdk.internal.vm.annotation.ForceInline)3 IOException (java.io.IOException)2 ObjectStreamField (java.io.ObjectStreamField)2 AnnotatedType (java.lang.reflect.AnnotatedType)2 Field (java.lang.reflect.Field)2 GenericArrayType (java.lang.reflect.GenericArrayType)2 Type (java.lang.reflect.Type)2 URL (java.net.URL)2 ReflectionFactory (jdk.internal.reflect.ReflectionFactory)2 CoreReflectionFactory (sun.reflect.generics.factory.CoreReflectionFactory)2 Constructor (java.lang.reflect.Constructor)1 ResourceBundle (java.util.ResourceBundle)1 HotSpotIntrinsicCandidate (jdk.internal.HotSpotIntrinsicCandidate)1 ConstructorAccessor (jdk.internal.reflect.ConstructorAccessor)1 MethodAccessor (jdk.internal.reflect.MethodAccessor)1 ConstructorRepository (sun.reflect.generics.repository.ConstructorRepository)1