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.Constants;
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 * @version $Id: ClassLoader.html 992795 2016-07-14 11:53:52Z britter $
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 = {
062            "java.", "javax.", "sun."
063    };
064
065    private final Hashtable<String, Class<?>> classes = new Hashtable<>();
066    // Hashtable is synchronized thus thread-safe
067    private final String[] ignored_packages;
068    private Repository repository = SyntheticRepository.getInstance();
069
070
071    /** Ignored packages are by default ( "java.", "sun.",
072     * "javax."), i.e. loaded by system class loader
073     */
074    public ClassLoader() {
075        this(DEFAULT_IGNORED_PACKAGES);
076    }
077
078
079    /** @param deferTo delegate class loader to use for ignored packages
080     */
081    public ClassLoader(final java.lang.ClassLoader deferTo) {
082        super(deferTo);
083        this.ignored_packages = DEFAULT_IGNORED_PACKAGES;
084        this.repository = new ClassLoaderRepository(deferTo);
085    }
086
087
088    /** @param ignored_packages classes contained in these packages will be loaded
089     * with the system class loader
090     */
091    public ClassLoader(final String[] ignored_packages) {
092        this.ignored_packages = ignored_packages;
093    }
094
095
096    /** @param ignored_packages classes contained in these packages will be loaded
097     * with the system class loader
098     * @param deferTo delegate class loader to use for ignored packages
099     */
100    public ClassLoader(final java.lang.ClassLoader deferTo, final String[] ignored_packages) {
101        this(ignored_packages);
102        this.repository = new ClassLoaderRepository(deferTo);
103    }
104
105    @Override
106    protected Class<?> loadClass( final String class_name, final boolean resolve ) throws ClassNotFoundException {
107        Class<?> cl = null;
108        /* First try: lookup hash table.
109         */
110        if ((cl = classes.get(class_name)) == null) {
111            /* Second try: Load system class using system class loader. You better
112             * don't mess around with them.
113             */
114            for (final String ignored_package : ignored_packages) {
115                if (class_name.startsWith(ignored_package)) {
116                    cl = getParent().loadClass(class_name);
117                    break;
118                }
119            }
120            if (cl == null) {
121                JavaClass clazz = null;
122                /* Third try: Special request?
123                 */
124                if (class_name.contains(BCEL_TOKEN)) {
125                    clazz = createClass(class_name);
126                } else { // Fourth try: Load classes via repository
127                    if ((clazz = repository.loadClass(class_name)) != null) {
128                        clazz = modifyClass(clazz);
129                    } else {
130                        throw new ClassNotFoundException(class_name);
131                    }
132                }
133                if (clazz != null) {
134                    final byte[] bytes = clazz.getBytes();
135                    cl = defineClass(class_name, bytes, 0, bytes.length);
136                } else {
137                    cl = Class.forName(class_name);
138                }
139            }
140            if (resolve) {
141                resolveClass(cl);
142            }
143        }
144        classes.put(class_name, cl);
145        return cl;
146    }
147
148
149    /** Override this method if you want to alter a class before it gets actually
150     * loaded. Does nothing by default.
151     */
152    protected JavaClass modifyClass( final JavaClass clazz ) {
153        return clazz;
154    }
155
156
157    /** 
158     * Override this method to create you own classes on the fly. The
159     * name contains the special token $$BCEL$$. Everything before that
160     * token is considered to be a package name. You can encode your own
161     * arguments into the subsequent string. You must ensure however not
162     * to use any "illegal" characters, i.e., characters that may not
163     * appear in a Java class name too<br>
164     *
165     * The default implementation interprets the string as a encoded compressed
166     * Java class, unpacks and decodes it with the Utility.decode() method, and
167     * parses the resulting byte array and returns the resulting JavaClass object.
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                Constants.CONSTANT_Class);
187        final ConstantUtf8 name = (ConstantUtf8) cp.getConstant(cl.getNameIndex(),
188                Constants.CONSTANT_Utf8);
189        name.setBytes(class_name.replace('.', '/'));
190        return clazz;
191    }
192}