    001/*
    002 * Licensed to the Apache Software Foundation (ASF) under one or more
    003 * contributor license agreements.  See the NOTICE file distributed with
    004 * this work for additional information regarding copyright ownership.
    005 * The ASF licenses this file to You under the Apache License, Version 2.0
    006 * (the "License"); you may not use this file except in compliance with
    007 * the License.  You may obtain a copy of the License at
    008 *
    009 *      http://www.apache.org/licenses/LICENSE-2.0
    010 *
    011 *  Unless required by applicable law or agreed to in writing, software
    012 *  distributed under the License is distributed on an "AS IS" BASIS,
    013 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    014 *  See the License for the specific language governing permissions and
    015 *  limitations under the License.
    016 *
    017 */
    018package org.apache.bcel.util;
    019
    020import java.io.ByteArrayInputStream;
    021import java.io.IOException;
    022import java.util.Hashtable;
    023
    024import org.apache.bcel.Const;
    025import org.apache.bcel.classfile.ClassParser;
    026import org.apache.bcel.classfile.ConstantClass;
    027import org.apache.bcel.classfile.ConstantPool;
    028import org.apache.bcel.classfile.ConstantUtf8;
    029import org.apache.bcel.classfile.JavaClass;
    030import org.apache.bcel.classfile.Utility;
    031
    032/**
    033 * <p>Drop in replacement for the standard class loader of the JVM. You can use it
    034 * in conjunction with the JavaWrapper to dynamically modify/create classes
    035 * as they're requested.</p>
    036 *
    037 * <p>This class loader recognizes special requests in a distinct
    038 * format, i.e., when the name of the requested class contains with
    039 * "$$BCEL$$" it calls the createClass() method with that name
    040 * (everything bevor the $$BCEL$$ is considered to be the package
    041 * name. You can subclass the class loader and override that
    042 * method. "Normal" classes class can be modified by overriding the
    043 * modifyClass() method which is called just before defineClass().</p>
    044 *
    045 * <p>There may be a number of packages where you have to use the
    046 * default class loader (which may also be faster). You can define the
    047 * set of packages where to use the system class loader in the
    048 * constructor. The default value contains "java.", "sun.",
    049 * "javax."</p>
    050 *
    051 * @see JavaWrapper
    052 * @see ClassPath
    053 * @deprecated 6.0 Do not use - does not work
    054 */
    055@Deprecated
    056public class ClassLoader extends java.lang.ClassLoader {
    057
    058    private static final String BCEL_TOKEN = "$$BCEL$$";
    059
    060    public static final String[] DEFAULT_IGNORED_PACKAGES = {
    061            "java.", "javax.", "sun."
    062    };
    063
    064    private final Hashtable<String, Class<?>> classes = new Hashtable<>();
    065    // Hashtable is synchronized thus thread-safe
    066    private final String[] ignored_packages;
    067    private Repository repository = SyntheticRepository.getInstance();
    068
    069
    070    /** Ignored packages are by default ( "java.", "sun.",
    071     * "javax."), i.e. loaded by system class loader
    072     */
    073    public ClassLoader() {
    074        this(DEFAULT_IGNORED_PACKAGES);
    075    }
    076
    077
    078    /** @param deferTo delegate class loader to use for ignored packages
    079     */
    080    public ClassLoader(final java.lang.ClassLoader deferTo) {
    081        super(deferTo);
    082        this.ignored_packages = DEFAULT_IGNORED_PACKAGES;
    083        this.repository = new ClassLoaderRepository(deferTo);
    084    }
    085
    086
    087    /** @param ignored_packages classes contained in these packages will be loaded
    088     * with the system class loader
    089     */
    090    public ClassLoader(final String[] ignored_packages) {
    091        this.ignored_packages = ignored_packages;
    092    }
    093
    094
    095    /** @param ignored_packages classes contained in these packages will be loaded
    096     * with the system class loader
    097     * @param deferTo delegate class loader to use for ignored packages
    098     */
    099    public ClassLoader(final java.lang.ClassLoader deferTo, final String[] ignored_packages) {
    100        this(ignored_packages);
    101        this.repository = new ClassLoaderRepository(deferTo);
    102    }
    103
    104    @Override
    105    protected Class<?> loadClass( final String class_name, final boolean resolve ) throws ClassNotFoundException {
    106        Class<?> cl = null;
    107        /* First try: lookup hash table.
    108         */
    109        if ((cl = classes.get(class_name)) == null) {
    110            /* Second try: Load system class using system class loader. You better
    111             * don't mess around with them.
    112             */
    113            for (final String ignored_package : ignored_packages) {
    114                if (class_name.startsWith(ignored_package)) {
    115                    cl = getParent().loadClass(class_name);
    116                    break;
    117                }
    118            }
    119            if (cl == null) {
    120                JavaClass clazz = null;
    121                /* Third try: Special request?
    122                 */
    123                if (class_name.contains(BCEL_TOKEN)) {
    124                    clazz = createClass(class_name);
    125                } else { // Fourth try: Load classes via repository
    126                    if ((clazz = repository.loadClass(class_name)) != null) {
    127                        clazz = modifyClass(clazz);
    128                    } else {
    129                        throw new ClassNotFoundException(class_name);
    130                    }
    131                }
    132                if (clazz != null) {
    133                    final byte[] bytes = clazz.getBytes();
    134                    cl = defineClass(class_name, bytes, 0, bytes.length);
    135                } else {
    136                    cl = Class.forName(class_name);
    137                }
    138            }
    139            if (resolve) {
    140                resolveClass(cl);
    141            }
    142        }
    143        classes.put(class_name, cl);
    144        return cl;
    145    }
    146
    147
    148    /** Override this method if you want to alter a class before it gets actually
    149     * loaded. Does nothing by default.
    150     */
    151    protected JavaClass modifyClass( final JavaClass clazz ) {
    152        return clazz;
    153    }
    154
    155
    156    /**
    157     * Override this method to create you own classes on the fly. The
    158     * name contains the special token $$BCEL$$. Everything before that
    159     * token is considered to be a package name. You can encode your own
    160     * arguments into the subsequent string. You must ensure however not
    161     * to use any "illegal" characters, i.e., characters that may not
    162     * appear in a Java class name too
    163     * <p>
    164     * The default implementation interprets the string as a encoded compressed
    165     * Java class, unpacks and decodes it with the Utility.decode() method, and
    166     * parses the resulting byte array and returns the resulting JavaClass object.
    167     * </p>
    168     *
    169     * @param class_name compressed byte code with "$$BCEL$$" in it
    170     */
    171    protected JavaClass createClass( final String class_name ) {
    172        final int index = class_name.indexOf(BCEL_TOKEN);
    173        final String real_name = class_name.substring(index + BCEL_TOKEN.length());
    174        JavaClass clazz = null;
    175        try {
    176            final byte[] bytes = Utility.decode(real_name, true);
    177            final ClassParser parser = new ClassParser(new ByteArrayInputStream(bytes), "foo");
    178            clazz = parser.parse();
    179        } catch (final IOException e) {
    180            e.printStackTrace();
    181            return null;
    182        }
    183        // Adapt the class name to the passed value
    184        final ConstantPool cp = clazz.getConstantPool();
    185        final ConstantClass cl = (ConstantClass) cp.getConstant(clazz.getClassNameIndex(),
    186                Const.CONSTANT_Class);
    187        final ConstantUtf8 name = (ConstantUtf8) cp.getConstant(cl.getNameIndex(),
    188                Const.CONSTANT_Utf8);
    189        name.setBytes(class_name.replace('.', '/'));
    190        return clazz;
    191    }
    192}