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