1 /*
2 * Licensed to the Apache Software Foundation (ASF) under one or more
3 * contributor license agreements. See the NOTICE file distributed with
4 * this work for additional information regarding copyright ownership.
5 * The ASF licenses this file to You under the Apache license, Version 2.0
6 * (the "License"); you may not use this file except in compliance with
7 * the License. You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the license for the specific language governing permissions and
15 * limitations under the license.
16 */
17 package org.apache.logging.log4j.util;
18
19 import java.io.IOException;
20 import java.lang.reflect.InvocationTargetException;
21 import java.net.URL;
22 import java.security.AccessController;
23 import java.security.PrivilegedAction;
24 import java.util.Collection;
25 import java.util.Enumeration;
26 import java.util.LinkedHashSet;
27 import java.util.Objects;
28
29 /**
30 * <em>Consider this class private.</em> Utility class for ClassLoaders.
31 *
32 * @see ClassLoader
33 * @see RuntimePermission
34 * @see Thread#getContextClassLoader()
35 * @see ClassLoader#getSystemClassLoader()
36 */
37 public final class LoaderUtil {
38
39 private static final ClassLoader[] EMPTY_CLASS_LOADER_ARRAY = {};
40
41 /**
42 * System property to set to ignore the thread context ClassLoader.
43 *
44 * @since 2.1
45 */
46 public static final String IGNORE_TCCL_PROPERTY = "log4j.ignoreTCL";
47
48 private static final SecurityManager SECURITY_MANAGER = System.getSecurityManager();
49
50 // this variable must be lazily loaded; otherwise, we get a nice circular class loading problem where LoaderUtil
51 // wants to use PropertiesUtil, but then PropertiesUtil wants to use LoaderUtil.
52 private static Boolean ignoreTCCL;
53
54 private static final boolean GET_CLASS_LOADER_DISABLED;
55
56 private static final PrivilegedAction<ClassLoader> TCCL_GETTER = new ThreadContextClassLoaderGetter();
57
58 static {
59 if (SECURITY_MANAGER != null) {
60 boolean getClassLoaderDisabled;
61 try {
62 SECURITY_MANAGER.checkPermission(new RuntimePermission("getClassLoader"));
63 getClassLoaderDisabled = false;
64 } catch (final SecurityException ignored) {
65 getClassLoaderDisabled = true;
66 }
67 GET_CLASS_LOADER_DISABLED = getClassLoaderDisabled;
68 } else {
69 GET_CLASS_LOADER_DISABLED = false;
70 }
71 }
72
73 private LoaderUtil() {
74 }
75
76 /**
77 * Gets the current Thread ClassLoader. Returns the system ClassLoader if the TCCL is {@code null}. If the system
78 * ClassLoader is {@code null} as well, then the ClassLoader for this class is returned. If running with a
79 * {@link SecurityManager} that does not allow access to the Thread ClassLoader or system ClassLoader, then the
80 * ClassLoader for this class is returned.
81 *
82 * @return the current ThreadContextClassLoader.
83 */
84 public static ClassLoader getThreadContextClassLoader() {
85 if (GET_CLASS_LOADER_DISABLED) {
86 // we can at least get this class's ClassLoader regardless of security context
87 // however, if this is null, there's really no option left at this point
88 return LoaderUtil.class.getClassLoader();
89 }
90 return SECURITY_MANAGER == null ? TCCL_GETTER.run() : AccessController.doPrivileged(TCCL_GETTER);
91 }
92
93 /**
94 *
95 */
96 private static class ThreadContextClassLoaderGetter implements PrivilegedAction<ClassLoader> {
97 @Override
98 public ClassLoader run() {
99 final ClassLoader cl = Thread.currentThread().getContextClassLoader();
100 if (cl != null) {
101 return cl;
102 }
103 final ClassLoader ccl = LoaderUtil.class.getClassLoader();
104 return ccl == null && !GET_CLASS_LOADER_DISABLED ? ClassLoader.getSystemClassLoader() : ccl;
105 }
106 }
107
108 public static ClassLoader[] getClassLoaders() {
109 final Collection<ClassLoader> classLoaders = new LinkedHashSet<>();
110 final ClassLoader tcl = getThreadContextClassLoader();
111 if (tcl != null) {
112 classLoaders.add(tcl);
113 }
114 accumulateClassLoaders(LoaderUtil.class.getClassLoader(), classLoaders);
115 accumulateClassLoaders(tcl == null ? null : tcl.getParent(), classLoaders);
116 final ClassLoader systemClassLoader = ClassLoader.getSystemClassLoader();
117 if (systemClassLoader != null) {
118 classLoaders.add(systemClassLoader);
119 }
120 return classLoaders.toArray(EMPTY_CLASS_LOADER_ARRAY);
121 }
122
123 /**
124 * Adds the provided loader to the loaders collection, and traverses up the tree until either a null
125 * value or a classloader which has already been added is encountered.
126 */
127 private static void accumulateClassLoaders(ClassLoader loader, Collection<ClassLoader> loaders) {
128 // Some implementations may use null to represent the bootstrap class loader.
129 if (loader != null && loaders.add(loader)) {
130 accumulateClassLoaders(loader.getParent(), loaders);
131 }
132 }
133
134 /**
135 * Determines if a named Class can be loaded or not.
136 *
137 * @param className The class name.
138 * @return {@code true} if the class could be found or {@code false} otherwise.
139 * @since 2.7
140 */
141 public static boolean isClassAvailable(final String className) {
142 try {
143 final Class<?> clazz = loadClass(className);
144 return clazz != null;
145 } catch (final ClassNotFoundException | LinkageError e) {
146 return false;
147 } catch (final Throwable e) {
148 LowLevelLogUtil.logException("Unknown error checking for existence of class: " + className, e);
149 return false;
150 }
151 }
152
153 /**
154 * Loads a class by name. This method respects the {@link #IGNORE_TCCL_PROPERTY} Log4j property. If this property is
155 * specified and set to anything besides {@code false}, then the default ClassLoader will be used.
156 *
157 * @param className The class name.
158 * @return the Class for the given name.
159 * @throws ClassNotFoundException if the specified class name could not be found
160 * @since 2.1
161 */
162 public static Class<?> loadClass(final String className) throws ClassNotFoundException {
163 if (isIgnoreTccl()) {
164 return Class.forName(className);
165 }
166 try {
167 ClassLoader tccl = getThreadContextClassLoader();
168 if (tccl != null) {
169 return tccl.loadClass(className);
170 }
171 } catch (final Throwable ignored) {
172 }
173 return Class.forName(className);
174 }
175
176 /**
177 * Loads and instantiates a Class using the default constructor.
178 *
179 * @param <T> the type of the class modeled by the {@code Class} object.
180 * @param clazz The class.
181 * @return new instance of the class.
182 * @throws IllegalAccessException if the class can't be instantiated through a public constructor
183 * @throws InstantiationException if there was an exception whilst instantiating the class
184 * @throws InvocationTargetException if there was an exception whilst constructing the class
185 * @since 2.7
186 */
187 public static <T> T newInstanceOf(final Class<T> clazz)
188 throws InstantiationException, IllegalAccessException, InvocationTargetException {
189 try {
190 return clazz.getConstructor().newInstance();
191 } catch (final NoSuchMethodException ignored) {
192 // FIXME: looking at the code for Class.newInstance(), this seems to do the same thing as above
193 return clazz.newInstance();
194 }
195 }
196
197 /**
198 * Loads and instantiates a Class using the default constructor.
199 *
200 * @param className The class name.
201 * @return new instance of the class.
202 * @throws ClassNotFoundException if the class isn't available to the usual ClassLoaders
203 * @throws IllegalAccessException if the class can't be instantiated through a public constructor
204 * @throws InstantiationException if there was an exception whilst instantiating the class
205 * @throws InvocationTargetException if there was an exception whilst constructing the class
206 * @since 2.1
207 */
208 @SuppressWarnings("unchecked")
209 public static <T> T newInstanceOf(final String className) throws ClassNotFoundException, IllegalAccessException,
210 InstantiationException, InvocationTargetException {
211 return newInstanceOf((Class<T>) loadClass(className));
212 }
213
214 /**
215 * Loads and instantiates a derived class using its default constructor.
216 *
217 * @param className The class name.
218 * @param clazz The class to cast it to.
219 * @param <T> The type of the class to check.
220 * @return new instance of the class cast to {@code T}
221 * @throws ClassNotFoundException if the class isn't available to the usual ClassLoaders
222 * @throws IllegalAccessException if the class can't be instantiated through a public constructor
223 * @throws InstantiationException if there was an exception whilst instantiating the class
224 * @throws InvocationTargetException if there was an exception whilst constructing the class
225 * @throws ClassCastException if the constructed object isn't type compatible with {@code T}
226 * @since 2.1
227 */
228 public static <T> T newCheckedInstanceOf(final String className, final Class<T> clazz)
229 throws ClassNotFoundException, InvocationTargetException, InstantiationException,
230 IllegalAccessException {
231 return clazz.cast(newInstanceOf(className));
232 }
233
234 /**
235 * Loads and instantiates a class given by a property name.
236 *
237 * @param propertyName The property name to look up a class name for.
238 * @param clazz The class to cast it to.
239 * @param <T> The type to cast it to.
240 * @return new instance of the class given in the property or {@code null} if the property was unset.
241 * @throws ClassNotFoundException if the class isn't available to the usual ClassLoaders
242 * @throws IllegalAccessException if the class can't be instantiated through a public constructor
243 * @throws InstantiationException if there was an exception whilst instantiating the class
244 * @throws InvocationTargetException if there was an exception whilst constructing the class
245 * @throws ClassCastException if the constructed object isn't type compatible with {@code T}
246 * @since 2.5
247 */
248 public static <T> T newCheckedInstanceOfProperty(final String propertyName, final Class<T> clazz)
249 throws ClassNotFoundException, InvocationTargetException, InstantiationException,
250 IllegalAccessException {
251 final String className = PropertiesUtil.getProperties().getStringProperty(propertyName);
252 if (className == null) {
253 return null;
254 }
255 return newCheckedInstanceOf(className, clazz);
256 }
257
258 private static boolean isIgnoreTccl() {
259 // we need to lazily initialize this, but concurrent access is not an issue
260 if (ignoreTCCL == null) {
261 final String ignoreTccl = PropertiesUtil.getProperties().getStringProperty(IGNORE_TCCL_PROPERTY, null);
262 ignoreTCCL = ignoreTccl != null && !"false".equalsIgnoreCase(ignoreTccl.trim());
263 }
264 return ignoreTCCL;
265 }
266
267 /**
268 * Finds classpath {@linkplain URL resources}.
269 *
270 * @param resource the name of the resource to find.
271 * @return a Collection of URLs matching the resource name. If no resources could be found, then this will be empty.
272 * @since 2.1
273 */
274 public static Collection<URL> findResources(final String resource) {
275 final Collection<UrlResource> urlResources = findUrlResources(resource);
276 final Collection<URL> resources = new LinkedHashSet<>(urlResources.size());
277 for (final UrlResource urlResource : urlResources) {
278 resources.add(urlResource.getUrl());
279 }
280 return resources;
281 }
282
283 static Collection<UrlResource> findUrlResources(final String resource) {
284 // @formatter:off
285 final ClassLoader[] candidates = {
286 getThreadContextClassLoader(),
287 LoaderUtil.class.getClassLoader(),
288 GET_CLASS_LOADER_DISABLED ? null : ClassLoader.getSystemClassLoader()};
289 // @formatter:on
290 final Collection<UrlResource> resources = new LinkedHashSet<>();
291 for (final ClassLoader cl : candidates) {
292 if (cl != null) {
293 try {
294 final Enumeration<URL> resourceEnum = cl.getResources(resource);
295 while (resourceEnum.hasMoreElements()) {
296 resources.add(new UrlResource(cl, resourceEnum.nextElement()));
297 }
298 } catch (final IOException e) {
299 LowLevelLogUtil.logException(e);
300 }
301 }
302 }
303 return resources;
304 }
305
306 /**
307 * {@link URL} and {@link ClassLoader} pair.
308 */
309 static class UrlResource {
310 private final ClassLoader classLoader;
311 private final URL url;
312
313 UrlResource(final ClassLoader classLoader, final URL url) {
314 this.classLoader = classLoader;
315 this.url = url;
316 }
317
318 public ClassLoader getClassLoader() {
319 return classLoader;
320 }
321
322 public URL getUrl() {
323 return url;
324 }
325
326 @Override
327 public boolean equals(final Object o) {
328 if (this == o) {
329 return true;
330 }
331 if (o == null || getClass() != o.getClass()) {
332 return false;
333 }
334
335 final UrlResource that = (UrlResource) o;
336
337 if (classLoader != null ? !classLoader.equals(that.classLoader) : that.classLoader != null) {
338 return false;
339 }
340 if (url != null ? !url.equals(that.url) : that.url != null) {
341 return false;
342 }
343
344 return true;
345 }
346
347 @Override
348 public int hashCode() {
349 return Objects.hashCode(classLoader) + Objects.hashCode(url);
350 }
351 }
352 }
353