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