1 /*
2 * Copyright (c) 2013, 2025, Oracle and/or its affiliates. All rights reserved.
3 * Copyright (c) 2019, Azul Systems, Inc. All rights reserved.
4 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5 *
6 * This code is free software; you can redistribute it and/or modify it
7 * under the terms of the GNU General Public License version 2 only, as
8 * published by the Free Software Foundation. Oracle designates this
9 * particular file as subject to the "Classpath" exception as provided
10 * by Oracle in the LICENSE file that accompanied this code.
11 *
12 * This code is distributed in the hope that it will be useful, but WITHOUT
13 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
15 * version 2 for more details (a copy is included in the LICENSE file that
16 * accompanied this code).
17 *
18 * You should have received a copy of the GNU General Public License version
19 * 2 along with this work; if not, write to the Free Software Foundation,
20 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
21 *
22 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
23 * or visit www.oracle.com if you need additional information or have any
24 * questions.
25 */
26
27 package java.lang;
28
29 import java.io.InputStream;
30 import java.io.IOException;
31 import java.io.UncheckedIOException;
32 import java.io.File;
33 import java.lang.foreign.Arena;
34 import java.lang.reflect.Constructor;
35 import java.lang.reflect.InvocationTargetException;
36 import java.net.URL;
37 import java.nio.ByteBuffer;
38 import java.security.CodeSource;
39 import java.security.ProtectionDomain;
40 import java.security.cert.Certificate;
41 import java.util.ArrayList;
42 import java.util.Collections;
43 import java.util.Enumeration;
44 import java.util.HashMap;
45 import java.util.Map;
46 import java.util.NoSuchElementException;
47 import java.util.Objects;
48 import java.util.Set;
49 import java.util.Spliterator;
50 import java.util.Spliterators;
51 import java.util.WeakHashMap;
52 import java.util.concurrent.ConcurrentHashMap;
53 import java.util.function.Supplier;
54 import java.util.stream.Stream;
55 import java.util.stream.StreamSupport;
56
57 import jdk.internal.access.SharedSecrets;
58 import jdk.internal.loader.BootLoader;
59 import jdk.internal.loader.BuiltinClassLoader;
60 import jdk.internal.loader.ClassLoaders;
61 import jdk.internal.loader.NativeLibrary;
62 import jdk.internal.loader.NativeLibraries;
63 import jdk.internal.perf.PerfCounter;
64 import jdk.internal.misc.CDS;
65 import jdk.internal.misc.Unsafe;
66 import jdk.internal.misc.VM;
67 import jdk.internal.reflect.CallerSensitive;
68 import jdk.internal.reflect.CallerSensitiveAdapter;
69 import jdk.internal.reflect.Reflection;
70 import jdk.internal.util.StaticProperty;
71 import jdk.internal.vm.annotation.AOTRuntimeSetup;
72 import jdk.internal.vm.annotation.AOTSafeClassInitializer;
73
74 /**
75 * A class loader is an object that is responsible for loading classes. The
76 * class {@code ClassLoader} is an abstract class. Given the <a
77 * href="#binary-name">binary name</a> of a class, a class loader should attempt to
78 * locate or generate data that constitutes a definition for the class. A
79 * typical strategy is to transform the name into a file name and then read a
80 * "class file" of that name from a file system.
81 *
82 * <p> Every {@link java.lang.Class Class} object contains a {@link
83 * Class#getClassLoader() reference} to the {@code ClassLoader} that defined
84 * it.
85 *
86 * <p> {@code Class} objects for array classes are not created by class
87 * loaders, but are created automatically as required by the Java runtime.
88 * The class loader for an array class, as returned by {@link
89 * Class#getClassLoader()} is the same as the class loader for its element
90 * type; if the element type is a primitive type, then the array class has no
91 * class loader.
92 *
93 * <p> Applications implement subclasses of {@code ClassLoader} in order to
94 * extend the manner in which the Java virtual machine dynamically loads
95 * classes.
96 *
97 * <p> In addition to loading classes, a class loader is also responsible for
98 * locating resources. A resource is some data (a "{@code .class}" file,
99 * configuration data, or an image for example) that is identified with an
100 * abstract '/'-separated path name. Resources are typically packaged with an
101 * application or library so that they can be located by code in the
102 * application or library. In some cases, the resources are included so that
103 * they can be located by other libraries.
104 *
105 * <p> The {@code ClassLoader} class uses a delegation model to search for
106 * classes and resources. Each instance of {@code ClassLoader} has an
107 * associated parent class loader. When requested to find a class or
108 * resource, a {@code ClassLoader} instance will usually delegate the search
109 * for the class or resource to its parent class loader before attempting to
110 * find the class or resource itself.
111 *
112 * <p> Class loaders that support concurrent loading of classes are known as
113 * <em>{@linkplain #isRegisteredAsParallelCapable() parallel capable}</em> class
114 * loaders and are required to register themselves at their class initialization
115 * time by invoking the {@link
116 * #registerAsParallelCapable ClassLoader.registerAsParallelCapable}
117 * method. Note that the {@code ClassLoader} class is registered as parallel
118 * capable by default. However, its subclasses still need to register themselves
119 * if they are parallel capable.
120 * In environments in which the delegation model is not strictly
121 * hierarchical, class loaders need to be parallel capable, otherwise class
122 * loading can lead to deadlocks because the loader lock is held for the
123 * duration of the class loading process (see {@link #loadClass
124 * loadClass} methods).
125 *
126 * <h2> <a id="builtinLoaders">Run-time Built-in Class Loaders</a></h2>
127 *
128 * The Java run-time has the following built-in class loaders:
129 *
130 * <ul>
131 * <li><p>Bootstrap class loader.
132 * It is the virtual machine's built-in class loader, typically represented
133 * as {@code null}, and does not have a parent.</li>
134 * <li><p>{@linkplain #getPlatformClassLoader() Platform class loader}.
135 * The platform class loader is responsible for loading the
136 * <em>platform classes</em>. Platform classes include Java SE platform APIs,
137 * their implementation classes and JDK-specific run-time classes that are
138 * defined by the platform class loader or its ancestors.
139 * The platform class loader can be used as the parent of a {@code ClassLoader}
140 * instance.
141 * <p> To allow for upgrading/overriding of modules defined to the platform
142 * class loader, and where upgraded modules read modules defined to class
143 * loaders other than the platform class loader and its ancestors, then
144 * the platform class loader may have to delegate to other class loaders,
145 * the application class loader for example.
146 * In other words, classes in named modules defined to class loaders
147 * other than the platform class loader and its ancestors may be visible
148 * to the platform class loader. </li>
149 * <li><p>{@linkplain #getSystemClassLoader() System class loader}.
150 * It is also known as <em>application class loader</em> and is distinct
151 * from the platform class loader.
152 * The system class loader is typically used to define classes on the
153 * application class path, module path, and JDK-specific tools.
154 * The platform class loader is the parent or an ancestor of the system class
155 * loader, so the system class loader can load platform classes by delegating
156 * to its parent.</li>
157 * </ul>
158 *
159 * <p> Normally, the Java virtual machine loads classes from the local file
160 * system in a platform-dependent manner.
161 * However, some classes may not originate from a file; they may originate
162 * from other sources, such as the network, or they could be constructed by an
163 * application. The method {@link #defineClass(String, byte[], int, int)
164 * defineClass} converts an array of bytes into an instance of class
165 * {@code Class}. Instances of this newly defined class can be created using
166 * {@link Class#newInstance Class.newInstance}.
167 *
168 * <p> The methods and constructors of objects created by a class loader may
169 * reference other classes. To determine the class(es) referred to, the Java
170 * virtual machine invokes the {@link #loadClass loadClass} method of
171 * the class loader that originally created the class.
172 *
173 * <p> For example, an application could create a network class loader to
174 * download class files from a server. Sample code might look like:
175 *
176 * <blockquote><pre>
177 * ClassLoader loader = new NetworkClassLoader(host, port);
178 * Object main = loader.loadClass("Main", true).newInstance();
179 * . . .
180 * </pre></blockquote>
181 *
182 * <p> The network class loader subclass must define the methods {@link
183 * #findClass findClass} and {@code loadClassData} to load a class
184 * from the network. Once it has downloaded the bytes that make up the class,
185 * it should use the method {@link #defineClass defineClass} to
186 * create a class instance. A sample implementation is:
187 *
188 * <blockquote><pre>
189 * class NetworkClassLoader extends ClassLoader {
190 * String host;
191 * int port;
192 *
193 * public Class findClass(String name) {
194 * byte[] b = loadClassData(name);
195 * return defineClass(name, b, 0, b.length);
196 * }
197 *
198 * private byte[] loadClassData(String name) {
199 * // load the class data from the connection
200 * . . .
201 * }
202 * }
203 * </pre></blockquote>
204 *
205 * <h3> <a id="binary-name">Binary names</a> </h3>
206 *
207 * <p> Any class name provided as a {@code String} parameter to methods in
208 * {@code ClassLoader} must be a binary name as defined by
209 * <cite>The Java Language Specification</cite>.
210 *
211 * <p> Examples of valid class names include:
212 * <blockquote><pre>
213 * "java.lang.String"
214 * "javax.swing.JSpinner$DefaultEditor"
215 * "java.security.KeyStore$Builder$FileBuilder$1"
216 * "java.net.URLClassLoader$3$1"
217 * </pre></blockquote>
218 *
219 * <p> Any package name provided as a {@code String} parameter to methods in
220 * {@code ClassLoader} must be either the empty string (denoting an unnamed package)
221 * or a fully qualified name as defined by
222 * <cite>The Java Language Specification</cite>.
223 *
224 * @jls 6.7 Fully Qualified Names and Canonical Names
225 * @jls 13.1 The Form of a Binary
226 * @see #resolveClass(Class)
227 * @since 1.0
228 */
229 @AOTSafeClassInitializer
230 public abstract class ClassLoader {
231
232 private static native void registerNatives();
233 static {
234 runtimeSetup();
235 }
236
237 @AOTRuntimeSetup
238 private static void runtimeSetup() {
239 registerNatives();
240 }
241
242 // The parent class loader for delegation
243 // Note: VM hardcoded the offset of this field, thus all new fields
244 // must be added *after* it.
245 private final ClassLoader parent;
246
247 // class loader name
248 private final String name;
249
250 // the unnamed module for this ClassLoader
251 private final Module unnamedModule;
252
253 // a string for exception message printing
254 private final String nameAndId;
255
256 /**
257 * Encapsulates the set of parallel capable loader types.
258 */
259 private static class ParallelLoaders {
260 private ParallelLoaders() {}
261
262 // the set of parallel capable loader types
263 private static final Set<Class<? extends ClassLoader>> loaderTypes =
264 Collections.newSetFromMap(new WeakHashMap<>());
265 static {
266 synchronized (loaderTypes) { loaderTypes.add(ClassLoader.class); }
267 }
268
269 /**
270 * Registers the given class loader type as parallel capable.
271 * Returns {@code true} is successfully registered; {@code false} if
272 * loader's super class is not registered.
273 */
274 static boolean register(Class<? extends ClassLoader> c) {
275 synchronized (loaderTypes) {
276 if (loaderTypes.contains(c.getSuperclass())) {
277 // register the class loader as parallel capable
278 // if and only if all of its super classes are.
279 // Note: given current classloading sequence, if
280 // the immediate super class is parallel capable,
281 // all the super classes higher up must be too.
282 loaderTypes.add(c);
283 return true;
284 } else {
285 return false;
286 }
287 }
288 }
289
290 /**
291 * Returns {@code true} if the given class loader type is
292 * registered as parallel capable.
293 */
294 static boolean isRegistered(Class<? extends ClassLoader> c) {
295 synchronized (loaderTypes) {
296 return loaderTypes.contains(c);
297 }
298 }
299 }
300
301 // Maps class name to the corresponding lock object when the current
302 // class loader is parallel capable.
303 // Note: VM also uses this field to decide if the current class loader
304 // is parallel capable and the appropriate lock object for class loading.
305 private final ConcurrentHashMap<String, Object> parallelLockMap;
306
307 // Maps packages to certs
308 private final ConcurrentHashMap<String, Certificate[]> package2certs;
309
310 // Shared among all packages with unsigned classes
311 private static final Certificate[] nocerts = new Certificate[0];
312
313 // The classes loaded by this class loader. The only purpose of this table
314 // is to keep the classes from being GC'ed until the loader is GC'ed.
315 private final ArrayList<Class<?>> classes = new ArrayList<>();
316
317 // The "default" domain. Set as the default ProtectionDomain on newly
318 // created classes.
319 private final ProtectionDomain defaultDomain =
320 new ProtectionDomain(new CodeSource(null, (Certificate[]) null),
321 null, this, null);
322
323 // Invoked by the VM to record every loaded class with this loader.
324 void addClass(Class<?> c) {
325 synchronized (classes) {
326 classes.add(c);
327 }
328 }
329
330 // The packages defined in this class loader. Each package name is
331 // mapped to its corresponding NamedPackage object.
332 //
333 // The value is a Package object if ClassLoader::definePackage,
334 // Class::getPackage, ClassLoader::getDefinePackage(s) or
335 // Package::getPackage(s) method is called to define it.
336 // Otherwise, the value is a NamedPackage object.
337 private final ConcurrentHashMap<String, NamedPackage> packages
338 = new ConcurrentHashMap<>();
339
340 /*
341 * Returns a named package for the given module.
342 */
343 private NamedPackage getNamedPackage(String pn, Module m) {
344 NamedPackage p = packages.get(pn);
345 if (p == null) {
346 p = new NamedPackage(pn, m);
347
348 NamedPackage value = packages.putIfAbsent(pn, p);
349 if (value != null) {
350 // Package object already be defined for the named package
351 p = value;
352 // if definePackage is called by this class loader to define
353 // a package in a named module, this will return Package
354 // object of the same name. Package object may contain
355 // unexpected information but it does not impact the runtime.
356 // this assertion may be helpful for troubleshooting
357 assert value.module() == m;
358 }
359 }
360 return p;
361 }
362
363 private static Void checkCreateClassLoader() {
364 return checkCreateClassLoader(null);
365 }
366
367 private static Void checkCreateClassLoader(String name) {
368 if (name != null && name.isEmpty()) {
369 throw new IllegalArgumentException("name must be non-empty or null");
370 }
371 return null;
372 }
373
374 private ClassLoader(Void unused, String name, ClassLoader parent) {
375 this.name = name;
376 this.parent = parent;
377 this.unnamedModule = new Module(this);
378 if (ParallelLoaders.isRegistered(this.getClass())) {
379 parallelLockMap = new ConcurrentHashMap<>();
380 assertionLock = new Object();
381 } else {
382 // no finer-grained lock; lock on the classloader instance
383 parallelLockMap = null;
384 assertionLock = this;
385 }
386 this.package2certs = new ConcurrentHashMap<>();
387 this.nameAndId = nameAndId(this);
388 }
389
390 /**
391 * If the defining loader has a name explicitly set then
392 * '<loader-name>' @<id>
393 * If the defining loader has no name then
394 * <qualified-class-name> @<id>
395 * If it's built-in loader then omit `@<id>` as there is only one instance.
396 */
397 private static String nameAndId(ClassLoader ld) {
398 String nid = ld.getName() != null ? "\'" + ld.getName() + "\'"
399 : ld.getClass().getName();
400 if (!(ld instanceof BuiltinClassLoader)) {
401 String id = Integer.toHexString(System.identityHashCode(ld));
402 nid = nid + " @" + id;
403 }
404 return nid;
405 }
406
407 // Returns nameAndId string for exception message printing
408 String nameAndId() {
409 return nameAndId;
410 }
411
412 /**
413 * Creates a new class loader of the specified name and using the
414 * specified parent class loader for delegation.
415 *
416 * @apiNote If the parent is specified as {@code null} (for the
417 * bootstrap class loader) then there is no guarantee that all platform
418 * classes are visible.
419 *
420 * @param name class loader name; or {@code null} if not named
421 * @param parent the parent class loader
422 *
423 * @throws IllegalArgumentException if the given name is empty.
424 *
425 * @since 9
426 */
427 @SuppressWarnings("this-escape")
428 protected ClassLoader(String name, ClassLoader parent) {
429 this(checkCreateClassLoader(name), name, parent);
430 }
431
432 /**
433 * Creates a new class loader using the specified parent class loader for
434 * delegation.
435 *
436 * @apiNote If the parent is specified as {@code null} (for the
437 * bootstrap class loader) then there is no guarantee that all platform
438 * classes are visible.
439 *
440 * @param parent
441 * The parent class loader
442 *
443 * @since 1.2
444 */
445 @SuppressWarnings("this-escape")
446 protected ClassLoader(ClassLoader parent) {
447 this(checkCreateClassLoader(), null, parent);
448 }
449
450 /**
451 * Creates a new class loader using the {@code ClassLoader} returned by
452 * the method {@link #getSystemClassLoader()
453 * getSystemClassLoader()} as the parent class loader.
454 */
455 @SuppressWarnings("this-escape")
456 protected ClassLoader() {
457 this(checkCreateClassLoader(), null, getSystemClassLoader());
458 }
459
460 /**
461 * Returns the name of this class loader or {@code null} if
462 * this class loader is not named.
463 *
464 * @apiNote This method is non-final for compatibility. If this
465 * method is overridden, this method must return the same name
466 * as specified when this class loader was instantiated.
467 *
468 * @return name of this class loader; or {@code null} if
469 * this class loader is not named.
470 *
471 * @since 9
472 */
473 public String getName() {
474 return name;
475 }
476
477 // package-private used by StackTraceElement to avoid
478 // calling the overridable getName method
479 final String name() {
480 return name;
481 }
482
483 // -- Class --
484
485 /**
486 * Loads the class with the specified <a href="#binary-name">binary name</a>.
487 * This method searches for classes in the same manner as the {@link
488 * #loadClass(String, boolean)} method. It is invoked by the Java virtual
489 * machine to resolve class references. Invoking this method is equivalent
490 * to invoking {@link #loadClass(String, boolean) loadClass(name,
491 * false)}.
492 *
493 * @param name
494 * The <a href="#binary-name">binary name</a> of the class
495 *
496 * @return The resulting {@code Class} object
497 *
498 * @throws ClassNotFoundException
499 * If the class was not found
500 */
501 public Class<?> loadClass(String name) throws ClassNotFoundException {
502 return loadClass(name, false);
503 }
504
505 /**
506 * Loads the class with the specified <a href="#binary-name">binary name</a>. The
507 * default implementation of this method searches for classes in the
508 * following order:
509 *
510 * <ol>
511 *
512 * <li><p> Invoke {@link #findLoadedClass(String)} to check if the class
513 * has already been loaded. </p></li>
514 *
515 * <li><p> Invoke the {@link #loadClass(String) loadClass} method
516 * on the parent class loader. If the parent is {@code null} the class
517 * loader built into the virtual machine is used, instead. </p></li>
518 *
519 * <li><p> Invoke the {@link #findClass(String)} method to find the
520 * class. </p></li>
521 *
522 * </ol>
523 *
524 * <p> If the class was found using the above steps, and the
525 * {@code resolve} flag is true, this method will then invoke the {@link
526 * #resolveClass(Class)} method on the resulting {@code Class} object.
527 *
528 * <p> Subclasses of {@code ClassLoader} are encouraged to override {@link
529 * #findClass(String)}, rather than this method. </p>
530 *
531 * <p> Unless overridden, this method synchronizes on the result of
532 * {@link #getClassLoadingLock getClassLoadingLock} method
533 * during the entire class loading process.
534 *
535 * @param name
536 * The <a href="#binary-name">binary name</a> of the class
537 *
538 * @param resolve
539 * If {@code true} then resolve the class
540 *
541 * @return The resulting {@code Class} object
542 *
543 * @throws ClassNotFoundException
544 * If the class could not be found
545 */
546 protected Class<?> loadClass(String name, boolean resolve)
547 throws ClassNotFoundException
548 {
549 synchronized (getClassLoadingLock(name)) {
550 // First, check if the class has already been loaded
551 Class<?> c = findLoadedClass(name);
552 if (c == null) {
553 long t0 = System.nanoTime();
554 try {
555 if (parent != null) {
556 c = parent.loadClass(name, false);
557 } else {
558 c = findBootstrapClassOrNull(name);
559 }
560 } catch (ClassNotFoundException e) {
561 // ClassNotFoundException thrown if class not found
562 // from the non-null parent class loader
563 }
564
565 if (c == null) {
566 // If still not found, then invoke findClass in order
567 // to find the class.
568 long t1 = System.nanoTime();
569 c = findClass(name);
570
571 // this is the defining class loader; record the stats
572 PerfCounter.getParentDelegationTime().addTime(t1 - t0);
573 PerfCounter.getFindClassTime().addElapsedTimeFrom(t1);
574 PerfCounter.getFindClasses().increment();
575 }
576 }
577 if (resolve) {
578 resolveClass(c);
579 }
580 return c;
581 }
582 }
583
584 /**
585 * Loads the class with the specified <a href="#binary-name">binary name</a>
586 * in a module defined to this class loader. This method returns {@code null}
587 * if the class could not be found.
588 *
589 * @apiNote This method does not delegate to the parent class loader.
590 *
591 * @implSpec The default implementation of this method searches for classes
592 * in the following order:
593 *
594 * <ol>
595 * <li>Invoke {@link #findLoadedClass(String)} to check if the class
596 * has already been loaded.</li>
597 * <li>Invoke the {@link #findClass(String, String)} method to find the
598 * class in the given module.</li>
599 * </ol>
600 *
601 * @param module
602 * The module
603 * @param name
604 * The <a href="#binary-name">binary name</a> of the class
605 *
606 * @return The resulting {@code Class} object in a module defined by
607 * this class loader, or {@code null} if the class could not be found.
608 */
609 final Class<?> loadClass(Module module, String name) {
610 synchronized (getClassLoadingLock(name)) {
611 // First, check if the class has already been loaded
612 Class<?> c = findLoadedClass(name);
613 if (c == null) {
614 c = findClass(module.getName(), name);
615 }
616 if (c != null && c.getModule() == module) {
617 return c;
618 } else {
619 return null;
620 }
621 }
622 }
623
624 /**
625 * Returns the lock object for class loading operations.
626 *
627 * @implSpec
628 * If this {@code ClassLoader} object is registered as parallel capable,
629 * this method returns a dedicated object associated with the specified
630 * class name. Otherwise, this method returns this {@code ClassLoader} object.
631 *
632 * @apiNote
633 * This method allows parallel capable class loaders to implement
634 * finer-grained locking schemes such that multiple threads may load classes
635 * concurrently without deadlocks. For non-parallel-capable class loaders,
636 * the {@code ClassLoader} object is synchronized on during the class loading
637 * operations. Class loaders with non-hierarchical delegation should be
638 * {@linkplain #registerAsParallelCapable() registered as parallel capable}
639 * to prevent deadlocks.
640 *
641 * @param className
642 * The name of the to-be-loaded class
643 *
644 * @return the lock for class loading operations
645 *
646 * @throws NullPointerException
647 * If registered as parallel capable and {@code className} is {@code null}
648 *
649 * @see #loadClass(String, boolean)
650 *
651 * @since 1.7
652 */
653 protected Object getClassLoadingLock(String className) {
654 Object lock = this;
655 if (parallelLockMap != null) {
656 Object newLock = new Object();
657 lock = parallelLockMap.putIfAbsent(className, newLock);
658 if (lock == null) {
659 lock = newLock;
660 }
661 }
662 return lock;
663 }
664
665 /**
666 * Finds the class with the specified <a href="#binary-name">binary name</a>.
667 * This method should be overridden by class loader implementations that
668 * follow the delegation model for loading classes, and will be invoked by
669 * the {@link #loadClass loadClass} method after checking the
670 * parent class loader for the requested class.
671 *
672 * @implSpec The default implementation throws {@code ClassNotFoundException}.
673 *
674 * @param name
675 * The <a href="#binary-name">binary name</a> of the class
676 *
677 * @return The resulting {@code Class} object
678 *
679 * @throws ClassNotFoundException
680 * If the class could not be found
681 *
682 * @since 1.2
683 */
684 protected Class<?> findClass(String name) throws ClassNotFoundException {
685 throw new ClassNotFoundException(name);
686 }
687
688 /**
689 * Finds the class with the given <a href="#binary-name">binary name</a>
690 * in a module defined to this class loader.
691 * Class loader implementations that support loading from modules
692 * should override this method.
693 *
694 * @apiNote This method returns {@code null} rather than throwing
695 * {@code ClassNotFoundException} if the class could not be found.
696 *
697 * @implSpec The default implementation attempts to find the class by
698 * invoking {@link #findClass(String)} when the {@code moduleName} is
699 * {@code null}. It otherwise returns {@code null}.
700 *
701 * @param moduleName
702 * The module name; or {@code null} to find the class in the
703 * {@linkplain #getUnnamedModule() unnamed module} for this
704 * class loader
705 * @param name
706 * The <a href="#binary-name">binary name</a> of the class
707 *
708 * @return The resulting {@code Class} object, or {@code null}
709 * if the class could not be found.
710 *
711 * @since 9
712 */
713 protected Class<?> findClass(String moduleName, String name) {
714 if (moduleName == null) {
715 try {
716 return findClass(name);
717 } catch (ClassNotFoundException ignore) { }
718 }
719 return null;
720 }
721
722
723 /**
724 * Converts an array of bytes into an instance of class {@code Class}.
725 * Before the {@code Class} can be used it must be resolved. This method
726 * is deprecated in favor of the version that takes a <a
727 * href="#binary-name">binary name</a> as its first argument, and is more secure.
728 *
729 * @param b
730 * The bytes that make up the class data. The bytes in positions
731 * {@code off} through {@code off+len-1} should have the format
732 * of a valid class file as defined by
733 * <cite>The Java Virtual Machine Specification</cite>.
734 *
735 * @param off
736 * The start offset in {@code b} of the class data
737 *
738 * @param len
739 * The length of the class data
740 *
741 * @return The {@code Class} object that was created from the specified
742 * class data
743 *
744 * @throws ClassFormatError
745 * If the data did not contain a valid class
746 *
747 * @throws IndexOutOfBoundsException
748 * If either {@code off} or {@code len} is negative, or if
749 * {@code off+len} is greater than {@code b.length}.
750 *
751 * @throws SecurityException
752 * If an attempt is made to add this class to a package that
753 * contains classes that were signed by a different set of
754 * certificates than this class, or if an attempt is made
755 * to define a class in a package with a fully-qualified name
756 * that starts with "{@code java.}".
757 *
758 * @see #loadClass(String, boolean)
759 * @see #resolveClass(Class)
760 *
761 * @deprecated Replaced by {@link #defineClass(String, byte[], int, int)
762 * defineClass(String, byte[], int, int)}
763 */
764 @Deprecated(since="1.1")
765 protected final Class<?> defineClass(byte[] b, int off, int len)
766 throws ClassFormatError
767 {
768 return defineClass(null, b, off, len, null);
769 }
770
771 /**
772 * Converts an array of bytes into an instance of class {@code Class}.
773 * Before the {@code Class} can be used it must be resolved.
774 *
775 * <p> This method assigns a default {@link java.security.ProtectionDomain
776 * ProtectionDomain} to the newly defined class. The
777 * {@code getPermissions} method of the {@code ProtectionDomain} always
778 * returns {@code null}.
779 * The default protection domain is created on the first invocation
780 * of {@link #defineClass(String, byte[], int, int) defineClass},
781 * and re-used on subsequent invocations.
782 *
783 * <p> To assign a specific {@code ProtectionDomain} to the class, use
784 * the {@link #defineClass(String, byte[], int, int,
785 * java.security.ProtectionDomain) defineClass} method that takes a
786 * {@code ProtectionDomain} as one of its arguments. </p>
787 *
788 * <p>
789 * This method defines a package in this class loader corresponding to the
790 * package of the {@code Class} (if such a package has not already been defined
791 * in this class loader). The name of the defined package is derived from
792 * the <a href="#binary-name">binary name</a> of the class specified by
793 * the byte array {@code b}.
794 * Other properties of the defined package are as specified by {@link Package}.
795 *
796 * @param name
797 * The expected <a href="#binary-name">binary name</a> of the class, or
798 * {@code null} if not known
799 *
800 * @param b
801 * The bytes that make up the class data. The bytes in positions
802 * {@code off} through {@code off+len-1} should have the format
803 * of a valid class file as defined by
804 * <cite>The Java Virtual Machine Specification</cite>.
805 *
806 * @param off
807 * The start offset in {@code b} of the class data
808 *
809 * @param len
810 * The length of the class data
811 *
812 * @return The {@code Class} object that was created from the specified
813 * class data.
814 *
815 * @throws ClassFormatError
816 * If the data did not contain a valid class
817 *
818 * @throws IndexOutOfBoundsException
819 * If either {@code off} or {@code len} is negative, or if
820 * {@code off+len} is greater than {@code b.length}.
821 *
822 * @throws SecurityException
823 * If an attempt is made to add this class to a package that
824 * contains classes that were signed by a different set of
825 * certificates than this class (which is unsigned), or if
826 * {@code name} begins with "{@code java.}".
827 *
828 * @see #loadClass(String, boolean)
829 * @see #resolveClass(Class)
830 * @see java.security.CodeSource
831 * @see java.security.SecureClassLoader
832 *
833 * @since 1.1
834 */
835 protected final Class<?> defineClass(String name, byte[] b, int off, int len)
836 throws ClassFormatError
837 {
838 return defineClass(name, b, off, len, null);
839 }
840
841 /* Determine protection domain, and check that:
842 - not define java.* class,
843 - signer of this class matches signers for the rest of the classes in
844 package.
845 */
846 private ProtectionDomain preDefineClass(String name,
847 ProtectionDomain pd)
848 {
849 if (!checkName(name))
850 throw new NoClassDefFoundError("IllegalName: " + name);
851
852 // Note: Checking logic in java.lang.invoke.MemberName.checkForTypeAlias
853 // relies on the fact that spoofing is impossible if a class has a name
854 // of the form "java.*"
855 if ((name != null) && name.startsWith("java.")
856 && this != getBuiltinPlatformClassLoader()) {
857 throw new SecurityException
858 ("Prohibited package name: " +
859 name.substring(0, name.lastIndexOf('.')));
860 }
861 if (pd == null) {
862 pd = defaultDomain;
863 }
864
865 if (name != null) {
866 checkCerts(name, pd.getCodeSource());
867 }
868
869 return pd;
870 }
871
872 private String defineClassSourceLocation(ProtectionDomain pd) {
873 CodeSource cs = pd.getCodeSource();
874 String source = null;
875 if (cs != null && cs.getLocation() != null) {
876 source = cs.getLocation().toString();
877 }
878 return source;
879 }
880
881 private void postDefineClass(Class<?> c, ProtectionDomain pd) {
882 // define a named package, if not present
883 getNamedPackage(c.getPackageName(), c.getModule());
884
885 if (pd.getCodeSource() != null) {
886 Certificate certs[] = pd.getCodeSource().getCertificates();
887 if (certs != null)
888 setSigners(c, certs);
889 }
890 }
891
892 /**
893 * Converts an array of bytes into an instance of class {@code Class},
894 * with a given {@code ProtectionDomain}.
895 *
896 * <p> If the given {@code ProtectionDomain} is {@code null},
897 * then a default protection domain will be assigned to the class as specified
898 * in the documentation for {@link #defineClass(String, byte[], int, int)}.
899 * Before the class can be used it must be resolved.
900 *
901 * <p> The first class defined in a package determines the exact set of
902 * certificates that all subsequent classes defined in that package must
903 * contain. The set of certificates for a class is obtained from the
904 * {@link java.security.CodeSource CodeSource} within the
905 * {@code ProtectionDomain} of the class. Any classes added to that
906 * package must contain the same set of certificates or a
907 * {@code SecurityException} will be thrown. Note that if
908 * {@code name} is {@code null}, this check is not performed.
909 * You should always pass in the <a href="#binary-name">binary name</a> of the
910 * class you are defining as well as the bytes. This ensures that the
911 * class you are defining is indeed the class you think it is.
912 *
913 * <p> If the specified {@code name} begins with "{@code java.}", it can
914 * only be defined by the {@linkplain #getPlatformClassLoader()
915 * platform class loader} or its ancestors; otherwise {@code SecurityException}
916 * will be thrown. If {@code name} is not {@code null}, it must be equal to
917 * the <a href="#binary-name">binary name</a> of the class
918 * specified by the byte array {@code b}, otherwise a {@link
919 * NoClassDefFoundError NoClassDefFoundError} will be thrown.
920 *
921 * <p> This method defines a package in this class loader corresponding to the
922 * package of the {@code Class} (if such a package has not already been defined
923 * in this class loader). The name of the defined package is derived from
924 * the <a href="#binary-name">binary name</a> of the class specified by
925 * the byte array {@code b}.
926 * Other properties of the defined package are as specified by {@link Package}.
927 *
928 * @param name
929 * The expected <a href="#binary-name">binary name</a> of the class, or
930 * {@code null} if not known
931 *
932 * @param b
933 * The bytes that make up the class data. The bytes in positions
934 * {@code off} through {@code off+len-1} should have the format
935 * of a valid class file as defined by
936 * <cite>The Java Virtual Machine Specification</cite>.
937 *
938 * @param off
939 * The start offset in {@code b} of the class data
940 *
941 * @param len
942 * The length of the class data
943 *
944 * @param protectionDomain
945 * The {@code ProtectionDomain} of the class
946 *
947 * @return The {@code Class} object created from the data,
948 * and {@code ProtectionDomain}.
949 *
950 * @throws ClassFormatError
951 * If the data did not contain a valid class
952 *
953 * @throws NoClassDefFoundError
954 * If {@code name} is not {@code null} and not equal to the
955 * <a href="#binary-name">binary name</a> of the class specified by {@code b}
956 *
957 * @throws IndexOutOfBoundsException
958 * If either {@code off} or {@code len} is negative, or if
959 * {@code off+len} is greater than {@code b.length}.
960 *
961 * @throws SecurityException
962 * If an attempt is made to add this class to a package that
963 * contains classes that were signed by a different set of
964 * certificates than this class, or if {@code name} begins with
965 * "{@code java.}" and this class loader is not the platform
966 * class loader or its ancestor.
967 */
968 protected final Class<?> defineClass(String name, byte[] b, int off, int len,
969 ProtectionDomain protectionDomain)
970 throws ClassFormatError
971 {
972 protectionDomain = preDefineClass(name, protectionDomain);
973 String source = defineClassSourceLocation(protectionDomain);
974 Class<?> c = defineClass1(this, name, b, off, len, protectionDomain, source);
975 postDefineClass(c, protectionDomain);
976 return c;
977 }
978
979 /**
980 * Converts a {@link java.nio.ByteBuffer ByteBuffer} into an instance
981 * of class {@code Class}, with the given {@code ProtectionDomain}.
982 * If the given {@code ProtectionDomain} is {@code null}, then a default
983 * protection domain will be assigned to the class as
984 * specified in the documentation for {@link #defineClass(String, byte[],
985 * int, int)}. Before the class can be used it must be resolved.
986 *
987 * <p>The rules about the first class defined in a package determining the
988 * set of certificates for the package, the restrictions on class names,
989 * and the defined package of the class
990 * are identical to those specified in the documentation for {@link
991 * #defineClass(String, byte[], int, int, ProtectionDomain)}.
992 *
993 * <p> An invocation of this method of the form
994 * <i>cl</i>{@code .defineClass(}<i>name</i>{@code ,}
995 * <i>bBuffer</i>{@code ,} <i>pd</i>{@code )} yields exactly the same
996 * result as the statements
997 *
998 *<p> <code>
999 * ...<br>
1000 * byte[] temp = new byte[bBuffer.{@link
1001 * java.nio.ByteBuffer#remaining remaining}()];<br>
1002 * bBuffer.{@link java.nio.ByteBuffer#get(byte[])
1003 * get}(temp);<br>
1004 * return {@link #defineClass(String, byte[], int, int, ProtectionDomain)
1005 * cl.defineClass}(name, temp, 0,
1006 * temp.length, pd);<br>
1007 * </code></p>
1008 *
1009 * @param name
1010 * The expected <a href="#binary-name">binary name</a>. of the class, or
1011 * {@code null} if not known
1012 *
1013 * @param b
1014 * The bytes that make up the class data. The bytes from positions
1015 * {@code b.position()} through {@code b.position() + b.limit() -1
1016 * } should have the format of a valid class file as defined by
1017 * <cite>The Java Virtual Machine Specification</cite>.
1018 *
1019 * @param protectionDomain
1020 * The {@code ProtectionDomain} of the class, or {@code null}.
1021 *
1022 * @return The {@code Class} object created from the data,
1023 * and {@code ProtectionDomain}.
1024 *
1025 * @throws ClassFormatError
1026 * If the data did not contain a valid class.
1027 *
1028 * @throws NoClassDefFoundError
1029 * If {@code name} is not {@code null} and not equal to the
1030 * <a href="#binary-name">binary name</a> of the class specified by {@code b}
1031 *
1032 * @throws SecurityException
1033 * If an attempt is made to add this class to a package that
1034 * contains classes that were signed by a different set of
1035 * certificates than this class, or if {@code name} begins with
1036 * "{@code java.}".
1037 *
1038 * @see #defineClass(String, byte[], int, int, ProtectionDomain)
1039 *
1040 * @since 1.5
1041 */
1042 protected final Class<?> defineClass(String name, ByteBuffer b,
1043 ProtectionDomain protectionDomain)
1044 throws ClassFormatError
1045 {
1046 int len = b.remaining();
1047
1048 // Use byte[] if not a direct ByteBuffer:
1049 if (!b.isDirect()) {
1050 if (b.hasArray()) {
1051 return defineClass(name, b.array(),
1052 b.position() + b.arrayOffset(), len,
1053 protectionDomain);
1054 } else {
1055 // no array, or read-only array
1056 byte[] tb = new byte[len];
1057 b.get(tb); // get bytes out of byte buffer.
1058 return defineClass(name, tb, 0, len, protectionDomain);
1059 }
1060 }
1061
1062 boolean trusted = this instanceof BuiltinClassLoader;
1063 if (trusted) {
1064 return defineClass(name, b, len, protectionDomain);
1065 } else {
1066 // make copy from input byte buffer
1067 try (var arena = Arena.ofConfined()) {
1068 ByteBuffer bb = arena.allocate(len).asByteBuffer();
1069 bb.put(0, b, b.position(), len);
1070 return defineClass(name, bb, len, protectionDomain);
1071 }
1072 }
1073 }
1074
1075 private Class<?> defineClass(String name, ByteBuffer b, int len, ProtectionDomain pd) {
1076 pd = preDefineClass(name, pd);
1077 String source = defineClassSourceLocation(pd);
1078 SharedSecrets.getJavaNioAccess().acquireSession(b);
1079 try {
1080 Class<?> c = defineClass2(this, name, b, b.position(), len, pd, source);
1081 postDefineClass(c, pd);
1082 return c;
1083 } finally {
1084 SharedSecrets.getJavaNioAccess().releaseSession(b);
1085 }
1086 }
1087
1088 static native Class<?> defineClass1(ClassLoader loader, String name, byte[] b, int off, int len,
1089 ProtectionDomain pd, String source);
1090
1091 // Warning: Before calling this method, the provided ByteBuffer must be guarded
1092 // via JavaNioAccess::(acquire|release)Session
1093 static native Class<?> defineClass2(ClassLoader loader, String name, java.nio.ByteBuffer b,
1094 int off, int len, ProtectionDomain pd,
1095 String source);
1096
1097 /**
1098 * Defines a class of the given flags via Lookup.defineClass.
1099 *
1100 * @param loader the defining loader
1101 * @param lookup nest host of the Class to be defined
1102 * @param name the binary name or {@code null} if not findable
1103 * @param b class bytes
1104 * @param off the start offset in {@code b} of the class bytes
1105 * @param len the length of the class bytes
1106 * @param pd protection domain
1107 * @param initialize initialize the class
1108 * @param flags flags
1109 * @param classData class data
1110 */
1111 static native Class<?> defineClass0(ClassLoader loader,
1112 Class<?> lookup,
1113 String name,
1114 byte[] b, int off, int len,
1115 ProtectionDomain pd,
1116 boolean initialize,
1117 int flags,
1118 Object classData);
1119
1120 // true if the name is null or has the potential to be a valid binary name
1121 private static boolean checkName(String name) {
1122 if ((name == null) || (name.isEmpty()))
1123 return true;
1124 if ((name.indexOf('/') != -1) || (name.charAt(0) == '['))
1125 return false;
1126 return true;
1127 }
1128
1129 private void checkCerts(String name, CodeSource cs) {
1130 int i = name.lastIndexOf('.');
1131 String pname = (i == -1) ? "" : name.substring(0, i);
1132
1133 Certificate[] certs = null;
1134 if (cs != null) {
1135 certs = cs.getCertificates();
1136 }
1137 certs = certs == null ? nocerts : certs;
1138 Certificate[] pcerts = package2certs.putIfAbsent(pname, certs);
1139 if (pcerts != null && !compareCerts(pcerts, certs)) {
1140 throw new SecurityException("class \"" + name
1141 + "\"'s signer information does not match signer information"
1142 + " of other classes in the same package");
1143 }
1144 }
1145
1146 /**
1147 * check to make sure the certs for the new class (certs) are the same as
1148 * the certs for the first class inserted in the package (pcerts)
1149 */
1150 private boolean compareCerts(Certificate[] pcerts, Certificate[] certs) {
1151 // empty array fast-path
1152 if (certs.length == 0)
1153 return pcerts.length == 0;
1154
1155 // the length must be the same at this point
1156 if (certs.length != pcerts.length)
1157 return false;
1158
1159 // go through and make sure all the certs in one array
1160 // are in the other and vice-versa.
1161 boolean match;
1162 for (Certificate cert : certs) {
1163 match = false;
1164 for (Certificate pcert : pcerts) {
1165 if (cert.equals(pcert)) {
1166 match = true;
1167 break;
1168 }
1169 }
1170 if (!match) return false;
1171 }
1172
1173 // now do the same for pcerts
1174 for (Certificate pcert : pcerts) {
1175 match = false;
1176 for (Certificate cert : certs) {
1177 if (pcert.equals(cert)) {
1178 match = true;
1179 break;
1180 }
1181 }
1182 if (!match) return false;
1183 }
1184
1185 return true;
1186 }
1187
1188 /**
1189 * Links the specified class. This (misleadingly named) method may be
1190 * used by a class loader to link a class. If the class {@code c} has
1191 * already been linked, then this method simply returns. Otherwise, the
1192 * class is linked as described in the "Execution" chapter of
1193 * <cite>The Java Language Specification</cite>.
1194 *
1195 * @param c
1196 * The class to link
1197 *
1198 * @throws NullPointerException
1199 * If {@code c} is {@code null}.
1200 *
1201 * @see #defineClass(String, byte[], int, int)
1202 */
1203 protected final void resolveClass(Class<?> c) {
1204 if (c == null) {
1205 throw new NullPointerException();
1206 }
1207 }
1208
1209 /**
1210 * Finds a class with the specified <a href="#binary-name">binary name</a>,
1211 * loading it if necessary.
1212 *
1213 * <p> This method loads the class through the system class loader (see
1214 * {@link #getSystemClassLoader()}). The {@code Class} object returned
1215 * might have more than one {@code ClassLoader} associated with it.
1216 * Subclasses of {@code ClassLoader} need not usually invoke this method,
1217 * because most class loaders need to override just {@link
1218 * #findClass(String)}. </p>
1219 *
1220 * @param name
1221 * The <a href="#binary-name">binary name</a> of the class
1222 *
1223 * @return The {@code Class} object for the specified {@code name}
1224 *
1225 * @throws ClassNotFoundException
1226 * If the class could not be found
1227 *
1228 * @see #ClassLoader(ClassLoader)
1229 * @see #getParent()
1230 */
1231 protected final Class<?> findSystemClass(String name)
1232 throws ClassNotFoundException
1233 {
1234 return getSystemClassLoader().loadClass(name);
1235 }
1236
1237 /**
1238 * Returns a class loaded by the bootstrap class loader;
1239 * or return null if not found.
1240 */
1241 static Class<?> findBootstrapClassOrNull(String name) {
1242 if (!checkName(name)) return null;
1243
1244 return findBootstrapClass(name);
1245 }
1246
1247 // return null if not found
1248 private static native Class<?> findBootstrapClass(String name);
1249
1250 /**
1251 * Returns the class with the given <a href="#binary-name">binary name</a> if this
1252 * loader has been recorded by the Java virtual machine as an initiating
1253 * loader of a class with that <a href="#binary-name">binary name</a>. Otherwise
1254 * {@code null} is returned.
1255 *
1256 * @param name
1257 * The <a href="#binary-name">binary name</a> of the class
1258 *
1259 * @return The {@code Class} object, or {@code null} if the class has
1260 * not been loaded
1261 *
1262 * @since 1.1
1263 */
1264 protected final Class<?> findLoadedClass(String name) {
1265 if (!checkName(name))
1266 return null;
1267 return findLoadedClass0(name);
1268 }
1269
1270 private final native Class<?> findLoadedClass0(String name);
1271
1272 /**
1273 * Sets the signers of a class. This should be invoked after defining a
1274 * class.
1275 *
1276 * @param c
1277 * The {@code Class} object
1278 *
1279 * @param signers
1280 * The signers for the class
1281 *
1282 * @since 1.1
1283 */
1284 protected final void setSigners(Class<?> c, Object[] signers) {
1285 c.setSigners(signers);
1286 }
1287
1288
1289 // -- Resources --
1290
1291 /**
1292 * Returns a URL to a resource in a module defined to this class loader.
1293 * Class loader implementations that support loading from modules
1294 * should override this method.
1295 *
1296 * @apiNote This method is the basis for the {@link
1297 * Class#getResource Class.getResource}, {@link Class#getResourceAsStream
1298 * Class.getResourceAsStream}, and {@link Module#getResourceAsStream
1299 * Module.getResourceAsStream} methods. It is not subject to the rules for
1300 * encapsulation specified by {@code Module.getResourceAsStream}.
1301 *
1302 * @implSpec The default implementation attempts to find the resource by
1303 * invoking {@link #findResource(String)} when the {@code moduleName} is
1304 * {@code null}. It otherwise returns {@code null}.
1305 *
1306 * @param moduleName
1307 * The module name; or {@code null} to find a resource in the
1308 * {@linkplain #getUnnamedModule() unnamed module} for this
1309 * class loader
1310 * @param name
1311 * The resource name
1312 *
1313 * @return A URL to the resource; {@code null} if the resource could not be
1314 * found, a URL could not be constructed to locate the resource, or
1315 * there isn't a module of the given name defined to the class
1316 * loader.
1317 *
1318 * @throws IOException
1319 * If I/O errors occur
1320 *
1321 * @see java.lang.module.ModuleReader#find(String)
1322 * @since 9
1323 */
1324 protected URL findResource(String moduleName, String name) throws IOException {
1325 if (moduleName == null) {
1326 return findResource(name);
1327 } else {
1328 return null;
1329 }
1330 }
1331
1332 /**
1333 * Finds the resource with the given name. A resource is some data
1334 * (images, audio, text, etc) that can be accessed by class code in a way
1335 * that is independent of the location of the code.
1336 *
1337 * <p> The name of a resource is a '{@code /}'-separated path name that
1338 * identifies the resource. </p>
1339 *
1340 * <p> Resources in named modules are subject to the encapsulation rules
1341 * specified by {@link Module#getResourceAsStream Module.getResourceAsStream}.
1342 * Additionally, and except for the special case where the resource has a
1343 * name ending with "{@code .class}", this method will only find resources in
1344 * packages of named modules when the package is {@link Module#isOpen(String)
1345 * opened} unconditionally (even if the caller of this method is in the
1346 * same module as the resource). </p>
1347 *
1348 * @implSpec The default implementation will first search the parent class
1349 * loader for the resource; if the parent is {@code null} the path of the
1350 * class loader built into the virtual machine is searched. If not found,
1351 * this method will invoke {@link #findResource(String)} to find the resource.
1352 *
1353 * @apiNote Where several modules are defined to the same class loader,
1354 * and where more than one module contains a resource with the given name,
1355 * then the ordering that modules are searched is not specified and may be
1356 * very unpredictable.
1357 * When overriding this method it is recommended that an implementation
1358 * ensures that any delegation is consistent with the {@link
1359 * #getResources(java.lang.String) getResources(String)} method.
1360 *
1361 * @param name
1362 * The resource name
1363 *
1364 * @return {@code URL} object for reading the resource; {@code null} if
1365 * the resource could not be found, a {@code URL} could not be
1366 * constructed to locate the resource, or the resource is in a package
1367 * that is not opened unconditionally.
1368 *
1369 * @throws NullPointerException If {@code name} is {@code null}
1370 *
1371 * @since 1.1
1372 */
1373 public URL getResource(String name) {
1374 Objects.requireNonNull(name);
1375 URL url;
1376 if (parent != null) {
1377 url = parent.getResource(name);
1378 } else {
1379 url = BootLoader.findResource(name);
1380 }
1381 if (url == null) {
1382 url = findResource(name);
1383 }
1384 return url;
1385 }
1386
1387 /**
1388 * Finds all the resources with the given name. A resource is some data
1389 * (images, audio, text, etc) that can be accessed by class code in a way
1390 * that is independent of the location of the code.
1391 *
1392 * <p> The name of a resource is a {@code /}-separated path name that
1393 * identifies the resource. </p>
1394 *
1395 * <p> Resources in named modules are subject to the encapsulation rules
1396 * specified by {@link Module#getResourceAsStream Module.getResourceAsStream}.
1397 * Additionally, and except for the special case where the resource has a
1398 * name ending with "{@code .class}", this method will only find resources in
1399 * packages of named modules when the package is {@link Module#isOpen(String)
1400 * opened} unconditionally (even if the caller of this method is in the
1401 * same module as the resource). </p>
1402 *
1403 * @implSpec The default implementation will first search the parent class
1404 * loader for the resource; if the parent is {@code null} the path of the
1405 * class loader built into the virtual machine is searched. It then
1406 * invokes {@link #findResources(String)} to find the resources with the
1407 * name in this class loader. It returns an enumeration whose elements
1408 * are the URLs found by searching the parent class loader followed by
1409 * the elements found with {@code findResources}.
1410 *
1411 * @apiNote Where several modules are defined to the same class loader,
1412 * and where more than one module contains a resource with the given name,
1413 * then the ordering is not specified and may be very unpredictable.
1414 * When overriding this method it is recommended that an
1415 * implementation ensures that any delegation is consistent with the {@link
1416 * #getResource(java.lang.String) getResource(String)} method. This should
1417 * ensure that the first element returned by the Enumeration's
1418 * {@code nextElement} method is the same resource that the
1419 * {@code getResource(String)} method would return.
1420 *
1421 * @param name
1422 * The resource name
1423 *
1424 * @return An enumeration of {@link java.net.URL URL} objects for the
1425 * resource. If no resources could be found, the enumeration will
1426 * be empty. Resources for which a {@code URL} cannot be
1427 * constructed, or are in a package that is not opened
1428 * unconditionally, are not returned in the enumeration.
1429 *
1430 * @throws IOException
1431 * If I/O errors occur
1432 * @throws NullPointerException If {@code name} is {@code null}
1433 *
1434 * @since 1.2
1435 */
1436 public Enumeration<URL> getResources(String name) throws IOException {
1437 Objects.requireNonNull(name);
1438 @SuppressWarnings("unchecked")
1439 Enumeration<URL>[] tmp = (Enumeration<URL>[]) new Enumeration<?>[2];
1440 if (parent != null) {
1441 tmp[0] = parent.getResources(name);
1442 } else {
1443 tmp[0] = BootLoader.findResources(name);
1444 }
1445 tmp[1] = findResources(name);
1446
1447 return new CompoundEnumeration<>(tmp);
1448 }
1449
1450 /**
1451 * Returns a stream whose elements are the URLs of all the resources with
1452 * the given name. A resource is some data (images, audio, text, etc) that
1453 * can be accessed by class code in a way that is independent of the
1454 * location of the code.
1455 *
1456 * <p> The name of a resource is a {@code /}-separated path name that
1457 * identifies the resource.
1458 *
1459 * <p> The resources will be located when the returned stream is evaluated.
1460 * If the evaluation results in an {@code IOException} then the I/O
1461 * exception is wrapped in an {@link UncheckedIOException} that is then
1462 * thrown.
1463 *
1464 * <p> Resources in named modules are subject to the encapsulation rules
1465 * specified by {@link Module#getResourceAsStream Module.getResourceAsStream}.
1466 * Additionally, and except for the special case where the resource has a
1467 * name ending with "{@code .class}", this method will only find resources in
1468 * packages of named modules when the package is {@link Module#isOpen(String)
1469 * opened} unconditionally (even if the caller of this method is in the
1470 * same module as the resource). </p>
1471 *
1472 * @implSpec The default implementation invokes {@link #getResources(String)
1473 * getResources} to find all the resources with the given name and returns
1474 * a stream with the elements in the enumeration as the source.
1475 *
1476 * @apiNote When overriding this method it is recommended that an
1477 * implementation ensures that any delegation is consistent with the {@link
1478 * #getResource(java.lang.String) getResource(String)} method. This should
1479 * ensure that the first element returned by the stream is the same
1480 * resource that the {@code getResource(String)} method would return.
1481 *
1482 * @param name
1483 * The resource name
1484 *
1485 * @return A stream of resource {@link java.net.URL URL} objects. If no
1486 * resources could be found, the stream will be empty. Resources
1487 * for which a {@code URL} cannot be constructed, or are in a package
1488 * that is not opened unconditionally, will not be in the stream.
1489 *
1490 * @throws NullPointerException If {@code name} is {@code null}
1491 *
1492 * @since 9
1493 */
1494 public Stream<URL> resources(String name) {
1495 Objects.requireNonNull(name);
1496 int characteristics = Spliterator.NONNULL | Spliterator.IMMUTABLE;
1497 Supplier<Spliterator<URL>> si = () -> {
1498 try {
1499 return Spliterators.spliteratorUnknownSize(
1500 getResources(name).asIterator(), characteristics);
1501 } catch (IOException e) {
1502 throw new UncheckedIOException(e);
1503 }
1504 };
1505 return StreamSupport.stream(si, characteristics, false);
1506 }
1507
1508 /**
1509 * Finds the resource with the given name. Class loader implementations
1510 * should override this method.
1511 *
1512 * <p> For resources in named modules then the method must implement the
1513 * rules for encapsulation specified in the {@code Module} {@link
1514 * Module#getResourceAsStream getResourceAsStream} method. Additionally,
1515 * it must not find non-"{@code .class}" resources in packages of named
1516 * modules unless the package is {@link Module#isOpen(String) opened}
1517 * unconditionally. </p>
1518 *
1519 * @implSpec The default implementation returns {@code null}.
1520 *
1521 * @param name
1522 * The resource name
1523 *
1524 * @return {@code URL} object for reading the resource; {@code null} if
1525 * the resource could not be found, a {@code URL} could not be
1526 * constructed to locate the resource, or the resource is in a package
1527 * that is not opened unconditionally.
1528 *
1529 * @since 1.2
1530 */
1531 protected URL findResource(String name) {
1532 return null;
1533 }
1534
1535 /**
1536 * Returns an enumeration of {@link java.net.URL URL} objects
1537 * representing all the resources with the given name. Class loader
1538 * implementations should override this method.
1539 *
1540 * <p> For resources in named modules then the method must implement the
1541 * rules for encapsulation specified in the {@code Module} {@link
1542 * Module#getResourceAsStream getResourceAsStream} method. Additionally,
1543 * it must not find non-"{@code .class}" resources in packages of named
1544 * modules unless the package is {@link Module#isOpen(String) opened}
1545 * unconditionally. </p>
1546 *
1547 * @implSpec The default implementation returns an enumeration that
1548 * contains no elements.
1549 *
1550 * @param name
1551 * The resource name
1552 *
1553 * @return An enumeration of {@link java.net.URL URL} objects for
1554 * the resource. If no resources could be found, the enumeration
1555 * will be empty. Resources for which a {@code URL} cannot be
1556 * constructed, or are in a package that is not opened unconditionally,
1557 * are not returned in the enumeration.
1558 *
1559 * @throws IOException
1560 * If I/O errors occur
1561 *
1562 * @since 1.2
1563 */
1564 protected Enumeration<URL> findResources(String name) throws IOException {
1565 return Collections.emptyEnumeration();
1566 }
1567
1568 /**
1569 * Registers the caller as
1570 * {@linkplain #isRegisteredAsParallelCapable() parallel capable}.
1571 * The registration succeeds if and only if all of the following
1572 * conditions are met:
1573 * <ol>
1574 * <li> no instance of the caller has been created</li>
1575 * <li> all of the super classes (except class Object) of the caller are
1576 * registered as parallel capable</li>
1577 * </ol>
1578 * <p>Note that once a class loader is registered as parallel capable, there
1579 * is no way to change it back.</p>
1580 * <p>
1581 * In cases where this method is called from a context where the caller is
1582 * not a subclass of {@code ClassLoader} or there is no caller frame on the
1583 * stack (e.g. when called directly from a JNI attached thread),
1584 * {@code IllegalCallerException} is thrown.
1585 * </p>
1586 *
1587 * @return {@code true} if the caller is successfully registered as
1588 * parallel capable and {@code false} if otherwise.
1589 * @throws IllegalCallerException if the caller is not a subclass of {@code ClassLoader}
1590 *
1591 * @see #isRegisteredAsParallelCapable()
1592 *
1593 * @since 1.7
1594 */
1595 @CallerSensitive
1596 protected static boolean registerAsParallelCapable() {
1597 return registerAsParallelCapable(Reflection.getCallerClass());
1598 }
1599
1600 // Caller-sensitive adapter method for reflective invocation
1601 @CallerSensitiveAdapter
1602 private static boolean registerAsParallelCapable(Class<?> caller) {
1603 if ((caller == null) || !ClassLoader.class.isAssignableFrom(caller)) {
1604 throw new IllegalCallerException(caller + " not a subclass of ClassLoader");
1605 }
1606 return ParallelLoaders.register(caller.asSubclass(ClassLoader.class));
1607 }
1608
1609 /**
1610 * Returns {@code true} if this class loader is registered as
1611 * {@linkplain #registerAsParallelCapable parallel capable}, otherwise
1612 * {@code false}.
1613 *
1614 * @return {@code true} if this class loader is parallel capable,
1615 * otherwise {@code false}.
1616 *
1617 * @see #registerAsParallelCapable()
1618 *
1619 * @since 9
1620 */
1621 public final boolean isRegisteredAsParallelCapable() {
1622 return ParallelLoaders.isRegistered(this.getClass());
1623 }
1624
1625 /**
1626 * Find a resource of the specified name from the search path used to load
1627 * classes. This method locates the resource through the system class
1628 * loader (see {@link #getSystemClassLoader()}).
1629 *
1630 * <p> Resources in named modules are subject to the encapsulation rules
1631 * specified by {@link Module#getResourceAsStream Module.getResourceAsStream}.
1632 * Additionally, and except for the special case where the resource has a
1633 * name ending with "{@code .class}", this method will only find resources in
1634 * packages of named modules when the package is {@link Module#isOpen(String)
1635 * opened} unconditionally. </p>
1636 *
1637 * @param name
1638 * The resource name
1639 *
1640 * @return A {@link java.net.URL URL} to the resource; {@code
1641 * null} if the resource could not be found, a URL could not be
1642 * constructed to locate the resource, or the resource is in a package
1643 * that is not opened unconditionally.
1644 *
1645 * @since 1.1
1646 */
1647 public static URL getSystemResource(String name) {
1648 return getSystemClassLoader().getResource(name);
1649 }
1650
1651 /**
1652 * Finds all resources of the specified name from the search path used to
1653 * load classes. The resources thus found are returned as an
1654 * {@link java.util.Enumeration Enumeration} of {@link
1655 * java.net.URL URL} objects.
1656 *
1657 * <p> The search order is described in the documentation for {@link
1658 * #getSystemResource(String)}. </p>
1659 *
1660 * <p> Resources in named modules are subject to the encapsulation rules
1661 * specified by {@link Module#getResourceAsStream Module.getResourceAsStream}.
1662 * Additionally, and except for the special case where the resource has a
1663 * name ending with "{@code .class}", this method will only find resources in
1664 * packages of named modules when the package is {@link Module#isOpen(String)
1665 * opened} unconditionally. </p>
1666 *
1667 * @param name
1668 * The resource name
1669 *
1670 * @return An enumeration of {@link java.net.URL URL} objects for
1671 * the resource. If no resources could be found, the enumeration
1672 * will be empty. Resources for which a {@code URL} cannot be
1673 * constructed, or are in a package that is not opened unconditionally,
1674 * are not returned in the enumeration.
1675 *
1676 * @throws IOException
1677 * If I/O errors occur
1678 *
1679 * @since 1.2
1680 */
1681 public static Enumeration<URL> getSystemResources(String name)
1682 throws IOException
1683 {
1684 return getSystemClassLoader().getResources(name);
1685 }
1686
1687 /**
1688 * Returns an input stream for reading the specified resource.
1689 *
1690 * <p> The search order is described in the documentation for {@link
1691 * #getResource(String)}. </p>
1692 *
1693 * <p> Resources in named modules are subject to the encapsulation rules
1694 * specified by {@link Module#getResourceAsStream Module.getResourceAsStream}.
1695 * Additionally, and except for the special case where the resource has a
1696 * name ending with "{@code .class}", this method will only find resources in
1697 * packages of named modules when the package is {@link Module#isOpen(String)
1698 * opened} unconditionally. </p>
1699 *
1700 * @param name
1701 * The resource name
1702 *
1703 * @return An input stream for reading the resource; {@code null} if the
1704 * resource could not be found, or the resource is in a package that
1705 * is not opened unconditionally.
1706 *
1707 * @throws NullPointerException If {@code name} is {@code null}
1708 *
1709 * @since 1.1
1710 */
1711 public InputStream getResourceAsStream(String name) {
1712 Objects.requireNonNull(name);
1713 URL url = getResource(name);
1714 try {
1715 return url != null ? url.openStream() : null;
1716 } catch (IOException e) {
1717 return null;
1718 }
1719 }
1720
1721 /**
1722 * Called by VM for reading class bytes.
1723 */
1724 private byte[] getResourceAsByteArray(String name) throws IOException {
1725 Objects.requireNonNull(name);
1726 InputStream is = getResourceAsStream(name);
1727 return is != null ? is.readAllBytes() : null;
1728 }
1729
1730 /**
1731 * Open for reading, a resource of the specified name from the search path
1732 * used to load classes. This method locates the resource through the
1733 * system class loader (see {@link #getSystemClassLoader()}).
1734 *
1735 * <p> Resources in named modules are subject to the encapsulation rules
1736 * specified by {@link Module#getResourceAsStream Module.getResourceAsStream}.
1737 * Additionally, and except for the special case where the resource has a
1738 * name ending with "{@code .class}", this method will only find resources in
1739 * packages of named modules when the package is {@link Module#isOpen(String)
1740 * opened} unconditionally. </p>
1741 *
1742 * @param name
1743 * The resource name
1744 *
1745 * @return An input stream for reading the resource; {@code null} if the
1746 * resource could not be found, or the resource is in a package that
1747 * is not opened unconditionally.
1748 *
1749 * @since 1.1
1750 */
1751 public static InputStream getSystemResourceAsStream(String name) {
1752 URL url = getSystemResource(name);
1753 try {
1754 return url != null ? url.openStream() : null;
1755 } catch (IOException e) {
1756 return null;
1757 }
1758 }
1759
1760
1761 // -- Hierarchy --
1762
1763 /**
1764 * Returns the parent class loader for delegation. Some implementations may
1765 * use {@code null} to represent the bootstrap class loader. This method
1766 * will return {@code null} in such implementations if this class loader's
1767 * parent is the bootstrap class loader.
1768 *
1769 * @return The parent {@code ClassLoader}
1770 *
1771 * @since 1.2
1772 */
1773 public final ClassLoader getParent() {
1774 return parent;
1775 }
1776
1777 /**
1778 * Returns the unnamed {@code Module} for this class loader.
1779 *
1780 * @return The unnamed Module for this class loader
1781 *
1782 * @see Module#isNamed()
1783 * @since 9
1784 */
1785 public final Module getUnnamedModule() {
1786 return unnamedModule;
1787 }
1788
1789 /**
1790 * Returns the platform class loader. All
1791 * <a href="#builtinLoaders">platform classes</a> are visible to
1792 * the platform class loader.
1793 *
1794 * @implNote The name of the builtin platform class loader is
1795 * {@code "platform"}.
1796 *
1797 * @return The platform {@code ClassLoader}.
1798 *
1799 * @since 9
1800 */
1801 public static ClassLoader getPlatformClassLoader() {
1802 return getBuiltinPlatformClassLoader();
1803 }
1804
1805 /**
1806 * Returns the system class loader. This is the default
1807 * delegation parent for new {@code ClassLoader} instances, and is
1808 * typically the class loader used to start the application.
1809 *
1810 * <p> This method is first invoked early in the runtime's startup
1811 * sequence, at which point it creates the system class loader. This
1812 * class loader will be the context class loader for the main application
1813 * thread (for example, the thread that invokes the {@code main} method of
1814 * the main class).
1815 *
1816 * <p> The default system class loader is an implementation-dependent
1817 * instance of this class.
1818 *
1819 * <p> If the system property "{@systemProperty java.system.class.loader}"
1820 * is defined when this method is first invoked then the value of that
1821 * property is taken to be the name of a class that will be returned as the
1822 * system class loader. The class is loaded using the default system class
1823 * loader and must define a public constructor that takes a single parameter
1824 * of type {@code ClassLoader} which is used as the delegation parent. An
1825 * instance is then created using this constructor with the default system
1826 * class loader as the parameter. The resulting class loader is defined
1827 * to be the system class loader. During construction, the class loader
1828 * should take great care to avoid calling {@code getSystemClassLoader()}.
1829 * If circular initialization of the system class loader is detected then
1830 * an {@code IllegalStateException} is thrown.
1831 *
1832 * @implNote The system property to override the system class loader is not
1833 * examined until the VM is almost fully initialized. Code that executes
1834 * this method during startup should take care not to cache the return
1835 * value until the system is fully initialized.
1836 *
1837 * <p> The name of the built-in system class loader is {@code "app"}.
1838 * The system property "{@code java.class.path}" is read during early
1839 * initialization of the VM to determine the class path.
1840 * An empty value of "{@code java.class.path}" property is interpreted
1841 * differently depending on whether the initial module (the module
1842 * containing the main class) is named or unnamed:
1843 * If named, the built-in system class loader will have no class path and
1844 * will search for classes and resources using the application module path;
1845 * otherwise, if unnamed, it will set the class path to the current
1846 * working directory.
1847 *
1848 * <p> JAR files on the class path may contain a {@code Class-Path} manifest
1849 * attribute to specify dependent JAR files to be included in the class path.
1850 * {@code Class-Path} entries must meet certain conditions for validity (see
1851 * the <a href="{@docRoot}/../specs/jar/jar.html#class-path-attribute">
1852 * JAR File Specification</a> for details). Invalid {@code Class-Path}
1853 * entries are ignored. For debugging purposes, ignored entries can be
1854 * printed to the console if the
1855 * {@systemProperty jdk.net.URLClassPath.showIgnoredClassPathEntries} system
1856 * property is set to {@code true}.
1857 *
1858 * @return The system {@code ClassLoader}
1859 *
1860 * @throws IllegalStateException
1861 * If invoked recursively during the construction of the class
1862 * loader specified by the "{@code java.system.class.loader}"
1863 * property.
1864 *
1865 * @throws Error
1866 * If the system property "{@code java.system.class.loader}"
1867 * is defined but the named class could not be loaded, the
1868 * provider class does not define the required constructor, or an
1869 * exception is thrown by that constructor when it is invoked. The
1870 * underlying cause of the error can be retrieved via the
1871 * {@link Throwable#getCause()} method.
1872 */
1873 public static ClassLoader getSystemClassLoader() {
1874 switch (VM.initLevel()) {
1875 case 0:
1876 case 1:
1877 case 2:
1878 // the system class loader is the built-in app class loader during startup
1879 return getBuiltinAppClassLoader();
1880 case 3:
1881 String msg = "getSystemClassLoader cannot be called during the system class loader instantiation";
1882 throw new IllegalStateException(msg);
1883 default:
1884 // system fully initialized
1885 assert VM.isBooted() && Holder.scl != null;
1886 return Holder.scl;
1887 }
1888 }
1889
1890 static ClassLoader getBuiltinPlatformClassLoader() {
1891 return ClassLoaders.platformClassLoader();
1892 }
1893
1894 static ClassLoader getBuiltinAppClassLoader() {
1895 return ClassLoaders.appClassLoader();
1896 }
1897
1898 /*
1899 * Initialize the system class loader that may be a custom class on the
1900 * application class path or application module path.
1901 *
1902 * @see java.lang.System#initPhase3
1903 */
1904 static synchronized ClassLoader initSystemClassLoader() {
1905 if (VM.initLevel() != 3) {
1906 throw new InternalError("system class loader cannot be set at initLevel " +
1907 VM.initLevel());
1908 }
1909
1910 // detect recursive initialization
1911 if (Holder.scl != null) {
1912 throw new IllegalStateException("recursive invocation");
1913 }
1914
1915 ClassLoader builtinLoader = getBuiltinAppClassLoader();
1916 String cn = System.getProperty("java.system.class.loader");
1917 if (cn != null) {
1918 try {
1919 // custom class loader is only supported to be loaded from unnamed module
1920 Constructor<?> ctor = Class.forName(cn, false, builtinLoader)
1921 .getDeclaredConstructor(ClassLoader.class);
1922 Holder.scl = (ClassLoader) ctor.newInstance(builtinLoader);
1923 } catch (Exception e) {
1924 Throwable cause = e;
1925 if (e instanceof InvocationTargetException) {
1926 cause = e.getCause();
1927 if (cause instanceof Error) {
1928 throw (Error) cause;
1929 }
1930 }
1931 if (cause instanceof RuntimeException) {
1932 throw (RuntimeException) cause;
1933 }
1934 throw new Error(cause.getMessage(), cause);
1935 }
1936 } else {
1937 Holder.scl = builtinLoader;
1938 }
1939 return Holder.scl;
1940 }
1941
1942 // Returns the class's class loader, or null if none.
1943 static ClassLoader getClassLoader(Class<?> caller) {
1944 // This can be null if the VM is requesting it
1945 if (caller == null) {
1946 return null;
1947 }
1948 // Circumvent security check since this is package-private
1949 return caller.getClassLoader0();
1950 }
1951
1952 // Holder has the field(s) that need to be initialized during JVM bootstrap even if
1953 // the outer is aot-initialized.
1954 private static class Holder {
1955 // The system class loader
1956 // @GuardedBy("ClassLoader.class")
1957 private static volatile ClassLoader scl;
1958 }
1959
1960 // -- Package --
1961
1962 /**
1963 * Define a Package of the given Class object.
1964 *
1965 * If the given class represents an array type, a primitive type or void,
1966 * this method returns {@code null}.
1967 *
1968 * This method does not throw IllegalArgumentException.
1969 */
1970 Package definePackage(Class<?> c) {
1971 if (c.isPrimitive() || c.isArray()) {
1972 return null;
1973 }
1974
1975 return definePackage(c.getPackageName(), c.getModule());
1976 }
1977
1978 /**
1979 * Defines a Package of the given name and module
1980 *
1981 * This method does not throw IllegalArgumentException.
1982 *
1983 * @param name package name
1984 * @param m module
1985 */
1986 Package definePackage(String name, Module m) {
1987 if (name.isEmpty() && m.isNamed()) {
1988 throw new InternalError("unnamed package in " + m);
1989 }
1990
1991 // check if Package object is already defined
1992 NamedPackage pkg = packages.get(name);
1993 if (pkg instanceof Package)
1994 return (Package)pkg;
1995
1996 return (Package)packages.compute(name, (n, p) -> toPackage(n, p, m));
1997 }
1998
1999 /*
2000 * Returns a Package object for the named package
2001 */
2002 private Package toPackage(String name, NamedPackage p, Module m) {
2003 // define Package object if the named package is not yet defined
2004 if (p == null)
2005 return NamedPackage.toPackage(name, m);
2006
2007 // otherwise, replace the NamedPackage object with Package object
2008 if (p instanceof Package)
2009 return (Package)p;
2010
2011 return NamedPackage.toPackage(p.packageName(), p.module());
2012 }
2013
2014 /**
2015 * Defines a package by <a href="#binary-name">name</a> in this {@code ClassLoader}.
2016 * <p>
2017 * <a href="#binary-name">Package names</a> must be unique within a class loader and
2018 * cannot be redefined or changed once created.
2019 * <p>
2020 * If a class loader wishes to define a package with specific properties,
2021 * such as version information, then the class loader should call this
2022 * {@code definePackage} method before calling {@code defineClass}.
2023 * Otherwise, the
2024 * {@link #defineClass(String, byte[], int, int, ProtectionDomain) defineClass}
2025 * method will define a package in this class loader corresponding to the package
2026 * of the newly defined class; the properties of this defined package are
2027 * specified by {@link Package}.
2028 *
2029 * @apiNote
2030 * A class loader that wishes to define a package for classes in a JAR
2031 * typically uses the specification and implementation titles, versions, and
2032 * vendors from the JAR's manifest. If the package is specified as
2033 * {@linkplain java.util.jar.Attributes.Name#SEALED sealed} in the JAR's manifest,
2034 * the {@code URL} of the JAR file is typically used as the {@code sealBase}.
2035 * If classes of package {@code 'p'} defined by this class loader
2036 * are loaded from multiple JARs, the {@code Package} object may contain
2037 * different information depending on the first class of package {@code 'p'}
2038 * defined and which JAR's manifest is read first to explicitly define
2039 * package {@code 'p'}.
2040 *
2041 * <p> It is strongly recommended that a class loader does not call this
2042 * method to explicitly define packages in <em>named modules</em>; instead,
2043 * the package will be automatically defined when a class is {@linkplain
2044 * #defineClass(String, byte[], int, int, ProtectionDomain) being defined}.
2045 * If it is desirable to define {@code Package} explicitly, it should ensure
2046 * that all packages in a named module are defined with the properties
2047 * specified by {@link Package}. Otherwise, some {@code Package} objects
2048 * in a named module may be for example sealed with different seal base.
2049 *
2050 * @param name
2051 * The <a href="#binary-name">package name</a>
2052 *
2053 * @param specTitle
2054 * The specification title
2055 *
2056 * @param specVersion
2057 * The specification version
2058 *
2059 * @param specVendor
2060 * The specification vendor
2061 *
2062 * @param implTitle
2063 * The implementation title
2064 *
2065 * @param implVersion
2066 * The implementation version
2067 *
2068 * @param implVendor
2069 * The implementation vendor
2070 *
2071 * @param sealBase
2072 * If not {@code null}, then this package is sealed with
2073 * respect to the given code source {@link java.net.URL URL}
2074 * object. Otherwise, the package is not sealed.
2075 *
2076 * @return The newly defined {@code Package} object
2077 *
2078 * @throws NullPointerException
2079 * if {@code name} is {@code null}.
2080 *
2081 * @throws IllegalArgumentException
2082 * if a package of the given {@code name} is already
2083 * defined by this class loader
2084 *
2085 *
2086 * @since 1.2
2087 *
2088 * @jvms 5.3 Creation and Loading
2089 * @see <a href="{@docRoot}/../specs/jar/jar.html#package-sealing">
2090 * The JAR File Specification: Package Sealing</a>
2091 */
2092 protected Package definePackage(String name, String specTitle,
2093 String specVersion, String specVendor,
2094 String implTitle, String implVersion,
2095 String implVendor, URL sealBase)
2096 {
2097 Objects.requireNonNull(name);
2098
2099 // definePackage is not final and may be overridden by custom class loader
2100 Package p = new Package(name, specTitle, specVersion, specVendor,
2101 implTitle, implVersion, implVendor,
2102 sealBase, this);
2103
2104 if (packages.putIfAbsent(name, p) != null)
2105 throw new IllegalArgumentException(name);
2106
2107 return p;
2108 }
2109
2110 /**
2111 * Returns a {@code Package} of the given <a href="#binary-name">name</a> that
2112 * has been defined by this class loader.
2113 *
2114 * @param name The <a href="#binary-name">package name</a>
2115 *
2116 * @return The {@code Package} of the given name that has been defined
2117 * by this class loader, or {@code null} if not found
2118 *
2119 * @throws NullPointerException
2120 * if {@code name} is {@code null}.
2121 *
2122 * @jvms 5.3 Creation and Loading
2123 *
2124 * @since 9
2125 */
2126 public final Package getDefinedPackage(String name) {
2127 Objects.requireNonNull(name, "name cannot be null");
2128
2129 NamedPackage p = packages.get(name);
2130 if (p == null)
2131 return null;
2132
2133 return definePackage(name, p.module());
2134 }
2135
2136 /**
2137 * Returns all of the {@code Package}s that have been defined by
2138 * this class loader. The returned array has no duplicated {@code Package}s
2139 * of the same name.
2140 *
2141 * @apiNote This method returns an array rather than a {@code Set} or {@code Stream}
2142 * for consistency with the existing {@link #getPackages} method.
2143 *
2144 * @return The array of {@code Package} objects that have been defined by
2145 * this class loader; or a zero length array if no package has been
2146 * defined by this class loader.
2147 *
2148 * @jvms 5.3 Creation and Loading
2149 *
2150 * @since 9
2151 */
2152 public final Package[] getDefinedPackages() {
2153 return packages().toArray(Package[]::new);
2154 }
2155
2156 /**
2157 * Finds a package by <a href="#binary-name">name</a> in this class loader and its ancestors.
2158 * <p>
2159 * If this class loader defines a {@code Package} of the given name,
2160 * the {@code Package} is returned. Otherwise, the ancestors of
2161 * this class loader are searched recursively (parent by parent)
2162 * for a {@code Package} of the given name.
2163 *
2164 * @apiNote The {@link #getPlatformClassLoader() platform class loader}
2165 * may delegate to the application class loader but the application class
2166 * loader is not its ancestor. When invoked on the platform class loader,
2167 * this method will not find packages defined to the application
2168 * class loader.
2169 *
2170 * @param name
2171 * The <a href="#binary-name">package name</a>
2172 *
2173 * @return The {@code Package} of the given name that has been defined by
2174 * this class loader or its ancestors, or {@code null} if not found.
2175 *
2176 * @throws NullPointerException
2177 * if {@code name} is {@code null}.
2178 *
2179 * @deprecated
2180 * If multiple class loaders delegate to each other and define classes
2181 * with the same package name, and one such loader relies on the lookup
2182 * behavior of {@code getPackage} to return a {@code Package} from
2183 * a parent loader, then the properties exposed by the {@code Package}
2184 * may not be as expected in the rest of the program.
2185 * For example, the {@code Package} will only expose annotations from the
2186 * {@code package-info.class} file defined by the parent loader, even if
2187 * annotations exist in a {@code package-info.class} file defined by
2188 * a child loader. A more robust approach is to use the
2189 * {@link ClassLoader#getDefinedPackage} method which returns
2190 * a {@code Package} for the specified class loader.
2191 *
2192 * @see ClassLoader#getDefinedPackage(String)
2193 *
2194 * @since 1.2
2195 */
2196 @Deprecated(since="9")
2197 protected Package getPackage(String name) {
2198 Package pkg = getDefinedPackage(name);
2199 if (pkg == null) {
2200 if (parent != null) {
2201 pkg = parent.getPackage(name);
2202 } else {
2203 pkg = BootLoader.getDefinedPackage(name);
2204 }
2205 }
2206 return pkg;
2207 }
2208
2209 /**
2210 * Returns all of the {@code Package}s that have been defined by
2211 * this class loader and its ancestors. The returned array may contain
2212 * more than one {@code Package} object of the same package name, each
2213 * defined by a different class loader in the class loader hierarchy.
2214 *
2215 * @apiNote The {@link #getPlatformClassLoader() platform class loader}
2216 * may delegate to the application class loader. In other words,
2217 * packages in modules defined to the application class loader may be
2218 * visible to the platform class loader. On the other hand,
2219 * the application class loader is not its ancestor and hence
2220 * when invoked on the platform class loader, this method will not
2221 * return any packages defined to the application class loader.
2222 *
2223 * @return The array of {@code Package} objects that have been defined by
2224 * this class loader and its ancestors
2225 *
2226 * @see ClassLoader#getDefinedPackages()
2227 *
2228 * @since 1.2
2229 */
2230 protected Package[] getPackages() {
2231 Stream<Package> pkgs = packages();
2232 ClassLoader ld = parent;
2233 while (ld != null) {
2234 pkgs = Stream.concat(ld.packages(), pkgs);
2235 ld = ld.parent;
2236 }
2237 return Stream.concat(BootLoader.packages(), pkgs)
2238 .toArray(Package[]::new);
2239 }
2240
2241
2242
2243 // package-private
2244
2245 /**
2246 * Returns a stream of Packages defined in this class loader
2247 */
2248 Stream<Package> packages() {
2249 return packages.values().stream()
2250 .map(p -> definePackage(p.packageName(), p.module()));
2251 }
2252
2253 // -- Native library access --
2254
2255 /**
2256 * Returns the absolute path name of a native library. The VM invokes this
2257 * method to locate the native libraries that belong to classes loaded with
2258 * this class loader. If this method returns {@code null}, the VM
2259 * searches the library along the path specified as the
2260 * "{@code java.library.path}" property.
2261 *
2262 * @param libname
2263 * The library name
2264 *
2265 * @return The absolute path of the native library
2266 *
2267 * @see System#loadLibrary(String)
2268 * @see System#mapLibraryName(String)
2269 *
2270 * @since 1.2
2271 */
2272 protected String findLibrary(String libname) {
2273 return null;
2274 }
2275
2276 private final NativeLibraries libraries = NativeLibraries.newInstance(this);
2277
2278 // Invoked in the java.lang.Runtime class to implement load and loadLibrary.
2279 static NativeLibrary loadLibrary(Class<?> fromClass, File file) {
2280 ClassLoader loader = (fromClass == null) ? null : fromClass.getClassLoader();
2281 NativeLibraries libs = loader != null ? loader.libraries : BootLoader.getNativeLibraries();
2282 NativeLibrary nl = libs.loadLibrary(fromClass, file);
2283 if (nl != null) {
2284 return nl;
2285 }
2286 throw new UnsatisfiedLinkError("Can't load library: " + file);
2287 }
2288 static NativeLibrary loadLibrary(Class<?> fromClass, String name) {
2289 ClassLoader loader = (fromClass == null) ? null : fromClass.getClassLoader();
2290 if (loader == null) {
2291 NativeLibrary nl = BootLoader.getNativeLibraries().loadLibrary(fromClass, name);
2292 if (nl != null) {
2293 return nl;
2294 }
2295 throw new UnsatisfiedLinkError("no " + name +
2296 " in system library path: " + StaticProperty.sunBootLibraryPath());
2297 }
2298
2299 NativeLibraries libs = loader.libraries;
2300 // First load from the file returned from ClassLoader::findLibrary, if found.
2301 String libfilename = loader.findLibrary(name);
2302 if (libfilename != null) {
2303 File libfile = new File(libfilename);
2304 if (!libfile.isAbsolute()) {
2305 throw new UnsatisfiedLinkError(
2306 "ClassLoader.findLibrary failed to return an absolute path: " + libfilename);
2307 }
2308 NativeLibrary nl = libs.loadLibrary(fromClass, libfile);
2309 if (nl != null) {
2310 return nl;
2311 }
2312 throw new UnsatisfiedLinkError("Can't load " + libfilename);
2313 }
2314 // Then load from system library path and java library path
2315 NativeLibrary nl = libs.loadLibrary(fromClass, name);
2316 if (nl != null) {
2317 return nl;
2318 }
2319
2320 // Oops, it failed
2321 throw new UnsatisfiedLinkError("no " + name +
2322 " in java.library.path: " + StaticProperty.javaLibraryPath());
2323 }
2324
2325 /**
2326 * Invoked in the VM class linking code.
2327 * @param loader the class loader used to look up the native library symbol
2328 * @param clazz the class in which the native method is declared
2329 * @param entryName the native method's mangled name (this is the name used for the native lookup)
2330 * @param javaName the native method's declared name
2331 */
2332 static long findNative(ClassLoader loader, Class<?> clazz, String entryName, String javaName) {
2333 NativeLibraries nativeLibraries = nativeLibrariesFor(loader);
2334 long addr = nativeLibraries.find(entryName);
2335 if (addr != 0 && loader != null) {
2336 Reflection.ensureNativeAccess(clazz, clazz, javaName, true);
2337 }
2338 return addr;
2339 }
2340
2341 /*
2342 * This is also called by SymbolLookup::loaderLookup. In that case, we need
2343 * to avoid a restricted check, as that check has already been performed when
2344 * obtaining the lookup.
2345 */
2346 static NativeLibraries nativeLibrariesFor(ClassLoader loader) {
2347 if (loader == null) {
2348 return BootLoader.getNativeLibraries();
2349 } else {
2350 return loader.libraries;
2351 }
2352 }
2353
2354 // -- Assertion management --
2355
2356 final Object assertionLock;
2357
2358 // The default toggle for assertion checking.
2359 // @GuardedBy("assertionLock")
2360 private boolean defaultAssertionStatus = false;
2361
2362 // Maps String packageName to Boolean package default assertion status Note
2363 // that the default package is placed under a null map key. If this field
2364 // is null then we are delegating assertion status queries to the VM, i.e.,
2365 // none of this ClassLoader's assertion status modification methods have
2366 // been invoked.
2367 // @GuardedBy("assertionLock")
2368 private Map<String, Boolean> packageAssertionStatus = null;
2369
2370 // Maps String fullyQualifiedClassName to Boolean assertionStatus If this
2371 // field is null then we are delegating assertion status queries to the VM,
2372 // i.e., none of this ClassLoader's assertion status modification methods
2373 // have been invoked.
2374 // @GuardedBy("assertionLock")
2375 Map<String, Boolean> classAssertionStatus = null;
2376
2377 /**
2378 * Sets the default assertion status for this class loader. This setting
2379 * determines whether classes loaded by this class loader and initialized
2380 * in the future will have assertions enabled or disabled by default.
2381 * This setting may be overridden on a per-package or per-class basis by
2382 * invoking {@link #setPackageAssertionStatus(String, boolean)} or {@link
2383 * #setClassAssertionStatus(String, boolean)}.
2384 *
2385 * @param enabled
2386 * {@code true} if classes loaded by this class loader will
2387 * henceforth have assertions enabled by default, {@code false}
2388 * if they will have assertions disabled by default.
2389 *
2390 * @since 1.4
2391 */
2392 public void setDefaultAssertionStatus(boolean enabled) {
2393 synchronized (assertionLock) {
2394 if (classAssertionStatus == null)
2395 initializeJavaAssertionMaps();
2396
2397 defaultAssertionStatus = enabled;
2398 }
2399 }
2400
2401 /**
2402 * Sets the package default assertion status for the named package. The
2403 * package default assertion status determines the assertion status for
2404 * classes initialized in the future that belong to the named package or
2405 * any of its "subpackages".
2406 *
2407 * <p> A subpackage of a package named p is any package whose name begins
2408 * with "{@code p.}". For example, {@code javax.swing.text} is a
2409 * subpackage of {@code javax.swing}, and both {@code java.util} and
2410 * {@code java.lang.reflect} are subpackages of {@code java}.
2411 *
2412 * <p> In the event that multiple package defaults apply to a given class,
2413 * the package default pertaining to the most specific package takes
2414 * precedence over the others. For example, if {@code javax.lang} and
2415 * {@code javax.lang.reflect} both have package defaults associated with
2416 * them, the latter package default applies to classes in
2417 * {@code javax.lang.reflect}.
2418 *
2419 * <p> Package defaults take precedence over the class loader's default
2420 * assertion status, and may be overridden on a per-class basis by invoking
2421 * {@link #setClassAssertionStatus(String, boolean)}. </p>
2422 *
2423 * @param packageName
2424 * The name of the package whose package default assertion status
2425 * is to be set. A {@code null} value indicates the unnamed
2426 * package that is "current"
2427 * (see section {@jls 7.4.2} of
2428 * <cite>The Java Language Specification</cite>.)
2429 *
2430 * @param enabled
2431 * {@code true} if classes loaded by this classloader and
2432 * belonging to the named package or any of its subpackages will
2433 * have assertions enabled by default, {@code false} if they will
2434 * have assertions disabled by default.
2435 *
2436 * @since 1.4
2437 */
2438 public void setPackageAssertionStatus(String packageName,
2439 boolean enabled) {
2440 synchronized (assertionLock) {
2441 if (packageAssertionStatus == null)
2442 initializeJavaAssertionMaps();
2443
2444 packageAssertionStatus.put(packageName, enabled);
2445 }
2446 }
2447
2448 /**
2449 * Sets the desired assertion status for the named top-level class in this
2450 * class loader and any nested classes contained therein. This setting
2451 * takes precedence over the class loader's default assertion status, and
2452 * over any applicable per-package default. This method has no effect if
2453 * the named class has already been initialized. (Once a class is
2454 * initialized, its assertion status cannot change.)
2455 *
2456 * <p> If the named class is not a top-level class, this invocation will
2457 * have no effect on the actual assertion status of any class. </p>
2458 *
2459 * @param className
2460 * The fully qualified class name of the top-level class whose
2461 * assertion status is to be set.
2462 *
2463 * @param enabled
2464 * {@code true} if the named class is to have assertions
2465 * enabled when (and if) it is initialized, {@code false} if the
2466 * class is to have assertions disabled.
2467 *
2468 * @since 1.4
2469 */
2470 public void setClassAssertionStatus(String className, boolean enabled) {
2471 synchronized (assertionLock) {
2472 if (classAssertionStatus == null)
2473 initializeJavaAssertionMaps();
2474
2475 classAssertionStatus.put(className, enabled);
2476 }
2477 }
2478
2479 /**
2480 * Sets the default assertion status for this class loader to
2481 * {@code false} and discards any package defaults or class assertion
2482 * status settings associated with the class loader. This method is
2483 * provided so that class loaders can be made to ignore any command line or
2484 * persistent assertion status settings and "start with a clean slate."
2485 *
2486 * @since 1.4
2487 */
2488 public void clearAssertionStatus() {
2489 /*
2490 * Whether or not "Java assertion maps" are initialized, set
2491 * them to empty maps, effectively ignoring any present settings.
2492 */
2493 synchronized (assertionLock) {
2494 classAssertionStatus = new HashMap<>();
2495 packageAssertionStatus = new HashMap<>();
2496 defaultAssertionStatus = false;
2497 }
2498 }
2499
2500 /**
2501 * Returns the assertion status that would be assigned to the specified
2502 * class if it were to be initialized at the time this method is invoked.
2503 * If the named class has had its assertion status set, the most recent
2504 * setting will be returned; otherwise, if any package default assertion
2505 * status pertains to this class, the most recent setting for the most
2506 * specific pertinent package default assertion status is returned;
2507 * otherwise, this class loader's default assertion status is returned.
2508 * </p>
2509 *
2510 * @param className
2511 * The fully qualified class name of the class whose desired
2512 * assertion status is being queried.
2513 *
2514 * @return The desired assertion status of the specified class.
2515 *
2516 * @see #setClassAssertionStatus(String, boolean)
2517 * @see #setPackageAssertionStatus(String, boolean)
2518 * @see #setDefaultAssertionStatus(boolean)
2519 *
2520 * @since 1.4
2521 */
2522 boolean desiredAssertionStatus(String className) {
2523 synchronized (assertionLock) {
2524 // assert classAssertionStatus != null;
2525 // assert packageAssertionStatus != null;
2526
2527 // Check for a class entry
2528 Boolean result = classAssertionStatus.get(className);
2529 if (result != null)
2530 return result.booleanValue();
2531
2532 // Check for most specific package entry
2533 int dotIndex = className.lastIndexOf('.');
2534 if (dotIndex < 0) { // default package
2535 result = packageAssertionStatus.get(null);
2536 if (result != null)
2537 return result.booleanValue();
2538 }
2539 while(dotIndex > 0) {
2540 className = className.substring(0, dotIndex);
2541 result = packageAssertionStatus.get(className);
2542 if (result != null)
2543 return result.booleanValue();
2544 dotIndex = className.lastIndexOf('.', dotIndex-1);
2545 }
2546
2547 // Return the classloader default
2548 return defaultAssertionStatus;
2549 }
2550 }
2551
2552 // Set up the assertions with information provided by the VM.
2553 // Note: Should only be called inside a synchronized block
2554 private void initializeJavaAssertionMaps() {
2555 // assert Thread.holdsLock(assertionLock);
2556
2557 classAssertionStatus = new HashMap<>();
2558 packageAssertionStatus = new HashMap<>();
2559 AssertionStatusDirectives directives = retrieveDirectives();
2560
2561 for(int i = 0; i < directives.classes.length; i++)
2562 classAssertionStatus.put(directives.classes[i],
2563 directives.classEnabled[i]);
2564
2565 for(int i = 0; i < directives.packages.length; i++)
2566 packageAssertionStatus.put(directives.packages[i],
2567 directives.packageEnabled[i]);
2568
2569 defaultAssertionStatus = directives.deflt;
2570 }
2571
2572 // Retrieves the assertion directives from the VM.
2573 private static native AssertionStatusDirectives retrieveDirectives();
2574
2575
2576 // -- Misc --
2577
2578 /**
2579 * Returns the ConcurrentHashMap used as a storage for ClassLoaderValue(s)
2580 * associated with this ClassLoader, creating it if it doesn't already exist.
2581 */
2582 ConcurrentHashMap<?, ?> createOrGetClassLoaderValueMap() {
2583 ConcurrentHashMap<?, ?> map = classLoaderValueMap;
2584 if (map == null) {
2585 map = new ConcurrentHashMap<>();
2586 boolean set = trySetObjectField("classLoaderValueMap", map);
2587 if (!set) {
2588 // beaten by someone else
2589 map = classLoaderValueMap;
2590 }
2591 }
2592 return map;
2593 }
2594
2595 // the storage for ClassLoaderValue(s) associated with this ClassLoader
2596 private volatile ConcurrentHashMap<?, ?> classLoaderValueMap;
2597
2598 /**
2599 * Attempts to atomically set a volatile field in this object. Returns
2600 * {@code true} if not beaten by another thread. Avoids the use of
2601 * AtomicReferenceFieldUpdater in this class.
2602 */
2603 private boolean trySetObjectField(String name, Object obj) {
2604 Unsafe unsafe = Unsafe.getUnsafe();
2605 long offset = unsafe.objectFieldOffset(ClassLoader.class, name);
2606 return unsafe.compareAndSetReference(this, offset, null, obj);
2607 }
2608
2609 private void reinitObjectField(String name, Object obj) {
2610 Unsafe unsafe = Unsafe.getUnsafe();
2611 long offset = unsafe.objectFieldOffset(ClassLoader.class, name);
2612
2613 // Extra safety: check the types
2614 Object current = unsafe.getReference(this, offset);
2615 if (current.getClass() != obj.getClass()) {
2616 throw new IllegalStateException("Wrong field type");
2617 }
2618
2619 unsafe.putReference(this, offset, obj);
2620 }
2621
2622 /**
2623 * Called only by the VM, during -Xshare:dump.
2624 *
2625 * @implNote This is done while the JVM is running in single-threaded mode,
2626 * and at the very end of Java bytecode execution. We know that no more classes
2627 * will be loaded and none of the fields modified by this method will be used again.
2628 */
2629 private void resetArchivedStates() {
2630 if (parallelLockMap != null) {
2631 reinitObjectField("parallelLockMap", new ConcurrentHashMap<>());
2632 }
2633
2634 if (CDS.isDumpingAOTLinkedClasses()) {
2635 if (System.getProperty("cds.debug.archived.packages") != null) {
2636 for (Map.Entry<String, NamedPackage> entry : packages.entrySet()) {
2637 String key = entry.getKey();
2638 NamedPackage value = entry.getValue();
2639 System.out.println("Archiving " +
2640 (value instanceof Package ? "Package" : "NamedPackage") +
2641 " \"" + key + "\" for " + this);
2642 }
2643 }
2644 } else {
2645 reinitObjectField("packages", new ConcurrentHashMap<>());
2646 }
2647
2648 reinitObjectField("package2certs", new ConcurrentHashMap<>());
2649 classes.clear();
2650 classes.trimToSize();
2651 classLoaderValueMap = null;
2652 libraries.clear();
2653 }
2654 }
2655
2656 /*
2657 * A utility class that will enumerate over an array of enumerations.
2658 */
2659 final class CompoundEnumeration<E> implements Enumeration<E> {
2660 private final Enumeration<E>[] enums;
2661 private int index;
2662
2663 public CompoundEnumeration(Enumeration<E>[] enums) {
2664 this.enums = enums;
2665 }
2666
2667 private boolean next() {
2668 while (index < enums.length) {
2669 if (enums[index] != null && enums[index].hasMoreElements()) {
2670 return true;
2671 }
2672 index++;
2673 }
2674 return false;
2675 }
2676
2677 public boolean hasMoreElements() {
2678 return next();
2679 }
2680
2681 public E nextElement() {
2682 if (!next()) {
2683 throw new NoSuchElementException();
2684 }
2685 return enums[index].nextElement();
2686 }
2687 }