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