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