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