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