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