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.util.Hashtable;
022
023import org.apache.bcel.Constants;
024import org.apache.bcel.classfile.ClassParser;
025import org.apache.bcel.classfile.ConstantClass;
026import org.apache.bcel.classfile.ConstantPool;
027import org.apache.bcel.classfile.ConstantUtf8;
028import org.apache.bcel.classfile.JavaClass;
029import org.apache.bcel.classfile.Utility;
030
031/**
032 * <p>Drop in replacement for the standard class loader of the JVM. You can use it
033 * in conjunction with the JavaWrapper to dynamically modify/create classes
034 * as they're requested.</p>
035 *
036 * <p>This class loader recognizes special requests in a distinct
037 * format, i.e., when the name of the requested class contains with
038 * "$$BCEL$$" it calls the createClass() method with that name
039 * (everything bevor the $$BCEL$$ is considered to be the package
040 * name. You can subclass the class loader and override that
041 * method. "Normal" classes class can be modified by overriding the
042 * modifyClass() method which is called just before defineClass().</p>
043 *
044 * <p>There may be a number of packages where you have to use the
045 * default class loader (which may also be faster). You can define the
046 * set of packages where to use the system class loader in the
047 * constructor. The default value contains "java.", "sun.",
048 * "javax."</p>
049 *
050 * @version $Id: ClassLoader.html 898356 2014-02-18 05:44:40Z ggregory $
051 * @author  <A HREF="mailto:m.dahm@gmx.de">M. Dahm</A>
052 * @see JavaWrapper
053 * @see ClassPath
054 */
055public class ClassLoader extends java.lang.ClassLoader {
056
057    public static final String[] DEFAULT_IGNORED_PACKAGES = {
058            "java.", "javax.", "sun."
059    };
060    private Hashtable<String, Class<?>> classes = new Hashtable<String, Class<?>>(); // Hashtable is synchronized thus thread-safe
061    private String[] ignored_packages;
062    private Repository repository = SyntheticRepository.getInstance();
063
064
065    /** Ignored packages are by default ( "java.", "sun.",
066     * "javax."), i.e. loaded by system class loader
067     */
068    public ClassLoader() {
069        this(DEFAULT_IGNORED_PACKAGES);
070    }
071
072
073    /** @param deferTo delegate class loader to use for ignored packages
074     */
075    public ClassLoader(java.lang.ClassLoader deferTo) {
076        super(deferTo);
077        this.ignored_packages = DEFAULT_IGNORED_PACKAGES;
078        this.repository = new ClassLoaderRepository(deferTo);
079    }
080
081
082    /** @param ignored_packages classes contained in these packages will be loaded
083     * with the system class loader
084     */
085    public ClassLoader(String[] ignored_packages) {
086        this.ignored_packages = ignored_packages;
087    }
088
089
090    /** @param ignored_packages classes contained in these packages will be loaded
091     * with the system class loader
092     * @param deferTo delegate class loader to use for ignored packages
093     */
094    public ClassLoader(java.lang.ClassLoader deferTo, String[] ignored_packages) {
095        this(ignored_packages);
096        this.repository = new ClassLoaderRepository(deferTo);
097    }
098
099    @Override
100    protected Class<?> loadClass( String class_name, boolean resolve ) throws ClassNotFoundException {
101        Class<?> cl = null;
102        /* First try: lookup hash table.
103         */
104        if ((cl = classes.get(class_name)) == null) {
105            /* Second try: Load system class using system class loader. You better
106             * don't mess around with them.
107             */
108            for (String ignored_package : ignored_packages) {
109                if (class_name.startsWith(ignored_package)) {
110                    cl = getParent().loadClass(class_name);
111                    break;
112                }
113            }
114            if (cl == null) {
115                JavaClass clazz = null;
116                /* Third try: Special request?
117                 */
118                if (class_name.indexOf("$$BCEL$$") >= 0) {
119                    clazz = createClass(class_name);
120                } else { // Fourth try: Load classes via repository
121                    if ((clazz = repository.loadClass(class_name)) != null) {
122                        clazz = modifyClass(clazz);
123                    } else {
124                        throw new ClassNotFoundException(class_name);
125                    }
126                }
127                if (clazz != null) {
128                    byte[] bytes = clazz.getBytes();
129                    cl = defineClass(class_name, bytes, 0, bytes.length);
130                } else {
131                    cl = Class.forName(class_name);
132                }
133            }
134            if (resolve) {
135                resolveClass(cl);
136            }
137        }
138        classes.put(class_name, cl);
139        return cl;
140    }
141
142
143    /** Override this method if you want to alter a class before it gets actually
144     * loaded. Does nothing by default.
145     */
146    protected JavaClass modifyClass( JavaClass clazz ) {
147        return clazz;
148    }
149
150
151    /** 
152     * Override this method to create you own classes on the fly. The
153     * name contains the special token $$BCEL$$. Everything before that
154     * token is consddered to be a package name. You can encode you own
155     * arguments into the subsequent string. You must regard however not
156     * to use any "illegal" characters, i.e., characters that may not
157     * appear in a Java class name too<br>
158     *
159     * The default implementation interprets the string as a encoded compressed
160     * Java class, unpacks and decodes it with the Utility.decode() method, and
161     * parses the resulting byte array and returns the resulting JavaClass object.
162     *
163     * @param class_name compressed byte code with "$$BCEL$$" in it
164     */
165    protected JavaClass createClass( String class_name ) {
166        int index = class_name.indexOf("$$BCEL$$");
167        String real_name = class_name.substring(index + 8);
168        JavaClass clazz = null;
169        try {
170            byte[] bytes = Utility.decode(real_name, true);
171            ClassParser parser = new ClassParser(new ByteArrayInputStream(bytes), "foo");
172            clazz = parser.parse();
173        } catch (Throwable e) {
174            e.printStackTrace();
175            return null;
176        }
177        // Adapt the class name to the passed value
178        ConstantPool cp = clazz.getConstantPool();
179        ConstantClass cl = (ConstantClass) cp.getConstant(clazz.getClassNameIndex(),
180                Constants.CONSTANT_Class);
181        ConstantUtf8 name = (ConstantUtf8) cp.getConstant(cl.getNameIndex(),
182                Constants.CONSTANT_Utf8);
183        name.setBytes(class_name.replace('.', '/'));
184        return clazz;
185    }
186}