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