1 /*
   2  * Copyright (c) 2013, 2019, Oracle and/or its affiliates. All rights reserved.
   3  * Copyright (c) 2019, Azul Systems, Inc. All rights reserved.
   4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   5  *
   6  * This code is free software; you can redistribute it and/or modify it
   7  * under the terms of the GNU General Public License version 2 only, as
   8  * published by the Free Software Foundation.  Oracle designates this
   9  * particular file as subject to the "Classpath" exception as provided
  10  * by Oracle in the LICENSE file that accompanied this code.
  11  *
  12  * This code is distributed in the hope that it will be useful, but WITHOUT
  13  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  14  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  15  * version 2 for more details (a copy is included in the LICENSE file that
  16  * accompanied this code).
  17  *
  18  * You should have received a copy of the GNU General Public License version
  19  * 2 along with this work; if not, write to the Free Software Foundation,
  20  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  21  *
  22  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  23  * or visit www.oracle.com if you need additional information or have any
  24  * questions.
  25  */
  26 
  27 package java.lang;
  28 
  29 import java.io.InputStream;
  30 import java.io.IOException;
  31 import java.io.UncheckedIOException;
  32 import java.io.File;
  33 import java.lang.reflect.Constructor;
  34 import java.lang.reflect.InvocationTargetException;
  35 import java.net.URL;
  36 import java.security.AccessController;
  37 import java.security.AccessControlContext;
  38 import java.security.CodeSource;
  39 import java.security.PrivilegedAction;
  40 import java.security.ProtectionDomain;
  41 import java.security.cert.Certificate;
  42 import java.util.ArrayDeque;
  43 import java.util.Arrays;
  44 import java.util.Collections;
  45 import java.util.Deque;
  46 import java.util.Enumeration;
  47 import java.util.HashMap;
  48 import java.util.HashSet;
  49 import java.util.Hashtable;
  50 import java.util.Map;
  51 import java.util.NoSuchElementException;
  52 import java.util.Objects;
  53 import java.util.Set;
  54 import java.util.Spliterator;
  55 import java.util.Spliterators;
  56 import java.util.Vector;
  57 import java.util.WeakHashMap;
  58 import java.util.concurrent.ConcurrentHashMap;
  59 import java.util.function.Supplier;
  60 import java.util.stream.Stream;
  61 import java.util.stream.StreamSupport;
  62 
  63 import jdk.internal.loader.BuiltinClassLoader;
  64 import jdk.internal.perf.PerfCounter;
  65 import jdk.internal.loader.BootLoader;
  66 import jdk.internal.loader.ClassLoaders;
  67 import jdk.internal.misc.Unsafe;
  68 import jdk.internal.misc.VM;
  69 import jdk.internal.ref.CleanerFactory;
  70 import jdk.internal.reflect.CallerSensitive;
  71 import jdk.internal.reflect.Reflection;
  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  * <h2> <a id="builtinLoaders">Run-time Built-in Class Loaders</a></h2>
 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     /**
1122      * Defines a class of the given flags via Lookup.defineClass.
1123      *
1124      * @param loader the defining loader
1125      * @param lookup nest host of the Class to be defined
1126      * @param name the binary name or {@code null} if not findable
1127      * @param b class bytes
1128      * @param off the start offset in {@code b} of the class bytes
1129      * @param len the length of the class bytes
1130      * @param pd protection domain
1131      * @param initialize initialize the class
1132      * @param flags flags
1133      * @param classData class data
1134      */
1135     static native Class<?> defineClass0(ClassLoader loader,
1136                                         Class<?> lookup,
1137                                         String name,
1138                                         byte[] b, int off, int len,
1139                                         ProtectionDomain pd,
1140                                         boolean initialize,
1141                                         int flags,
1142                                         Object classData);
1143 
1144     // true if the name is null or has the potential to be a valid binary name
1145     private boolean checkName(String name) {
1146         if ((name == null) || (name.isEmpty()))
1147             return true;
1148         if ((name.indexOf('/') != -1) || (name.charAt(0) == '['))
1149             return false;
1150         return true;
1151     }
1152 
1153     private void checkCerts(String name, CodeSource cs) {
1154         int i = name.lastIndexOf('.');
1155         String pname = (i == -1) ? "" : name.substring(0, i);
1156 
1157         Certificate[] certs = null;
1158         if (cs != null) {
1159             certs = cs.getCertificates();
1160         }
1161         Certificate[] pcerts = null;
1162         if (parallelLockMap == null) {
1163             synchronized (this) {
1164                 pcerts = package2certs.get(pname);
1165                 if (pcerts == null) {
1166                     package2certs.put(pname, (certs == null? nocerts:certs));
1167                 }
1168             }
1169         } else {
1170             pcerts = ((ConcurrentHashMap<String, Certificate[]>)package2certs).
1171                 putIfAbsent(pname, (certs == null? nocerts:certs));
1172         }
1173         if (pcerts != null && !compareCerts(pcerts, certs)) {
1174             throw new SecurityException("class \"" + name
1175                 + "\"'s signer information does not match signer information"
1176                 + " of other classes in the same package");
1177         }
1178     }
1179 
1180     /**
1181      * check to make sure the certs for the new class (certs) are the same as
1182      * the certs for the first class inserted in the package (pcerts)
1183      */
1184     private boolean compareCerts(Certificate[] pcerts,
1185                                  Certificate[] certs)
1186     {
1187         // certs can be null, indicating no certs.
1188         if ((certs == null) || (certs.length == 0)) {
1189             return pcerts.length == 0;
1190         }
1191 
1192         // the length must be the same at this point
1193         if (certs.length != pcerts.length)
1194             return false;
1195 
1196         // go through and make sure all the certs in one array
1197         // are in the other and vice-versa.
1198         boolean match;
1199         for (Certificate cert : certs) {
1200             match = false;
1201             for (Certificate pcert : pcerts) {
1202                 if (cert.equals(pcert)) {
1203                     match = true;
1204                     break;
1205                 }
1206             }
1207             if (!match) return false;
1208         }
1209 
1210         // now do the same for pcerts
1211         for (Certificate pcert : pcerts) {
1212             match = false;
1213             for (Certificate cert : certs) {
1214                 if (pcert.equals(cert)) {
1215                     match = true;
1216                     break;
1217                 }
1218             }
1219             if (!match) return false;
1220         }
1221 
1222         return true;
1223     }
1224 
1225     /**
1226      * Links the specified class.  This (misleadingly named) method may be
1227      * used by a class loader to link a class.  If the class {@code c} has
1228      * already been linked, then this method simply returns. Otherwise, the
1229      * class is linked as described in the "Execution" chapter of
1230      * <cite>The Java&trade; Language Specification</cite>.
1231      *
1232      * @param  c
1233      *         The class to link
1234      *
1235      * @throws  NullPointerException
1236      *          If {@code c} is {@code null}.
1237      *
1238      * @see  #defineClass(String, byte[], int, int)
1239      */
1240     protected final void resolveClass(Class<?> c) {
1241         if (c == null) {
1242             throw new NullPointerException();
1243         }
1244     }
1245 
1246     /**
1247      * Finds a class with the specified <a href="#binary-name">binary name</a>,
1248      * loading it if necessary.
1249      *
1250      * <p> This method loads the class through the system class loader (see
1251      * {@link #getSystemClassLoader()}).  The {@code Class} object returned
1252      * might have more than one {@code ClassLoader} associated with it.
1253      * Subclasses of {@code ClassLoader} need not usually invoke this method,
1254      * because most class loaders need to override just {@link
1255      * #findClass(String)}.  </p>
1256      *
1257      * @param  name
1258      *         The <a href="#binary-name">binary name</a> of the class
1259      *
1260      * @return  The {@code Class} object for the specified {@code name}
1261      *
1262      * @throws  ClassNotFoundException
1263      *          If the class could not be found
1264      *
1265      * @see  #ClassLoader(ClassLoader)
1266      * @see  #getParent()
1267      */
1268     protected final Class<?> findSystemClass(String name)
1269         throws ClassNotFoundException
1270     {
1271         return getSystemClassLoader().loadClass(name);
1272     }
1273 
1274     /**
1275      * Returns a class loaded by the bootstrap class loader;
1276      * or return null if not found.
1277      */
1278     Class<?> findBootstrapClassOrNull(String name) {
1279         if (!checkName(name)) return null;
1280 
1281         return findBootstrapClass(name);
1282     }
1283 
1284     // return null if not found
1285     private native Class<?> findBootstrapClass(String name);
1286 
1287     /**
1288      * Returns the class with the given <a href="#binary-name">binary name</a> if this
1289      * loader has been recorded by the Java virtual machine as an initiating
1290      * loader of a class with that <a href="#binary-name">binary name</a>.  Otherwise
1291      * {@code null} is returned.
1292      *
1293      * @param  name
1294      *         The <a href="#binary-name">binary name</a> of the class
1295      *
1296      * @return  The {@code Class} object, or {@code null} if the class has
1297      *          not been loaded
1298      *
1299      * @since  1.1
1300      */
1301     protected final Class<?> findLoadedClass(String name) {
1302         if (!checkName(name))
1303             return null;
1304         return findLoadedClass0(name);
1305     }
1306 
1307     private final native Class<?> findLoadedClass0(String name);
1308 
1309     /**
1310      * Sets the signers of a class.  This should be invoked after defining a
1311      * class.
1312      *
1313      * @param  c
1314      *         The {@code Class} object
1315      *
1316      * @param  signers
1317      *         The signers for the class
1318      *
1319      * @since  1.1
1320      */
1321     protected final void setSigners(Class<?> c, Object[] signers) {
1322         c.setSigners(signers);
1323     }
1324 
1325 
1326     // -- Resources --
1327 
1328     /**
1329      * Returns a URL to a resource in a module defined to this class loader.
1330      * Class loader implementations that support loading from modules
1331      * should override this method.
1332      *
1333      * @apiNote This method is the basis for the {@link
1334      * Class#getResource Class.getResource}, {@link Class#getResourceAsStream
1335      * Class.getResourceAsStream}, and {@link Module#getResourceAsStream
1336      * Module.getResourceAsStream} methods. It is not subject to the rules for
1337      * encapsulation specified by {@code Module.getResourceAsStream}.
1338      *
1339      * @implSpec The default implementation attempts to find the resource by
1340      * invoking {@link #findResource(String)} when the {@code moduleName} is
1341      * {@code null}. It otherwise returns {@code null}.
1342      *
1343      * @param  moduleName
1344      *         The module name; or {@code null} to find a resource in the
1345      *         {@linkplain #getUnnamedModule() unnamed module} for this
1346      *         class loader
1347      * @param  name
1348      *         The resource name
1349      *
1350      * @return A URL to the resource; {@code null} if the resource could not be
1351      *         found, a URL could not be constructed to locate the resource,
1352      *         access to the resource is denied by the security manager, or
1353      *         there isn't a module of the given name defined to the class
1354      *         loader.
1355      *
1356      * @throws IOException
1357      *         If I/O errors occur
1358      *
1359      * @see java.lang.module.ModuleReader#find(String)
1360      * @since 9
1361      * @spec JPMS
1362      */
1363     protected URL findResource(String moduleName, String name) throws IOException {
1364         if (moduleName == null) {
1365             return findResource(name);
1366         } else {
1367             return null;
1368         }
1369     }
1370 
1371     /**
1372      * Finds the resource with the given name.  A resource is some data
1373      * (images, audio, text, etc) that can be accessed by class code in a way
1374      * that is independent of the location of the code.
1375      *
1376      * <p> The name of a resource is a '{@code /}'-separated path name that
1377      * identifies the resource. </p>
1378      *
1379      * <p> Resources in named modules are subject to the encapsulation rules
1380      * specified by {@link Module#getResourceAsStream Module.getResourceAsStream}.
1381      * Additionally, and except for the special case where the resource has a
1382      * name ending with "{@code .class}", this method will only find resources in
1383      * packages of named modules when the package is {@link Module#isOpen(String)
1384      * opened} unconditionally (even if the caller of this method is in the
1385      * same module as the resource). </p>
1386      *
1387      * @implSpec The default implementation will first search the parent class
1388      * loader for the resource; if the parent is {@code null} the path of the
1389      * class loader built into the virtual machine is searched. If not found,
1390      * this method will invoke {@link #findResource(String)} to find the resource.
1391      *
1392      * @apiNote Where several modules are defined to the same class loader,
1393      * and where more than one module contains a resource with the given name,
1394      * then the ordering that modules are searched is not specified and may be
1395      * very unpredictable.
1396      * When overriding this method it is recommended that an implementation
1397      * ensures that any delegation is consistent with the {@link
1398      * #getResources(java.lang.String) getResources(String)} method.
1399      *
1400      * @param  name
1401      *         The resource name
1402      *
1403      * @return  {@code URL} object for reading the resource; {@code null} if
1404      *          the resource could not be found, a {@code URL} could not be
1405      *          constructed to locate the resource, the resource is in a package
1406      *          that is not opened unconditionally, or access to the resource is
1407      *          denied by the security manager.
1408      *
1409      * @throws  NullPointerException If {@code name} is {@code null}
1410      *
1411      * @since  1.1
1412      * @revised 9
1413      * @spec JPMS
1414      */
1415     public URL getResource(String name) {
1416         Objects.requireNonNull(name);
1417         URL url;
1418         if (parent != null) {
1419             url = parent.getResource(name);
1420         } else {
1421             url = BootLoader.findResource(name);
1422         }
1423         if (url == null) {
1424             url = findResource(name);
1425         }
1426         return url;
1427     }
1428 
1429     /**
1430      * Finds all the resources with the given name. A resource is some data
1431      * (images, audio, text, etc) that can be accessed by class code in a way
1432      * that is independent of the location of the code.
1433      *
1434      * <p> The name of a resource is a {@code /}-separated path name that
1435      * identifies the resource. </p>
1436      *
1437      * <p> Resources in named modules are subject to the encapsulation rules
1438      * specified by {@link Module#getResourceAsStream Module.getResourceAsStream}.
1439      * Additionally, and except for the special case where the resource has a
1440      * name ending with "{@code .class}", this method will only find resources in
1441      * packages of named modules when the package is {@link Module#isOpen(String)
1442      * opened} unconditionally (even if the caller of this method is in the
1443      * same module as the resource). </p>
1444      *
1445      * @implSpec The default implementation will first search the parent class
1446      * loader for the resource; if the parent is {@code null} the path of the
1447      * class loader built into the virtual machine is searched. It then
1448      * invokes {@link #findResources(String)} to find the resources with the
1449      * name in this class loader. It returns an enumeration whose elements
1450      * are the URLs found by searching the parent class loader followed by
1451      * the elements found with {@code findResources}.
1452      *
1453      * @apiNote Where several modules are defined to the same class loader,
1454      * and where more than one module contains a resource with the given name,
1455      * then the ordering is not specified and may be very unpredictable.
1456      * When overriding this method it is recommended that an
1457      * implementation ensures that any delegation is consistent with the {@link
1458      * #getResource(java.lang.String) getResource(String)} method. This should
1459      * ensure that the first element returned by the Enumeration's
1460      * {@code nextElement} method is the same resource that the
1461      * {@code getResource(String)} method would return.
1462      *
1463      * @param  name
1464      *         The resource name
1465      *
1466      * @return  An enumeration of {@link java.net.URL URL} objects for the
1467      *          resource. If no resources could be found, the enumeration will
1468      *          be empty. Resources for which a {@code URL} cannot be
1469      *          constructed, are in a package that is not opened
1470      *          unconditionally, or access to the resource is denied by the
1471      *          security manager, are not returned in the enumeration.
1472      *
1473      * @throws  IOException
1474      *          If I/O errors occur
1475      * @throws  NullPointerException If {@code name} is {@code null}
1476      *
1477      * @since  1.2
1478      * @revised 9
1479      * @spec JPMS
1480      */
1481     public Enumeration<URL> getResources(String name) throws IOException {
1482         Objects.requireNonNull(name);
1483         @SuppressWarnings("unchecked")
1484         Enumeration<URL>[] tmp = (Enumeration<URL>[]) new Enumeration<?>[2];
1485         if (parent != null) {
1486             tmp[0] = parent.getResources(name);
1487         } else {
1488             tmp[0] = BootLoader.findResources(name);
1489         }
1490         tmp[1] = findResources(name);
1491 
1492         return new CompoundEnumeration<>(tmp);
1493     }
1494 
1495     /**
1496      * Returns a stream whose elements are the URLs of all the resources with
1497      * the given name. A resource is some data (images, audio, text, etc) that
1498      * can be accessed by class code in a way that is independent of the
1499      * location of the code.
1500      *
1501      * <p> The name of a resource is a {@code /}-separated path name that
1502      * identifies the resource.
1503      *
1504      * <p> The resources will be located when the returned stream is evaluated.
1505      * If the evaluation results in an {@code IOException} then the I/O
1506      * exception is wrapped in an {@link UncheckedIOException} that is then
1507      * thrown.
1508      *
1509      * <p> Resources in named modules are subject to the encapsulation rules
1510      * specified by {@link Module#getResourceAsStream Module.getResourceAsStream}.
1511      * Additionally, and except for the special case where the resource has a
1512      * name ending with "{@code .class}", this method will only find resources in
1513      * packages of named modules when the package is {@link Module#isOpen(String)
1514      * opened} unconditionally (even if the caller of this method is in the
1515      * same module as the resource). </p>
1516      *
1517      * @implSpec The default implementation invokes {@link #getResources(String)
1518      * getResources} to find all the resources with the given name and returns
1519      * a stream with the elements in the enumeration as the source.
1520      *
1521      * @apiNote When overriding this method it is recommended that an
1522      * implementation ensures that any delegation is consistent with the {@link
1523      * #getResource(java.lang.String) getResource(String)} method. This should
1524      * ensure that the first element returned by the stream is the same
1525      * resource that the {@code getResource(String)} method would return.
1526      *
1527      * @param  name
1528      *         The resource name
1529      *
1530      * @return  A stream of resource {@link java.net.URL URL} objects. If no
1531      *          resources could  be found, the stream will be empty. Resources
1532      *          for which a {@code URL} cannot be constructed, are in a package
1533      *          that is not opened unconditionally, or access to the resource
1534      *          is denied by the security manager, will not be in the stream.
1535      *
1536      * @throws  NullPointerException If {@code name} is {@code null}
1537      *
1538      * @since  9
1539      */
1540     public Stream<URL> resources(String name) {
1541         Objects.requireNonNull(name);
1542         int characteristics = Spliterator.NONNULL | Spliterator.IMMUTABLE;
1543         Supplier<Spliterator<URL>> si = () -> {
1544             try {
1545                 return Spliterators.spliteratorUnknownSize(
1546                     getResources(name).asIterator(), characteristics);
1547             } catch (IOException e) {
1548                 throw new UncheckedIOException(e);
1549             }
1550         };
1551         return StreamSupport.stream(si, characteristics, false);
1552     }
1553 
1554     /**
1555      * Finds the resource with the given name. Class loader implementations
1556      * should override this method.
1557      *
1558      * <p> For resources in named modules then the method must implement the
1559      * rules for encapsulation specified in the {@code Module} {@link
1560      * Module#getResourceAsStream getResourceAsStream} method. Additionally,
1561      * it must not find non-"{@code .class}" resources in packages of named
1562      * modules unless the package is {@link Module#isOpen(String) opened}
1563      * unconditionally. </p>
1564      *
1565      * @implSpec The default implementation returns {@code null}.
1566      *
1567      * @param  name
1568      *         The resource name
1569      *
1570      * @return  {@code URL} object for reading the resource; {@code null} if
1571      *          the resource could not be found, a {@code URL} could not be
1572      *          constructed to locate the resource, the resource is in a package
1573      *          that is not opened unconditionally, or access to the resource is
1574      *          denied by the security manager.
1575      *
1576      * @since  1.2
1577      * @revised 9
1578      * @spec JPMS
1579      */
1580     protected URL findResource(String name) {
1581         return null;
1582     }
1583 
1584     /**
1585      * Returns an enumeration of {@link java.net.URL URL} objects
1586      * representing all the resources with the given name. Class loader
1587      * implementations should override this method.
1588      *
1589      * <p> For resources in named modules then the method must implement the
1590      * rules for encapsulation specified in the {@code Module} {@link
1591      * Module#getResourceAsStream getResourceAsStream} method. Additionally,
1592      * it must not find non-"{@code .class}" resources in packages of named
1593      * modules unless the package is {@link Module#isOpen(String) opened}
1594      * unconditionally. </p>
1595      *
1596      * @implSpec The default implementation returns an enumeration that
1597      * contains no elements.
1598      *
1599      * @param  name
1600      *         The resource name
1601      *
1602      * @return  An enumeration of {@link java.net.URL URL} objects for
1603      *          the resource. If no resources could  be found, the enumeration
1604      *          will be empty. Resources for which a {@code URL} cannot be
1605      *          constructed, are in a package that is not opened unconditionally,
1606      *          or access to the resource is denied by the security manager,
1607      *          are not returned in the enumeration.
1608      *
1609      * @throws  IOException
1610      *          If I/O errors occur
1611      *
1612      * @since  1.2
1613      * @revised 9
1614      * @spec JPMS
1615      */
1616     protected Enumeration<URL> findResources(String name) throws IOException {
1617         return Collections.emptyEnumeration();
1618     }
1619 
1620     /**
1621      * Registers the caller as
1622      * {@linkplain #isRegisteredAsParallelCapable() parallel capable}.
1623      * The registration succeeds if and only if all of the following
1624      * conditions are met:
1625      * <ol>
1626      * <li> no instance of the caller has been created</li>
1627      * <li> all of the super classes (except class Object) of the caller are
1628      * registered as parallel capable</li>
1629      * </ol>
1630      * <p>Note that once a class loader is registered as parallel capable, there
1631      * is no way to change it back.</p>
1632      *
1633      * @return  {@code true} if the caller is successfully registered as
1634      *          parallel capable and {@code false} if otherwise.
1635      *
1636      * @see #isRegisteredAsParallelCapable()
1637      *
1638      * @since   1.7
1639      */
1640     @CallerSensitive
1641     protected static boolean registerAsParallelCapable() {
1642         Class<? extends ClassLoader> callerClass =
1643             Reflection.getCallerClass().asSubclass(ClassLoader.class);
1644         return ParallelLoaders.register(callerClass);
1645     }
1646 
1647     /**
1648      * Returns {@code true} if this class loader is registered as
1649      * {@linkplain #registerAsParallelCapable parallel capable}, otherwise
1650      * {@code false}.
1651      *
1652      * @return  {@code true} if this class loader is parallel capable,
1653      *          otherwise {@code false}.
1654      *
1655      * @see #registerAsParallelCapable()
1656      *
1657      * @since   9
1658      */
1659     public final boolean isRegisteredAsParallelCapable() {
1660         return ParallelLoaders.isRegistered(this.getClass());
1661     }
1662 
1663     /**
1664      * Find a resource of the specified name from the search path used to load
1665      * classes.  This method locates the resource through the system class
1666      * loader (see {@link #getSystemClassLoader()}).
1667      *
1668      * <p> Resources in named modules are subject to the encapsulation rules
1669      * specified by {@link Module#getResourceAsStream Module.getResourceAsStream}.
1670      * Additionally, and except for the special case where the resource has a
1671      * name ending with "{@code .class}", this method will only find resources in
1672      * packages of named modules when the package is {@link Module#isOpen(String)
1673      * opened} unconditionally. </p>
1674      *
1675      * @param  name
1676      *         The resource name
1677      *
1678      * @return  A {@link java.net.URL URL} to the resource; {@code
1679      *          null} if the resource could not be found, a URL could not be
1680      *          constructed to locate the resource, the resource is in a package
1681      *          that is not opened unconditionally or access to the resource is
1682      *          denied by the security manager.
1683      *
1684      * @since  1.1
1685      * @revised 9
1686      * @spec JPMS
1687      */
1688     public static URL getSystemResource(String name) {
1689         return getSystemClassLoader().getResource(name);
1690     }
1691 
1692     /**
1693      * Finds all resources of the specified name from the search path used to
1694      * load classes.  The resources thus found are returned as an
1695      * {@link java.util.Enumeration Enumeration} of {@link
1696      * java.net.URL URL} objects.
1697      *
1698      * <p> The search order is described in the documentation for {@link
1699      * #getSystemResource(String)}.  </p>
1700      *
1701      * <p> Resources in named modules are subject to the encapsulation rules
1702      * specified by {@link Module#getResourceAsStream Module.getResourceAsStream}.
1703      * Additionally, and except for the special case where the resource has a
1704      * name ending with "{@code .class}", this method will only find resources in
1705      * packages of named modules when the package is {@link Module#isOpen(String)
1706      * opened} unconditionally. </p>
1707      *
1708      * @param  name
1709      *         The resource name
1710      *
1711      * @return  An enumeration of {@link java.net.URL URL} objects for
1712      *          the resource. If no resources could  be found, the enumeration
1713      *          will be empty. Resources for which a {@code URL} cannot be
1714      *          constructed, are in a package that is not opened unconditionally,
1715      *          or access to the resource is denied by the security manager,
1716      *          are not returned in the enumeration.
1717      *
1718      * @throws  IOException
1719      *          If I/O errors occur
1720      *
1721      * @since  1.2
1722      * @revised 9
1723      * @spec JPMS
1724      */
1725     public static Enumeration<URL> getSystemResources(String name)
1726         throws IOException
1727     {
1728         return getSystemClassLoader().getResources(name);
1729     }
1730 
1731     /**
1732      * Returns an input stream for reading the specified resource.
1733      *
1734      * <p> The search order is described in the documentation for {@link
1735      * #getResource(String)}.  </p>
1736      *
1737      * <p> Resources in named modules are subject to the encapsulation rules
1738      * specified by {@link Module#getResourceAsStream Module.getResourceAsStream}.
1739      * Additionally, and except for the special case where the resource has a
1740      * name ending with "{@code .class}", this method will only find resources in
1741      * packages of named modules when the package is {@link Module#isOpen(String)
1742      * opened} unconditionally. </p>
1743      *
1744      * @param  name
1745      *         The resource name
1746      *
1747      * @return  An input stream for reading the resource; {@code null} if the
1748      *          resource could not be found, the resource is in a package that
1749      *          is not opened unconditionally, or access to the resource is
1750      *          denied by the security manager.
1751      *
1752      * @throws  NullPointerException If {@code name} is {@code null}
1753      *
1754      * @since  1.1
1755      * @revised 9
1756      * @spec JPMS
1757      */
1758     public InputStream getResourceAsStream(String name) {
1759         Objects.requireNonNull(name);
1760         URL url = getResource(name);
1761         try {
1762             return url != null ? url.openStream() : null;
1763         } catch (IOException e) {
1764             return null;
1765         }
1766     }
1767 
1768     /**
1769      * Open for reading, a resource of the specified name from the search path
1770      * used to load classes.  This method locates the resource through the
1771      * system class loader (see {@link #getSystemClassLoader()}).
1772      *
1773      * <p> Resources in named modules are subject to the encapsulation rules
1774      * specified by {@link Module#getResourceAsStream Module.getResourceAsStream}.
1775      * Additionally, and except for the special case where the resource has a
1776      * name ending with "{@code .class}", this method will only find resources in
1777      * packages of named modules when the package is {@link Module#isOpen(String)
1778      * opened} unconditionally. </p>
1779      *
1780      * @param  name
1781      *         The resource name
1782      *
1783      * @return  An input stream for reading the resource; {@code null} if the
1784      *          resource could not be found, the resource is in a package that
1785      *          is not opened unconditionally, or access to the resource is
1786      *          denied by the security manager.
1787      *
1788      * @since  1.1
1789      * @revised 9
1790      * @spec JPMS
1791      */
1792     public static InputStream getSystemResourceAsStream(String name) {
1793         URL url = getSystemResource(name);
1794         try {
1795             return url != null ? url.openStream() : null;
1796         } catch (IOException e) {
1797             return null;
1798         }
1799     }
1800 
1801 
1802     // -- Hierarchy --
1803 
1804     /**
1805      * Returns the parent class loader for delegation. Some implementations may
1806      * use {@code null} to represent the bootstrap class loader. This method
1807      * will return {@code null} in such implementations if this class loader's
1808      * parent is the bootstrap class loader.
1809      *
1810      * @return  The parent {@code ClassLoader}
1811      *
1812      * @throws  SecurityException
1813      *          If a security manager is present, and the caller's class loader
1814      *          is not {@code null} and is not an ancestor of this class loader,
1815      *          and the caller does not have the
1816      *          {@link RuntimePermission}{@code ("getClassLoader")}
1817      *
1818      * @since  1.2
1819      */
1820     @CallerSensitive
1821     public final ClassLoader getParent() {
1822         if (parent == null)
1823             return null;
1824         SecurityManager sm = System.getSecurityManager();
1825         if (sm != null) {
1826             // Check access to the parent class loader
1827             // If the caller's class loader is same as this class loader,
1828             // permission check is performed.
1829             checkClassLoaderPermission(parent, Reflection.getCallerClass());
1830         }
1831         return parent;
1832     }
1833 
1834     /**
1835      * Returns the unnamed {@code Module} for this class loader.
1836      *
1837      * @return The unnamed Module for this class loader
1838      *
1839      * @see Module#isNamed()
1840      * @since 9
1841      * @spec JPMS
1842      */
1843     public final Module getUnnamedModule() {
1844         return unnamedModule;
1845     }
1846 
1847     /**
1848      * Returns the platform class loader.  All
1849      * <a href="#builtinLoaders">platform classes</a> are visible to
1850      * the platform class loader.
1851      *
1852      * @implNote The name of the builtin platform class loader is
1853      * {@code "platform"}.
1854      *
1855      * @return  The platform {@code ClassLoader}.
1856      *
1857      * @throws  SecurityException
1858      *          If a security manager is present, and the caller's class loader is
1859      *          not {@code null}, and the caller's class loader is not the same
1860      *          as or an ancestor of the platform class loader,
1861      *          and the caller does not have the
1862      *          {@link RuntimePermission}{@code ("getClassLoader")}
1863      *
1864      * @since 9
1865      * @spec JPMS
1866      */
1867     @CallerSensitive
1868     public static ClassLoader getPlatformClassLoader() {
1869         SecurityManager sm = System.getSecurityManager();
1870         ClassLoader loader = getBuiltinPlatformClassLoader();
1871         if (sm != null) {
1872             checkClassLoaderPermission(loader, Reflection.getCallerClass());
1873         }
1874         return loader;
1875     }
1876 
1877     /**
1878      * Returns the system class loader.  This is the default
1879      * delegation parent for new {@code ClassLoader} instances, and is
1880      * typically the class loader used to start the application.
1881      *
1882      * <p> This method is first invoked early in the runtime's startup
1883      * sequence, at which point it creates the system class loader. This
1884      * class loader will be the context class loader for the main application
1885      * thread (for example, the thread that invokes the {@code main} method of
1886      * the main class).
1887      *
1888      * <p> The default system class loader is an implementation-dependent
1889      * instance of this class.
1890      *
1891      * <p> If the system property "{@systemProperty java.system.class.loader}"
1892      * is defined when this method is first invoked then the value of that
1893      * property is taken to be the name of a class that will be returned as the
1894      * system class loader. The class is loaded using the default system class
1895      * loader and must define a public constructor that takes a single parameter
1896      * of type {@code ClassLoader} which is used as the delegation parent. An
1897      * instance is then created using this constructor with the default system
1898      * class loader as the parameter.  The resulting class loader is defined
1899      * to be the system class loader. During construction, the class loader
1900      * should take great care to avoid calling {@code getSystemClassLoader()}.
1901      * If circular initialization of the system class loader is detected then
1902      * an {@code IllegalStateException} is thrown.
1903      *
1904      * @implNote The system property to override the system class loader is not
1905      * examined until the VM is almost fully initialized. Code that executes
1906      * this method during startup should take care not to cache the return
1907      * value until the system is fully initialized.
1908      *
1909      * <p> The name of the built-in system class loader is {@code "app"}.
1910      * The system property "{@code java.class.path}" is read during early
1911      * initialization of the VM to determine the class path.
1912      * An empty value of "{@code java.class.path}" property is interpreted
1913      * differently depending on whether the initial module (the module
1914      * containing the main class) is named or unnamed:
1915      * If named, the built-in system class loader will have no class path and
1916      * will search for classes and resources using the application module path;
1917      * otherwise, if unnamed, it will set the class path to the current
1918      * working directory.
1919      *
1920      * <p> JAR files on the class path may contain a {@code Class-Path} manifest
1921      * attribute to specify dependent JAR files to be included in the class path.
1922      * {@code Class-Path} entries must meet certain conditions for validity (see
1923      * the <a href="{@docRoot}/../specs/jar/jar.html#class-path-attribute">
1924      * JAR File Specification</a> for details).  Invalid {@code Class-Path}
1925      * entries are ignored.  For debugging purposes, ignored entries can be
1926      * printed to the console if the
1927      * {@systemProperty jdk.net.URLClassPath.showIgnoredClassPathEntries} system
1928      * property is set to {@code true}.
1929      *
1930      * @return  The system {@code ClassLoader}
1931      *
1932      * @throws  SecurityException
1933      *          If a security manager is present, and the caller's class loader
1934      *          is not {@code null} and is not the same as or an ancestor of the
1935      *          system class loader, and the caller does not have the
1936      *          {@link RuntimePermission}{@code ("getClassLoader")}
1937      *
1938      * @throws  IllegalStateException
1939      *          If invoked recursively during the construction of the class
1940      *          loader specified by the "{@code java.system.class.loader}"
1941      *          property.
1942      *
1943      * @throws  Error
1944      *          If the system property "{@code java.system.class.loader}"
1945      *          is defined but the named class could not be loaded, the
1946      *          provider class does not define the required constructor, or an
1947      *          exception is thrown by that constructor when it is invoked. The
1948      *          underlying cause of the error can be retrieved via the
1949      *          {@link Throwable#getCause()} method.
1950      *
1951      * @revised  1.4
1952      * @revised 9
1953      * @spec JPMS
1954      */
1955     @CallerSensitive
1956     public static ClassLoader getSystemClassLoader() {
1957         switch (VM.initLevel()) {
1958             case 0:
1959             case 1:
1960             case 2:
1961                 // the system class loader is the built-in app class loader during startup
1962                 return getBuiltinAppClassLoader();
1963             case 3:
1964                 String msg = "getSystemClassLoader cannot be called during the system class loader instantiation";
1965                 throw new IllegalStateException(msg);
1966             default:
1967                 // system fully initialized
1968                 assert VM.isBooted() && scl != null;
1969                 SecurityManager sm = System.getSecurityManager();
1970                 if (sm != null) {
1971                     checkClassLoaderPermission(scl, Reflection.getCallerClass());
1972                 }
1973                 return scl;
1974         }
1975     }
1976 
1977     static ClassLoader getBuiltinPlatformClassLoader() {
1978         return ClassLoaders.platformClassLoader();
1979     }
1980 
1981     static ClassLoader getBuiltinAppClassLoader() {
1982         return ClassLoaders.appClassLoader();
1983     }
1984 
1985     /*
1986      * Initialize the system class loader that may be a custom class on the
1987      * application class path or application module path.
1988      *
1989      * @see java.lang.System#initPhase3
1990      */
1991     static synchronized ClassLoader initSystemClassLoader() {
1992         if (VM.initLevel() != 3) {
1993             throw new InternalError("system class loader cannot be set at initLevel " +
1994                                     VM.initLevel());
1995         }
1996 
1997         // detect recursive initialization
1998         if (scl != null) {
1999             throw new IllegalStateException("recursive invocation");
2000         }
2001 
2002         ClassLoader builtinLoader = getBuiltinAppClassLoader();
2003 
2004         // All are privileged frames.  No need to call doPrivileged.
2005         String cn = System.getProperty("java.system.class.loader");
2006         if (cn != null) {
2007             try {
2008                 // custom class loader is only supported to be loaded from unnamed module
2009                 Constructor<?> ctor = Class.forName(cn, false, builtinLoader)
2010                                            .getDeclaredConstructor(ClassLoader.class);
2011                 scl = (ClassLoader) ctor.newInstance(builtinLoader);
2012             } catch (Exception e) {
2013                 Throwable cause = e;
2014                 if (e instanceof InvocationTargetException) {
2015                     cause = e.getCause();
2016                     if (cause instanceof Error) {
2017                         throw (Error) cause;
2018                     }
2019                 }
2020                 if (cause instanceof RuntimeException) {
2021                     throw (RuntimeException) cause;
2022                 }
2023                 throw new Error(cause.getMessage(), cause);
2024             }
2025         } else {
2026             scl = builtinLoader;
2027         }
2028         return scl;
2029     }
2030 
2031     /*
2032      * Initialize default paths for native libraries search.
2033      * Must be done early as JDK may load libraries during bootstrap.
2034      *
2035      * @see java.lang.System#initPhase1
2036      */
2037     static void initLibraryPaths() {
2038         usr_paths = initializePath("java.library.path");
2039         sys_paths = initializePath("sun.boot.library.path");
2040     }
2041 
2042     // Returns true if the specified class loader can be found in this class
2043     // loader's delegation chain.
2044     boolean isAncestor(ClassLoader cl) {
2045         ClassLoader acl = this;
2046         do {
2047             acl = acl.parent;
2048             if (cl == acl) {
2049                 return true;
2050             }
2051         } while (acl != null);
2052         return false;
2053     }
2054 
2055     // Tests if class loader access requires "getClassLoader" permission
2056     // check.  A class loader 'from' can access class loader 'to' if
2057     // class loader 'from' is same as class loader 'to' or an ancestor
2058     // of 'to'.  The class loader in a system domain can access
2059     // any class loader.
2060     private static boolean needsClassLoaderPermissionCheck(ClassLoader from,
2061                                                            ClassLoader to)
2062     {
2063         if (from == to)
2064             return false;
2065 
2066         if (from == null)
2067             return false;
2068 
2069         return !to.isAncestor(from);
2070     }
2071 
2072     // Returns the class's class loader, or null if none.
2073     static ClassLoader getClassLoader(Class<?> caller) {
2074         // This can be null if the VM is requesting it
2075         if (caller == null) {
2076             return null;
2077         }
2078         // Circumvent security check since this is package-private
2079         return caller.getClassLoader0();
2080     }
2081 
2082     /*
2083      * Checks RuntimePermission("getClassLoader") permission
2084      * if caller's class loader is not null and caller's class loader
2085      * is not the same as or an ancestor of the given cl argument.
2086      */
2087     static void checkClassLoaderPermission(ClassLoader cl, Class<?> caller) {
2088         SecurityManager sm = System.getSecurityManager();
2089         if (sm != null) {
2090             // caller can be null if the VM is requesting it
2091             ClassLoader ccl = getClassLoader(caller);
2092             if (needsClassLoaderPermissionCheck(ccl, cl)) {
2093                 sm.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION);
2094             }
2095         }
2096     }
2097 
2098     // The system class loader
2099     // @GuardedBy("ClassLoader.class")
2100     private static volatile ClassLoader scl;
2101 
2102     // -- Package --
2103 
2104     /**
2105      * Define a Package of the given Class object.
2106      *
2107      * If the given class represents an array type, a primitive type or void,
2108      * this method returns {@code null}.
2109      *
2110      * This method does not throw IllegalArgumentException.
2111      */
2112     Package definePackage(Class<?> c) {
2113         if (c.isPrimitive() || c.isArray()) {
2114             return null;
2115         }
2116 
2117         return definePackage(c.getPackageName(), c.getModule());
2118     }
2119 
2120     /**
2121      * Defines a Package of the given name and module
2122      *
2123      * This method does not throw IllegalArgumentException.
2124      *
2125      * @param name package name
2126      * @param m    module
2127      */
2128     Package definePackage(String name, Module m) {
2129         if (name.isEmpty() && m.isNamed()) {
2130             throw new InternalError("unnamed package in  " + m);
2131         }
2132 
2133         // check if Package object is already defined
2134         NamedPackage pkg = packages.get(name);
2135         if (pkg instanceof Package)
2136             return (Package)pkg;
2137 
2138         return (Package)packages.compute(name, (n, p) -> toPackage(n, p, m));
2139     }
2140 
2141     /*
2142      * Returns a Package object for the named package
2143      */
2144     private Package toPackage(String name, NamedPackage p, Module m) {
2145         // define Package object if the named package is not yet defined
2146         if (p == null)
2147             return NamedPackage.toPackage(name, m);
2148 
2149         // otherwise, replace the NamedPackage object with Package object
2150         if (p instanceof Package)
2151             return (Package)p;
2152 
2153         return NamedPackage.toPackage(p.packageName(), p.module());
2154     }
2155 
2156     /**
2157      * Defines a package by <a href="#binary-name">name</a> in this {@code ClassLoader}.
2158      * <p>
2159      * <a href="#binary-name">Package names</a> must be unique within a class loader and
2160      * cannot be redefined or changed once created.
2161      * <p>
2162      * If a class loader wishes to define a package with specific properties,
2163      * such as version information, then the class loader should call this
2164      * {@code definePackage} method before calling {@code defineClass}.
2165      * Otherwise, the
2166      * {@link #defineClass(String, byte[], int, int, ProtectionDomain) defineClass}
2167      * method will define a package in this class loader corresponding to the package
2168      * of the newly defined class; the properties of this defined package are
2169      * specified by {@link Package}.
2170      *
2171      * @apiNote
2172      * A class loader that wishes to define a package for classes in a JAR
2173      * typically uses the specification and implementation titles, versions, and
2174      * vendors from the JAR's manifest. If the package is specified as
2175      * {@linkplain java.util.jar.Attributes.Name#SEALED sealed} in the JAR's manifest,
2176      * the {@code URL} of the JAR file is typically used as the {@code sealBase}.
2177      * If classes of package {@code 'p'} defined by this class loader
2178      * are loaded from multiple JARs, the {@code Package} object may contain
2179      * different information depending on the first class of package {@code 'p'}
2180      * defined and which JAR's manifest is read first to explicitly define
2181      * package {@code 'p'}.
2182      *
2183      * <p> It is strongly recommended that a class loader does not call this
2184      * method to explicitly define packages in <em>named modules</em>; instead,
2185      * the package will be automatically defined when a class is {@linkplain
2186      * #defineClass(String, byte[], int, int, ProtectionDomain) being defined}.
2187      * If it is desirable to define {@code Package} explicitly, it should ensure
2188      * that all packages in a named module are defined with the properties
2189      * specified by {@link Package}.  Otherwise, some {@code Package} objects
2190      * in a named module may be for example sealed with different seal base.
2191      *
2192      * @param  name
2193      *         The <a href="#binary-name">package name</a>
2194      *
2195      * @param  specTitle
2196      *         The specification title
2197      *
2198      * @param  specVersion
2199      *         The specification version
2200      *
2201      * @param  specVendor
2202      *         The specification vendor
2203      *
2204      * @param  implTitle
2205      *         The implementation title
2206      *
2207      * @param  implVersion
2208      *         The implementation version
2209      *
2210      * @param  implVendor
2211      *         The implementation vendor
2212      *
2213      * @param  sealBase
2214      *         If not {@code null}, then this package is sealed with
2215      *         respect to the given code source {@link java.net.URL URL}
2216      *         object.  Otherwise, the package is not sealed.
2217      *
2218      * @return  The newly defined {@code Package} object
2219      *
2220      * @throws  NullPointerException
2221      *          if {@code name} is {@code null}.
2222      *
2223      * @throws  IllegalArgumentException
2224      *          if a package of the given {@code name} is already
2225      *          defined by this class loader
2226      *
2227      *
2228      * @since  1.2
2229      * @revised 9
2230      * @spec JPMS
2231      *
2232      * @jvms 5.3 Creation and Loading
2233      * @see <a href="{@docRoot}/../specs/jar/jar.html#package-sealing">
2234      *      The JAR File Specification: Package Sealing</a>
2235      */
2236     protected Package definePackage(String name, String specTitle,
2237                                     String specVersion, String specVendor,
2238                                     String implTitle, String implVersion,
2239                                     String implVendor, URL sealBase)
2240     {
2241         Objects.requireNonNull(name);
2242 
2243         // definePackage is not final and may be overridden by custom class loader
2244         Package p = new Package(name, specTitle, specVersion, specVendor,
2245                                 implTitle, implVersion, implVendor,
2246                                 sealBase, this);
2247 
2248         if (packages.putIfAbsent(name, p) != null)
2249             throw new IllegalArgumentException(name);
2250 
2251         return p;
2252     }
2253 
2254     /**
2255      * Returns a {@code Package} of the given <a href="#binary-name">name</a> that
2256      * has been defined by this class loader.
2257      *
2258      * @param  name The <a href="#binary-name">package name</a>
2259      *
2260      * @return The {@code Package} of the given name that has been defined
2261      *         by this class loader, or {@code null} if not found
2262      *
2263      * @throws  NullPointerException
2264      *          if {@code name} is {@code null}.
2265      *
2266      * @jvms 5.3 Creation and Loading
2267      *
2268      * @since  9
2269      * @spec JPMS
2270      */
2271     public final Package getDefinedPackage(String name) {
2272         Objects.requireNonNull(name, "name cannot be null");
2273 
2274         NamedPackage p = packages.get(name);
2275         if (p == null)
2276             return null;
2277 
2278         return definePackage(name, p.module());
2279     }
2280 
2281     /**
2282      * Returns all of the {@code Package}s that have been defined by
2283      * this class loader.  The returned array has no duplicated {@code Package}s
2284      * of the same name.
2285      *
2286      * @apiNote This method returns an array rather than a {@code Set} or {@code Stream}
2287      *          for consistency with the existing {@link #getPackages} method.
2288      *
2289      * @return The array of {@code Package} objects that have been defined by
2290      *         this class loader; or an zero length array if no package has been
2291      *         defined by this class loader.
2292      *
2293      * @jvms 5.3 Creation and Loading
2294      *
2295      * @since  9
2296      * @spec JPMS
2297      */
2298     public final Package[] getDefinedPackages() {
2299         return packages().toArray(Package[]::new);
2300     }
2301 
2302     /**
2303      * Finds a package by <a href="#binary-name">name</a> in this class loader and its ancestors.
2304      * <p>
2305      * If this class loader defines a {@code Package} of the given name,
2306      * the {@code Package} is returned. Otherwise, the ancestors of
2307      * this class loader are searched recursively (parent by parent)
2308      * for a {@code Package} of the given name.
2309      *
2310      * @apiNote The {@link #getPlatformClassLoader() platform class loader}
2311      * may delegate to the application class loader but the application class
2312      * loader is not its ancestor.  When invoked on the platform class loader,
2313      * this method  will not find packages defined to the application
2314      * class loader.
2315      *
2316      * @param  name
2317      *         The <a href="#binary-name">package name</a>
2318      *
2319      * @return The {@code Package} of the given name that has been defined by
2320      *         this class loader or its ancestors, or {@code null} if not found.
2321      *
2322      * @throws  NullPointerException
2323      *          if {@code name} is {@code null}.
2324      *
2325      * @deprecated
2326      * If multiple class loaders delegate to each other and define classes
2327      * with the same package name, and one such loader relies on the lookup
2328      * behavior of {@code getPackage} to return a {@code Package} from
2329      * a parent loader, then the properties exposed by the {@code Package}
2330      * may not be as expected in the rest of the program.
2331      * For example, the {@code Package} will only expose annotations from the
2332      * {@code package-info.class} file defined by the parent loader, even if
2333      * annotations exist in a {@code package-info.class} file defined by
2334      * a child loader.  A more robust approach is to use the
2335      * {@link ClassLoader#getDefinedPackage} method which returns
2336      * a {@code Package} for the specified class loader.
2337      *
2338      * @see ClassLoader#getDefinedPackage(String)
2339      *
2340      * @since  1.2
2341      * @revised 9
2342      * @spec JPMS
2343      */
2344     @Deprecated(since="9")
2345     protected Package getPackage(String name) {
2346         Package pkg = getDefinedPackage(name);
2347         if (pkg == null) {
2348             if (parent != null) {
2349                 pkg = parent.getPackage(name);
2350             } else {
2351                 pkg = BootLoader.getDefinedPackage(name);
2352             }
2353         }
2354         return pkg;
2355     }
2356 
2357     /**
2358      * Returns all of the {@code Package}s that have been defined by
2359      * this class loader and its ancestors.  The returned array may contain
2360      * more than one {@code Package} object of the same package name, each
2361      * defined by a different class loader in the class loader hierarchy.
2362      *
2363      * @apiNote The {@link #getPlatformClassLoader() platform class loader}
2364      * may delegate to the application class loader. In other words,
2365      * packages in modules defined to the application class loader may be
2366      * visible to the platform class loader.  On the other hand,
2367      * the application class loader is not its ancestor and hence
2368      * when invoked on the platform class loader, this method will not
2369      * return any packages defined to the application class loader.
2370      *
2371      * @return  The array of {@code Package} objects that have been defined by
2372      *          this class loader and its ancestors
2373      *
2374      * @see ClassLoader#getDefinedPackages()
2375      *
2376      * @since  1.2
2377      * @revised 9
2378      * @spec JPMS
2379      */
2380     protected Package[] getPackages() {
2381         Stream<Package> pkgs = packages();
2382         ClassLoader ld = parent;
2383         while (ld != null) {
2384             pkgs = Stream.concat(ld.packages(), pkgs);
2385             ld = ld.parent;
2386         }
2387         return Stream.concat(BootLoader.packages(), pkgs)
2388                      .toArray(Package[]::new);
2389     }
2390 
2391 
2392 
2393     // package-private
2394 
2395     /**
2396      * Returns a stream of Packages defined in this class loader
2397      */
2398     Stream<Package> packages() {
2399         return packages.values().stream()
2400                        .map(p -> definePackage(p.packageName(), p.module()));
2401     }
2402 
2403     // -- Native library access --
2404 
2405     /**
2406      * Returns the absolute path name of a native library.  The VM invokes this
2407      * method to locate the native libraries that belong to classes loaded with
2408      * this class loader. If this method returns {@code null}, the VM
2409      * searches the library along the path specified as the
2410      * "{@code java.library.path}" property.
2411      *
2412      * @param  libname
2413      *         The library name
2414      *
2415      * @return  The absolute path of the native library
2416      *
2417      * @see  System#loadLibrary(String)
2418      * @see  System#mapLibraryName(String)
2419      *
2420      * @since  1.2
2421      */
2422     protected String findLibrary(String libname) {
2423         return null;
2424     }
2425 
2426     /**
2427      * The inner class NativeLibrary denotes a loaded native library instance.
2428      * Every classloader contains a vector of loaded native libraries in the
2429      * private field {@code nativeLibraries}.  The native libraries loaded
2430      * into the system are entered into the {@code systemNativeLibraries}
2431      * vector.
2432      *
2433      * <p> Every native library requires a particular version of JNI. This is
2434      * denoted by the private {@code jniVersion} field.  This field is set by
2435      * the VM when it loads the library, and used by the VM to pass the correct
2436      * version of JNI to the native methods.  </p>
2437      *
2438      * @see      ClassLoader
2439      * @since    1.2
2440      */
2441     static class NativeLibrary {
2442         // the class from which the library is loaded, also indicates
2443         // the loader this native library belongs.
2444         final Class<?> fromClass;
2445         // the canonicalized name of the native library.
2446         // or static library name
2447         final String name;
2448         // Indicates if the native library is linked into the VM
2449         final boolean isBuiltin;
2450 
2451         // opaque handle to native library, used in native code.
2452         long handle;
2453         // the version of JNI environment the native library requires.
2454         int jniVersion;
2455 
2456         native boolean load0(String name, boolean isBuiltin);
2457 
2458         native long findEntry(String name);
2459 
2460         NativeLibrary(Class<?> fromClass, String name, boolean isBuiltin) {
2461             this.name = name;
2462             this.fromClass = fromClass;
2463             this.isBuiltin = isBuiltin;
2464         }
2465 
2466         /*
2467          * Loads the native library and registers for cleanup when its
2468          * associated class loader is unloaded
2469          */
2470         boolean load() {
2471             if (handle != 0) {
2472                 throw new InternalError("Native library " + name + " has been loaded");
2473             }
2474 
2475             if (!load0(name, isBuiltin)) return false;
2476 
2477             // register the class loader for cleanup when unloaded
2478             // builtin class loaders are never unloaded
2479             ClassLoader loader = fromClass.getClassLoader();
2480             if (loader != null &&
2481                 loader != getBuiltinPlatformClassLoader() &&
2482                 loader != getBuiltinAppClassLoader()) {
2483                 CleanerFactory.cleaner().register(loader,
2484                         new Unloader(name, handle, isBuiltin));
2485             }
2486             return true;
2487         }
2488 
2489         static boolean loadLibrary(Class<?> fromClass, String name, boolean isBuiltin) {
2490             ClassLoader loader =
2491                 fromClass == null ? null : fromClass.getClassLoader();
2492 
2493             synchronized (loadedLibraryNames) {
2494                 Map<String, NativeLibrary> libs =
2495                     loader != null ? loader.nativeLibraries() : systemNativeLibraries();
2496                 if (libs.containsKey(name)) {
2497                     return true;
2498                 }
2499 
2500                 if (loadedLibraryNames.contains(name)) {
2501                     throw new UnsatisfiedLinkError("Native Library " + name +
2502                         " already loaded in another classloader");
2503                 }
2504 
2505                 /*
2506                  * When a library is being loaded, JNI_OnLoad function can cause
2507                  * another loadLibrary invocation that should succeed.
2508                  *
2509                  * We use a static stack to hold the list of libraries we are
2510                  * loading because this can happen only when called by the
2511                  * same thread because this block is synchronous.
2512                  *
2513                  * If there is a pending load operation for the library, we
2514                  * immediately return success; otherwise, we raise
2515                  * UnsatisfiedLinkError.
2516                  */
2517                 for (NativeLibrary lib : nativeLibraryContext) {
2518                     if (name.equals(lib.name)) {
2519                         if (loader == lib.fromClass.getClassLoader()) {
2520                             return true;
2521                         } else {
2522                             throw new UnsatisfiedLinkError("Native Library " +
2523                                 name + " is being loaded in another classloader");
2524                         }
2525                     }
2526                 }
2527                 NativeLibrary lib = new NativeLibrary(fromClass, name, isBuiltin);
2528                 // load the native library
2529                 nativeLibraryContext.push(lib);
2530                 try {
2531                     if (!lib.load()) return false;
2532                 } finally {
2533                     nativeLibraryContext.pop();
2534                 }
2535                 // register the loaded native library
2536                 loadedLibraryNames.add(name);
2537                 libs.put(name, lib);
2538             }
2539             return true;
2540         }
2541 
2542         // Invoked in the VM to determine the context class in JNI_OnLoad
2543         // and JNI_OnUnload
2544         static Class<?> getFromClass() {
2545             return nativeLibraryContext.peek().fromClass;
2546         }
2547 
2548         // native libraries being loaded
2549         static Deque<NativeLibrary> nativeLibraryContext = new ArrayDeque<>(8);
2550 
2551         /*
2552          * The run() method will be invoked when this class loader becomes
2553          * phantom reachable to unload the native library.
2554          */
2555         static class Unloader implements Runnable {
2556             // This represents the context when a native library is unloaded
2557             // and getFromClass() will return null,
2558             static final NativeLibrary UNLOADER =
2559                 new NativeLibrary(null, "dummy", false);
2560             final String name;
2561             final long handle;
2562             final boolean isBuiltin;
2563 
2564             Unloader(String name, long handle, boolean isBuiltin) {
2565                 if (handle == 0) {
2566                     throw new IllegalArgumentException(
2567                         "Invalid handle for native library " + name);
2568                 }
2569 
2570                 this.name = name;
2571                 this.handle = handle;
2572                 this.isBuiltin = isBuiltin;
2573             }
2574 
2575             @Override
2576             public void run() {
2577                 synchronized (loadedLibraryNames) {
2578                     /* remove the native library name */
2579                     loadedLibraryNames.remove(name);
2580                     nativeLibraryContext.push(UNLOADER);
2581                     try {
2582                         unload(name, isBuiltin, handle);
2583                     } finally {
2584                         nativeLibraryContext.pop();
2585                     }
2586 
2587                 }
2588             }
2589         }
2590 
2591         // JNI FindClass expects the caller class if invoked from JNI_OnLoad
2592         // and JNI_OnUnload is NativeLibrary class
2593         static native void unload(String name, boolean isBuiltin, long handle);
2594     }
2595 
2596     // The paths searched for libraries
2597     private static String usr_paths[];
2598     private static String sys_paths[];
2599 
2600     private static String[] initializePath(String propName) {
2601         String ldPath = System.getProperty(propName, "");
2602         int ldLen = ldPath.length();
2603         char ps = File.pathSeparatorChar;
2604         int psCount = 0;
2605 
2606         if (ClassLoaderHelper.allowsQuotedPathElements &&
2607             ldPath.indexOf('\"') >= 0) {
2608             // First, remove quotes put around quoted parts of paths.
2609             // Second, use a quotation mark as a new path separator.
2610             // This will preserve any quoted old path separators.
2611             char[] buf = new char[ldLen];
2612             int bufLen = 0;
2613             for (int i = 0; i < ldLen; ++i) {
2614                 char ch = ldPath.charAt(i);
2615                 if (ch == '\"') {
2616                     while (++i < ldLen &&
2617                         (ch = ldPath.charAt(i)) != '\"') {
2618                         buf[bufLen++] = ch;
2619                     }
2620                 } else {
2621                     if (ch == ps) {
2622                         psCount++;
2623                         ch = '\"';
2624                     }
2625                     buf[bufLen++] = ch;
2626                 }
2627             }
2628             ldPath = new String(buf, 0, bufLen);
2629             ldLen = bufLen;
2630             ps = '\"';
2631         } else {
2632             for (int i = ldPath.indexOf(ps); i >= 0;
2633                  i = ldPath.indexOf(ps, i + 1)) {
2634                 psCount++;
2635             }
2636         }
2637 
2638         String[] paths = new String[psCount + 1];
2639         int pathStart = 0;
2640         for (int j = 0; j < psCount; ++j) {
2641             int pathEnd = ldPath.indexOf(ps, pathStart);
2642             paths[j] = (pathStart < pathEnd) ?
2643                 ldPath.substring(pathStart, pathEnd) : ".";
2644             pathStart = pathEnd + 1;
2645         }
2646         paths[psCount] = (pathStart < ldLen) ?
2647             ldPath.substring(pathStart, ldLen) : ".";
2648         return paths;
2649     }
2650 
2651     // Invoked in the java.lang.Runtime class to implement load and loadLibrary.
2652     static void loadLibrary(Class<?> fromClass, String name,
2653                             boolean isAbsolute) {
2654         ClassLoader loader =
2655             (fromClass == null) ? null : fromClass.getClassLoader();
2656         assert sys_paths != null : "should be initialized at this point";
2657         assert usr_paths != null : "should be initialized at this point";
2658 
2659         if (isAbsolute) {
2660             if (loadLibrary0(fromClass, new File(name))) {
2661                 return;
2662             }
2663             throw new UnsatisfiedLinkError("Can't load library: " + name);
2664         }
2665         if (loader != null) {
2666             String libfilename = loader.findLibrary(name);
2667             if (libfilename != null) {
2668                 File libfile = new File(libfilename);
2669                 if (!libfile.isAbsolute()) {
2670                     throw new UnsatisfiedLinkError(
2671                         "ClassLoader.findLibrary failed to return an absolute path: " + libfilename);
2672                 }
2673                 if (loadLibrary0(fromClass, libfile)) {
2674                     return;
2675                 }
2676                 throw new UnsatisfiedLinkError("Can't load " + libfilename);
2677             }
2678         }
2679         for (String sys_path : sys_paths) {
2680             File libfile = new File(sys_path, System.mapLibraryName(name));
2681             if (loadLibrary0(fromClass, libfile)) {
2682                 return;
2683             }
2684             libfile = ClassLoaderHelper.mapAlternativeName(libfile);
2685             if (libfile != null && loadLibrary0(fromClass, libfile)) {
2686                 return;
2687             }
2688         }
2689         if (loader != null) {
2690             for (String usr_path : usr_paths) {
2691                 File libfile = new File(usr_path, System.mapLibraryName(name));
2692                 if (loadLibrary0(fromClass, libfile)) {
2693                     return;
2694                 }
2695                 libfile = ClassLoaderHelper.mapAlternativeName(libfile);
2696                 if (libfile != null && loadLibrary0(fromClass, libfile)) {
2697                     return;
2698                 }
2699             }
2700         }
2701         // Oops, it failed
2702         throw new UnsatisfiedLinkError("no " + name +
2703             " in java.library.path: " + Arrays.toString(usr_paths));
2704     }
2705 
2706     private static native String findBuiltinLib(String name);
2707 
2708     private static boolean loadLibrary0(Class<?> fromClass, final File file) {
2709         // Check to see if we're attempting to access a static library
2710         String name = findBuiltinLib(file.getName());
2711         boolean isBuiltin = (name != null);
2712         if (!isBuiltin) {
2713             name = AccessController.doPrivileged(
2714                 new PrivilegedAction<>() {
2715                     public String run() {
2716                         try {
2717                             return file.exists() ? file.getCanonicalPath() : null;
2718                         } catch (IOException e) {
2719                             return null;
2720                         }
2721                     }
2722                 });
2723             if (name == null) {
2724                 return false;
2725             }
2726         }
2727         return NativeLibrary.loadLibrary(fromClass, name, isBuiltin);
2728     }
2729 
2730     /*
2731      * Invoked in the VM class linking code.
2732      */
2733     private static long findNative(ClassLoader loader, String entryName) {
2734         Map<String, NativeLibrary> libs =
2735             loader != null ? loader.nativeLibraries() : systemNativeLibraries();
2736         if (libs.isEmpty())
2737             return 0;
2738 
2739         // the native libraries map may be updated in another thread
2740         // when a native library is being loaded.  No symbol will be
2741         // searched from it yet.
2742         for (NativeLibrary lib : libs.values()) {
2743             long entry = lib.findEntry(entryName);
2744             if (entry != 0) return entry;
2745         }
2746         return 0;
2747     }
2748 
2749     // All native library names we've loaded.
2750     // This also serves as the lock to obtain nativeLibraries
2751     // and write to nativeLibraryContext.
2752     private static final Set<String> loadedLibraryNames = new HashSet<>();
2753 
2754     // Native libraries belonging to system classes.
2755     private static volatile Map<String, NativeLibrary> systemNativeLibraries;
2756 
2757     // Native libraries associated with the class loader.
2758     private volatile Map<String, NativeLibrary> nativeLibraries;
2759 
2760     /*
2761      * Returns the native libraries map associated with bootstrap class loader
2762      * This method will create the map at the first time when called.
2763      */
2764     private static Map<String, NativeLibrary> systemNativeLibraries() {
2765         Map<String, NativeLibrary> libs = systemNativeLibraries;
2766         if (libs == null) {
2767             synchronized (loadedLibraryNames) {
2768                 libs = systemNativeLibraries;
2769                 if (libs == null) {
2770                     libs = systemNativeLibraries = new ConcurrentHashMap<>();
2771                 }
2772             }
2773         }
2774         return libs;
2775     }
2776 
2777     /*
2778      * Returns the native libraries map associated with this class loader
2779      * This method will create the map at the first time when called.
2780      */
2781     private Map<String, NativeLibrary> nativeLibraries() {
2782         Map<String, NativeLibrary> libs = nativeLibraries;
2783         if (libs == null) {
2784             synchronized (loadedLibraryNames) {
2785                 libs = nativeLibraries;
2786                 if (libs == null) {
2787                     libs = nativeLibraries = new ConcurrentHashMap<>();
2788                 }
2789             }
2790         }
2791         return libs;
2792     }
2793 
2794     // -- Assertion management --
2795 
2796     final Object assertionLock;
2797 
2798     // The default toggle for assertion checking.
2799     // @GuardedBy("assertionLock")
2800     private boolean defaultAssertionStatus = false;
2801 
2802     // Maps String packageName to Boolean package default assertion status Note
2803     // that the default package is placed under a null map key.  If this field
2804     // is null then we are delegating assertion status queries to the VM, i.e.,
2805     // none of this ClassLoader's assertion status modification methods have
2806     // been invoked.
2807     // @GuardedBy("assertionLock")
2808     private Map<String, Boolean> packageAssertionStatus = null;
2809 
2810     // Maps String fullyQualifiedClassName to Boolean assertionStatus If this
2811     // field is null then we are delegating assertion status queries to the VM,
2812     // i.e., none of this ClassLoader's assertion status modification methods
2813     // have been invoked.
2814     // @GuardedBy("assertionLock")
2815     Map<String, Boolean> classAssertionStatus = null;
2816 
2817     /**
2818      * Sets the default assertion status for this class loader.  This setting
2819      * determines whether classes loaded by this class loader and initialized
2820      * in the future will have assertions enabled or disabled by default.
2821      * This setting may be overridden on a per-package or per-class basis by
2822      * invoking {@link #setPackageAssertionStatus(String, boolean)} or {@link
2823      * #setClassAssertionStatus(String, boolean)}.
2824      *
2825      * @param  enabled
2826      *         {@code true} if classes loaded by this class loader will
2827      *         henceforth have assertions enabled by default, {@code false}
2828      *         if they will have assertions disabled by default.
2829      *
2830      * @since  1.4
2831      */
2832     public void setDefaultAssertionStatus(boolean enabled) {
2833         synchronized (assertionLock) {
2834             if (classAssertionStatus == null)
2835                 initializeJavaAssertionMaps();
2836 
2837             defaultAssertionStatus = enabled;
2838         }
2839     }
2840 
2841     /**
2842      * Sets the package default assertion status for the named package.  The
2843      * package default assertion status determines the assertion status for
2844      * classes initialized in the future that belong to the named package or
2845      * any of its "subpackages".
2846      *
2847      * <p> A subpackage of a package named p is any package whose name begins
2848      * with "{@code p.}".  For example, {@code javax.swing.text} is a
2849      * subpackage of {@code javax.swing}, and both {@code java.util} and
2850      * {@code java.lang.reflect} are subpackages of {@code java}.
2851      *
2852      * <p> In the event that multiple package defaults apply to a given class,
2853      * the package default pertaining to the most specific package takes
2854      * precedence over the others.  For example, if {@code javax.lang} and
2855      * {@code javax.lang.reflect} both have package defaults associated with
2856      * them, the latter package default applies to classes in
2857      * {@code javax.lang.reflect}.
2858      *
2859      * <p> Package defaults take precedence over the class loader's default
2860      * assertion status, and may be overridden on a per-class basis by invoking
2861      * {@link #setClassAssertionStatus(String, boolean)}.  </p>
2862      *
2863      * @param  packageName
2864      *         The name of the package whose package default assertion status
2865      *         is to be set. A {@code null} value indicates the unnamed
2866      *         package that is "current"
2867      *         (see section 7.4.2 of
2868      *         <cite>The Java&trade; Language Specification</cite>.)
2869      *
2870      * @param  enabled
2871      *         {@code true} if classes loaded by this classloader and
2872      *         belonging to the named package or any of its subpackages will
2873      *         have assertions enabled by default, {@code false} if they will
2874      *         have assertions disabled by default.
2875      *
2876      * @since  1.4
2877      */
2878     public void setPackageAssertionStatus(String packageName,
2879                                           boolean enabled) {
2880         synchronized (assertionLock) {
2881             if (packageAssertionStatus == null)
2882                 initializeJavaAssertionMaps();
2883 
2884             packageAssertionStatus.put(packageName, enabled);
2885         }
2886     }
2887 
2888     /**
2889      * Sets the desired assertion status for the named top-level class in this
2890      * class loader and any nested classes contained therein.  This setting
2891      * takes precedence over the class loader's default assertion status, and
2892      * over any applicable per-package default.  This method has no effect if
2893      * the named class has already been initialized.  (Once a class is
2894      * initialized, its assertion status cannot change.)
2895      *
2896      * <p> If the named class is not a top-level class, this invocation will
2897      * have no effect on the actual assertion status of any class. </p>
2898      *
2899      * @param  className
2900      *         The fully qualified class name of the top-level class whose
2901      *         assertion status is to be set.
2902      *
2903      * @param  enabled
2904      *         {@code true} if the named class is to have assertions
2905      *         enabled when (and if) it is initialized, {@code false} if the
2906      *         class is to have assertions disabled.
2907      *
2908      * @since  1.4
2909      */
2910     public void setClassAssertionStatus(String className, boolean enabled) {
2911         synchronized (assertionLock) {
2912             if (classAssertionStatus == null)
2913                 initializeJavaAssertionMaps();
2914 
2915             classAssertionStatus.put(className, enabled);
2916         }
2917     }
2918 
2919     /**
2920      * Sets the default assertion status for this class loader to
2921      * {@code false} and discards any package defaults or class assertion
2922      * status settings associated with the class loader.  This method is
2923      * provided so that class loaders can be made to ignore any command line or
2924      * persistent assertion status settings and "start with a clean slate."
2925      *
2926      * @since  1.4
2927      */
2928     public void clearAssertionStatus() {
2929         /*
2930          * Whether or not "Java assertion maps" are initialized, set
2931          * them to empty maps, effectively ignoring any present settings.
2932          */
2933         synchronized (assertionLock) {
2934             classAssertionStatus = new HashMap<>();
2935             packageAssertionStatus = new HashMap<>();
2936             defaultAssertionStatus = false;
2937         }
2938     }
2939 
2940     /**
2941      * Returns the assertion status that would be assigned to the specified
2942      * class if it were to be initialized at the time this method is invoked.
2943      * If the named class has had its assertion status set, the most recent
2944      * setting will be returned; otherwise, if any package default assertion
2945      * status pertains to this class, the most recent setting for the most
2946      * specific pertinent package default assertion status is returned;
2947      * otherwise, this class loader's default assertion status is returned.
2948      * </p>
2949      *
2950      * @param  className
2951      *         The fully qualified class name of the class whose desired
2952      *         assertion status is being queried.
2953      *
2954      * @return  The desired assertion status of the specified class.
2955      *
2956      * @see  #setClassAssertionStatus(String, boolean)
2957      * @see  #setPackageAssertionStatus(String, boolean)
2958      * @see  #setDefaultAssertionStatus(boolean)
2959      *
2960      * @since  1.4
2961      */
2962     boolean desiredAssertionStatus(String className) {
2963         synchronized (assertionLock) {
2964             // assert classAssertionStatus   != null;
2965             // assert packageAssertionStatus != null;
2966 
2967             // Check for a class entry
2968             Boolean result = classAssertionStatus.get(className);
2969             if (result != null)
2970                 return result.booleanValue();
2971 
2972             // Check for most specific package entry
2973             int dotIndex = className.lastIndexOf('.');
2974             if (dotIndex < 0) { // default package
2975                 result = packageAssertionStatus.get(null);
2976                 if (result != null)
2977                     return result.booleanValue();
2978             }
2979             while(dotIndex > 0) {
2980                 className = className.substring(0, dotIndex);
2981                 result = packageAssertionStatus.get(className);
2982                 if (result != null)
2983                     return result.booleanValue();
2984                 dotIndex = className.lastIndexOf('.', dotIndex-1);
2985             }
2986 
2987             // Return the classloader default
2988             return defaultAssertionStatus;
2989         }
2990     }
2991 
2992     // Set up the assertions with information provided by the VM.
2993     // Note: Should only be called inside a synchronized block
2994     private void initializeJavaAssertionMaps() {
2995         // assert Thread.holdsLock(assertionLock);
2996 
2997         classAssertionStatus = new HashMap<>();
2998         packageAssertionStatus = new HashMap<>();
2999         AssertionStatusDirectives directives = retrieveDirectives();
3000 
3001         for(int i = 0; i < directives.classes.length; i++)
3002             classAssertionStatus.put(directives.classes[i],
3003                                      directives.classEnabled[i]);
3004 
3005         for(int i = 0; i < directives.packages.length; i++)
3006             packageAssertionStatus.put(directives.packages[i],
3007                                        directives.packageEnabled[i]);
3008 
3009         defaultAssertionStatus = directives.deflt;
3010     }
3011 
3012     // Retrieves the assertion directives from the VM.
3013     private static native AssertionStatusDirectives retrieveDirectives();
3014 
3015 
3016     // -- Misc --
3017 
3018     /**
3019      * Returns the ConcurrentHashMap used as a storage for ClassLoaderValue(s)
3020      * associated with this ClassLoader, creating it if it doesn't already exist.
3021      */
3022     ConcurrentHashMap<?, ?> createOrGetClassLoaderValueMap() {
3023         ConcurrentHashMap<?, ?> map = classLoaderValueMap;
3024         if (map == null) {
3025             map = new ConcurrentHashMap<>();
3026             boolean set = trySetObjectField("classLoaderValueMap", map);
3027             if (!set) {
3028                 // beaten by someone else
3029                 map = classLoaderValueMap;
3030             }
3031         }
3032         return map;
3033     }
3034 
3035     // the storage for ClassLoaderValue(s) associated with this ClassLoader
3036     private volatile ConcurrentHashMap<?, ?> classLoaderValueMap;
3037 
3038     /**
3039      * Attempts to atomically set a volatile field in this object. Returns
3040      * {@code true} if not beaten by another thread. Avoids the use of
3041      * AtomicReferenceFieldUpdater in this class.
3042      */
3043     private boolean trySetObjectField(String name, Object obj) {
3044         Unsafe unsafe = Unsafe.getUnsafe();
3045         Class<?> k = ClassLoader.class;
3046         long offset;
3047         offset = unsafe.objectFieldOffset(k, name);
3048         return unsafe.compareAndSetReference(this, offset, null, obj);
3049     }
3050 }
3051 
3052 /*
3053  * A utility class that will enumerate over an array of enumerations.
3054  */
3055 final class CompoundEnumeration<E> implements Enumeration<E> {
3056     private final Enumeration<E>[] enums;
3057     private int index;
3058 
3059     public CompoundEnumeration(Enumeration<E>[] enums) {
3060         this.enums = enums;
3061     }
3062 
3063     private boolean next() {
3064         while (index < enums.length) {
3065             if (enums[index] != null && enums[index].hasMoreElements()) {
3066                 return true;
3067             }
3068             index++;
3069         }
3070         return false;
3071     }
3072 
3073     public boolean hasMoreElements() {
3074         return next();
3075     }
3076 
3077     public E nextElement() {
3078         if (!next()) {
3079             throw new NoSuchElementException();
3080         }
3081         return enums[index].nextElement();
3082     }
3083 }