001/*
002 * Copyright 2002-2019 the original author or authors.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *      https://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package org.springframework.instrument.classloading;
018
019import java.io.IOException;
020import java.io.InputStream;
021import java.lang.instrument.ClassFileTransformer;
022import java.lang.instrument.IllegalClassFormatException;
023import java.net.URL;
024import java.util.Enumeration;
025import java.util.HashMap;
026import java.util.LinkedList;
027import java.util.List;
028import java.util.Map;
029
030import org.springframework.core.DecoratingClassLoader;
031import org.springframework.lang.Nullable;
032import org.springframework.util.Assert;
033import org.springframework.util.FileCopyUtils;
034import org.springframework.util.StringUtils;
035
036/**
037 * ClassLoader decorator that shadows an enclosing ClassLoader,
038 * applying registered transformers to all affected classes.
039 *
040 * @author Rob Harrop
041 * @author Juergen Hoeller
042 * @author Costin Leau
043 * @since 2.0
044 * @see #addTransformer
045 * @see org.springframework.core.OverridingClassLoader
046 */
047public class ShadowingClassLoader extends DecoratingClassLoader {
048
049        /** Packages that are excluded by default. */
050        public static final String[] DEFAULT_EXCLUDED_PACKAGES =
051                        new String[] {"java.", "javax.", "jdk.", "sun.", "oracle.", "com.sun.", "com.ibm.", "COM.ibm.",
052                                        "org.w3c.", "org.xml.", "org.dom4j.", "org.eclipse", "org.aspectj.", "net.sf.cglib",
053                                        "org.springframework.cglib", "org.apache.xerces.", "org.apache.commons.logging."};
054
055
056        private final ClassLoader enclosingClassLoader;
057
058        private final List<ClassFileTransformer> classFileTransformers = new LinkedList<>();
059
060        private final Map<String, Class<?>> classCache = new HashMap<>();
061
062
063        /**
064         * Create a new ShadowingClassLoader, decorating the given ClassLoader,
065         * applying {@link #DEFAULT_EXCLUDED_PACKAGES}.
066         * @param enclosingClassLoader the ClassLoader to decorate
067         * @see #ShadowingClassLoader(ClassLoader, boolean)
068         */
069        public ShadowingClassLoader(ClassLoader enclosingClassLoader) {
070                this(enclosingClassLoader, true);
071        }
072
073        /**
074         * Create a new ShadowingClassLoader, decorating the given ClassLoader.
075         * @param enclosingClassLoader the ClassLoader to decorate
076         * @param defaultExcludes whether to apply {@link #DEFAULT_EXCLUDED_PACKAGES}
077         * @since 4.3.8
078         */
079        public ShadowingClassLoader(ClassLoader enclosingClassLoader, boolean defaultExcludes) {
080                Assert.notNull(enclosingClassLoader, "Enclosing ClassLoader must not be null");
081                this.enclosingClassLoader = enclosingClassLoader;
082                if (defaultExcludes) {
083                        for (String excludedPackage : DEFAULT_EXCLUDED_PACKAGES) {
084                                excludePackage(excludedPackage);
085                        }
086                }
087        }
088
089
090        /**
091         * Add the given ClassFileTransformer to the list of transformers that this
092         * ClassLoader will apply.
093         * @param transformer the ClassFileTransformer
094         */
095        public void addTransformer(ClassFileTransformer transformer) {
096                Assert.notNull(transformer, "Transformer must not be null");
097                this.classFileTransformers.add(transformer);
098        }
099
100        /**
101         * Copy all ClassFileTransformers from the given ClassLoader to the list of
102         * transformers that this ClassLoader will apply.
103         * @param other the ClassLoader to copy from
104         */
105        public void copyTransformers(ShadowingClassLoader other) {
106                Assert.notNull(other, "Other ClassLoader must not be null");
107                this.classFileTransformers.addAll(other.classFileTransformers);
108        }
109
110
111        @Override
112        public Class<?> loadClass(String name) throws ClassNotFoundException {
113                if (shouldShadow(name)) {
114                        Class<?> cls = this.classCache.get(name);
115                        if (cls != null) {
116                                return cls;
117                        }
118                        return doLoadClass(name);
119                }
120                else {
121                        return this.enclosingClassLoader.loadClass(name);
122                }
123        }
124
125        /**
126         * Determine whether the given class should be excluded from shadowing.
127         * @param className the name of the class
128         * @return whether the specified class should be shadowed
129         */
130        private boolean shouldShadow(String className) {
131                return (!className.equals(getClass().getName()) && !className.endsWith("ShadowingClassLoader") &&
132                                isEligibleForShadowing(className));
133        }
134
135        /**
136         * Determine whether the specified class is eligible for shadowing
137         * by this class loader.
138         * @param className the class name to check
139         * @return whether the specified class is eligible
140         * @see #isExcluded
141         */
142        protected boolean isEligibleForShadowing(String className) {
143                return !isExcluded(className);
144        }
145
146
147        private Class<?> doLoadClass(String name) throws ClassNotFoundException {
148                String internalName = StringUtils.replace(name, ".", "/") + ".class";
149                InputStream is = this.enclosingClassLoader.getResourceAsStream(internalName);
150                if (is == null) {
151                        throw new ClassNotFoundException(name);
152                }
153                try {
154                        byte[] bytes = FileCopyUtils.copyToByteArray(is);
155                        bytes = applyTransformers(name, bytes);
156                        Class<?> cls = defineClass(name, bytes, 0, bytes.length);
157                        // Additional check for defining the package, if not defined yet.
158                        if (cls.getPackage() == null) {
159                                int packageSeparator = name.lastIndexOf('.');
160                                if (packageSeparator != -1) {
161                                        String packageName = name.substring(0, packageSeparator);
162                                        definePackage(packageName, null, null, null, null, null, null, null);
163                                }
164                        }
165                        this.classCache.put(name, cls);
166                        return cls;
167                }
168                catch (IOException ex) {
169                        throw new ClassNotFoundException("Cannot load resource for class [" + name + "]", ex);
170                }
171        }
172
173        private byte[] applyTransformers(String name, byte[] bytes) {
174                String internalName = StringUtils.replace(name, ".", "/");
175                try {
176                        for (ClassFileTransformer transformer : this.classFileTransformers) {
177                                byte[] transformed = transformer.transform(this, internalName, null, null, bytes);
178                                bytes = (transformed != null ? transformed : bytes);
179                        }
180                        return bytes;
181                }
182                catch (IllegalClassFormatException ex) {
183                        throw new IllegalStateException(ex);
184                }
185        }
186
187
188        @Override
189        public URL getResource(String name) {
190                return this.enclosingClassLoader.getResource(name);
191        }
192
193        @Override
194        @Nullable
195        public InputStream getResourceAsStream(String name) {
196                return this.enclosingClassLoader.getResourceAsStream(name);
197        }
198
199        @Override
200        public Enumeration<URL> getResources(String name) throws IOException {
201                return this.enclosingClassLoader.getResources(name);
202        }
203
204}