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