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