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