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