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