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