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