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