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.lang.reflect.InvocationTargetException;
  34 import java.net.URL;
  35 import java.security.AccessController;
  36 import java.security.AccessControlContext;
  37 import java.security.CodeSource;
  38 import java.security.PrivilegedAction;
  39 import java.security.ProtectionDomain;
  40 import java.security.cert.Certificate;
  41 import java.util.ArrayDeque;
  42 import java.util.Arrays;
  43 import java.util.Collections;
  44 import java.util.Deque;
  45 import java.util.Enumeration;
  46 import java.util.HashMap;
  47 import java.util.HashSet;
  48 import java.util.Hashtable;
  49 import java.util.Map;
  50 import java.util.NoSuchElementException;
  51 import java.util.Objects;
  52 import java.util.Set;
  53 import java.util.Spliterator;
  54 import java.util.Spliterators;
  55 import java.util.Vector;
  56 import java.util.WeakHashMap;
  57 import java.util.concurrent.ConcurrentHashMap;
  58 import java.util.function.Supplier;
  59 import java.util.stream.Stream;
  60 import java.util.stream.StreamSupport;
  61 
  62 import jdk.internal.perf.PerfCounter;
  63 import jdk.internal.loader.BootLoader;
  64 import jdk.internal.loader.ClassLoaders;
  65 import jdk.internal.misc.Unsafe;
  66 import jdk.internal.misc.VM;
  67 import jdk.internal.ref.CleanerFactory;
  68 import jdk.internal.reflect.CallerSensitive;
  69 import jdk.internal.reflect.Reflection;
  70 import sun.reflect.misc.ReflectUtil;
  71 import sun.security.util.SecurityConstants;
  72 
  73 /**
  74  * A class loader is an object that is responsible for loading classes. The
  75  * class {@code ClassLoader} is an abstract class.  Given the <a
  76  * href="#name">binary name</a> of a class, a class loader should attempt to
  77  * locate or generate data that constitutes a definition for the class.  A
  78  * typical strategy is to transform the name into a file name and then read a
  79  * "class file" of that name from a file system.
  80  *
  81  * <p> Every {@link java.lang.Class Class} object contains a {@link
  82  * Class#getClassLoader() reference} to the {@code ClassLoader} that defined
  83  * it.
  84  *
  85  * <p> {@code Class} objects for array classes are not created by class
  86  * loaders, but are created automatically as required by the Java runtime.
  87  * The class loader for an array class, as returned by {@link
  88  * Class#getClassLoader()} is the same as the class loader for its element
  89  * type; if the element type is a primitive type, then the array class has no
  90  * class loader.
  91  *
  92  * <p> Applications implement subclasses of {@code ClassLoader} in order to
  93  * extend the manner in which the Java virtual machine dynamically loads
  94  * classes.
  95  *
  96  * <p> Class loaders may typically be used by security managers to indicate
  97  * security domains.
  98  *
  99  * <p> In addition to loading classes, a class loader is also responsible for
 100  * locating resources. A resource is some data (a "{@code .class}" file,
 101  * configuration data, or an image for example) that is identified with an
 102  * abstract '/'-separated path name. Resources are typically packaged with an
 103  * application or library so that they can be located by code in the
 104  * application or library. In some cases, the resources are included so that
 105  * they can be located by other libraries.
 106  *
 107  * <p> The {@code ClassLoader} class uses a delegation model to search for
 108  * classes and resources.  Each instance of {@code ClassLoader} has an
 109  * associated parent class loader. When requested to find a class or
 110  * resource, a {@code ClassLoader} instance will usually delegate the search
 111  * for the class or resource to its parent class loader before attempting to
 112  * find the class or resource itself.
 113  *
 114  * <p> Class loaders that support concurrent loading of classes are known as
 115  * <em>{@linkplain #isRegisteredAsParallelCapable() parallel capable}</em> class
 116  * loaders and are required to register themselves at their class initialization
 117  * time by invoking the {@link
 118  * #registerAsParallelCapable ClassLoader.registerAsParallelCapable}
 119  * method. Note that the {@code ClassLoader} class is registered as parallel
 120  * capable by default. However, its subclasses still need to register themselves
 121  * if they are parallel capable.
 122  * In environments in which the delegation model is not strictly
 123  * hierarchical, class loaders need to be parallel capable, otherwise class
 124  * loading can lead to deadlocks because the loader lock is held for the
 125  * duration of the class loading process (see {@link #loadClass
 126  * loadClass} methods).
 127  *
 128  * <h3> <a id="builtinLoaders">Run-time Built-in Class Loaders</a></h3>
 129  *
 130  * The Java run-time has the following built-in class loaders:
 131  *
 132  * <ul>
 133  * <li><p>Bootstrap class loader.
 134  *     It is the virtual machine's built-in class loader, typically represented
 135  *     as {@code null}, and does not have a parent.</li>
 136  * <li><p>{@linkplain #getPlatformClassLoader() Platform class loader}.
 137  *     All <em>platform classes</em> are visible to the platform class loader
 138  *     that can be used as the parent of a {@code ClassLoader} instance.
 139  *     Platform classes include Java SE platform APIs, their implementation
 140  *     classes and JDK-specific run-time classes that are defined by the
 141  *     platform class loader or its ancestors.
 142  *     <p> To allow for upgrading/overriding of modules defined to the platform
 143  *     class loader, and where upgraded modules read modules defined to class
 144  *     loaders other than the platform class loader and its ancestors, then
 145  *     the platform class loader may have to delegate to other class loaders,
 146  *     the application class loader for example.
 147  *     In other words, classes in named modules defined to class loaders
 148  *     other than the platform class loader and its ancestors may be visible
 149  *     to the platform class loader. </li>
 150  * <li><p>{@linkplain #getSystemClassLoader() System class loader}.
 151  *     It is also known as <em>application class loader</em> and is distinct
 152  *     from the platform class loader.
 153  *     The system class loader is typically used to define classes on the
 154  *     application class path, module path, and JDK-specific tools.
 155  *     The platform class loader is a parent or an ancestor of the system class
 156  *     loader that all platform classes are visible to it.</li>
 157  * </ul>
 158  *
 159  * <p> Normally, the Java virtual machine loads classes from the local file
 160  * system in a platform-dependent manner.
 161  * However, some classes may not originate from a file; they may originate
 162  * from other sources, such as the network, or they could be constructed by an
 163  * application.  The method {@link #defineClass(String, byte[], int, int)
 164  * defineClass} converts an array of bytes into an instance of class
 165  * {@code Class}. Instances of this newly defined class can be created using
 166  * {@link Class#newInstance Class.newInstance}.
 167  *
 168  * <p> The methods and constructors of objects created by a class loader may
 169  * reference other classes.  To determine the class(es) referred to, the Java
 170  * virtual machine invokes the {@link #loadClass loadClass} method of
 171  * the class loader that originally created the class.
 172  *
 173  * <p> For example, an application could create a network class loader to
 174  * download class files from a server.  Sample code might look like:
 175  *
 176  * <blockquote><pre>
 177  *   ClassLoader loader&nbsp;= new NetworkClassLoader(host,&nbsp;port);
 178  *   Object main&nbsp;= loader.loadClass("Main", true).newInstance();
 179  *       &nbsp;.&nbsp;.&nbsp;.
 180  * </pre></blockquote>
 181  *
 182  * <p> The network class loader subclass must define the methods {@link
 183  * #findClass findClass} and {@code loadClassData} to load a class
 184  * from the network.  Once it has downloaded the bytes that make up the class,
 185  * it should use the method {@link #defineClass defineClass} to
 186  * create a class instance.  A sample implementation is:
 187  *
 188  * <blockquote><pre>
 189  *     class NetworkClassLoader extends ClassLoader {
 190  *         String host;
 191  *         int port;
 192  *
 193  *         public Class findClass(String name) {
 194  *             byte[] b = loadClassData(name);
 195  *             return defineClass(name, b, 0, b.length);
 196  *         }
 197  *
 198  *         private byte[] loadClassData(String name) {
 199  *             // load the class data from the connection
 200  *             &nbsp;.&nbsp;.&nbsp;.
 201  *         }
 202  *     }
 203  * </pre></blockquote>
 204  *
 205  * <h3> <a id="name">Binary names</a> </h3>
 206  *
 207  * <p> Any class name provided as a {@code String} parameter to methods in
 208  * {@code ClassLoader} must be a binary name as defined by
 209  * <cite>The Java&trade; Language Specification</cite>.
 210  *
 211  * <p> Examples of valid class names include:
 212  * <blockquote><pre>
 213  *   "java.lang.String"
 214  *   "javax.swing.JSpinner$DefaultEditor"
 215  *   "java.security.KeyStore$Builder$FileBuilder$1"
 216  *   "java.net.URLClassLoader$3$1"
 217  * </pre></blockquote>
 218  *
 219  * <p> Any package name provided as a {@code String} parameter to methods in
 220  * {@code ClassLoader} must be either the empty string (denoting an unnamed package)
 221  * or a fully qualified name as defined by
 222  * <cite>The Java&trade; Language Specification</cite>.
 223  *
 224  * @jls 6.7  Fully Qualified Names
 225  * @jls 13.1 The Form of a Binary
 226  * @see      #resolveClass(Class)
 227  * @since 1.0
 228  * @revised 9
 229  * @spec JPMS
 230  */
 231 public abstract class ClassLoader {
 232 
 233     private static native void registerNatives();
 234     static {
 235         registerNatives();
 236     }
 237 
 238     // The parent class loader for delegation
 239     // Note: VM hardcoded the offset of this field, thus all new fields
 240     // must be added *after* it.
 241     private final ClassLoader parent;
 242 
 243     // class loader name
 244     private final String name;
 245 
 246     // the unnamed module for this ClassLoader
 247     private final Module unnamedModule;
 248 
 249     /**
 250      * Encapsulates the set of parallel capable loader types.
 251      */
 252     private static class ParallelLoaders {
 253         private ParallelLoaders() {}
 254 
 255         // the set of parallel capable loader types
 256         private static final Set<Class<? extends ClassLoader>> loaderTypes =
 257             Collections.newSetFromMap(new WeakHashMap<>());
 258         static {
 259             synchronized (loaderTypes) { loaderTypes.add(ClassLoader.class); }
 260         }
 261 
 262         /**
 263          * Registers the given class loader type as parallel capable.
 264          * Returns {@code true} is successfully registered; {@code false} if
 265          * loader's super class is not registered.
 266          */
 267         static boolean register(Class<? extends ClassLoader> c) {
 268             synchronized (loaderTypes) {
 269                 if (loaderTypes.contains(c.getSuperclass())) {
 270                     // register the class loader as parallel capable
 271                     // if and only if all of its super classes are.
 272                     // Note: given current classloading sequence, if
 273                     // the immediate super class is parallel capable,
 274                     // all the super classes higher up must be too.
 275                     loaderTypes.add(c);
 276                     return true;
 277                 } else {
 278                     return false;
 279                 }
 280             }
 281         }
 282 
 283         /**
 284          * Returns {@code true} if the given class loader type is
 285          * registered as parallel capable.
 286          */
 287         static boolean isRegistered(Class<? extends ClassLoader> c) {
 288             synchronized (loaderTypes) {
 289                 return loaderTypes.contains(c);
 290             }
 291         }
 292     }
 293 
 294     // Maps class name to the corresponding lock object when the current
 295     // class loader is parallel capable.
 296     // Note: VM also uses this field to decide if the current class loader
 297     // is parallel capable and the appropriate lock object for class loading.
 298     private final ConcurrentHashMap<String, Object> parallelLockMap;
 299 
 300     // Maps packages to certs
 301     private final Map <String, Certificate[]> package2certs;
 302 
 303     // Shared among all packages with unsigned classes
 304     private static final Certificate[] nocerts = new Certificate[0];
 305 
 306     // The classes loaded by this class loader. The only purpose of this table
 307     // is to keep the classes from being GC'ed until the loader is GC'ed.
 308     private final Vector<Class<?>> classes = new Vector<>();
 309 
 310     // The "default" domain. Set as the default ProtectionDomain on newly
 311     // created classes.
 312     private final ProtectionDomain defaultDomain =
 313         new ProtectionDomain(new CodeSource(null, (Certificate[]) null),
 314                              null, this, null);
 315 
 316     // Invoked by the VM to record every loaded class with this loader.
 317     void addClass(Class<?> c) {
 318         classes.addElement(c);
 319     }
 320 
 321     // The packages defined in this class loader.  Each package name is
 322     // mapped to its corresponding NamedPackage object.
 323     //
 324     // The value is a Package object if ClassLoader::definePackage,
 325     // Class::getPackage, ClassLoader::getDefinePackage(s) or
 326     // Package::getPackage(s) method is called to define it.
 327     // Otherwise, the value is a NamedPackage object.
 328     private final ConcurrentHashMap<String, NamedPackage> packages
 329             = new ConcurrentHashMap<>();
 330 
 331     /*
 332      * Returns a named package for the given module.
 333      */
 334     private NamedPackage getNamedPackage(String pn, Module m) {
 335         NamedPackage p = packages.get(pn);
 336         if (p == null) {
 337             p = new NamedPackage(pn, m);
 338 
 339             NamedPackage value = packages.putIfAbsent(pn, p);
 340             if (value != null) {
 341                 // Package object already be defined for the named package
 342                 p = value;
 343                 // if definePackage is called by this class loader to define
 344                 // a package in a named module, this will return Package
 345                 // object of the same name.  Package object may contain
 346                 // unexpected information but it does not impact the runtime.
 347                 // this assertion may be helpful for troubleshooting
 348                 assert value.module() == m;
 349             }
 350         }
 351         return p;
 352     }
 353 
 354     private static Void checkCreateClassLoader() {
 355         return checkCreateClassLoader(null);
 356     }
 357 
 358     private static Void checkCreateClassLoader(String name) {
 359         if (name != null && name.isEmpty()) {
 360             throw new IllegalArgumentException("name must be non-empty or null");
 361         }
 362 
 363         SecurityManager security = System.getSecurityManager();
 364         if (security != null) {
 365             security.checkCreateClassLoader();
 366         }
 367         return null;
 368     }
 369 
 370     private ClassLoader(Void unused, String name, ClassLoader parent) {
 371         this.name = name;
 372         this.parent = parent;
 373         this.unnamedModule = new Module(this);
 374         if (ParallelLoaders.isRegistered(this.getClass())) {
 375             parallelLockMap = new ConcurrentHashMap<>();
 376             package2certs = new ConcurrentHashMap<>();
 377             assertionLock = new Object();
 378         } else {
 379             // no finer-grained lock; lock on the classloader instance
 380             parallelLockMap = null;
 381             package2certs = new Hashtable<>();
 382             assertionLock = this;
 383         }
 384     }
 385 
 386     /**
 387      * Creates a new class loader of the specified name and using the
 388      * specified parent class loader for delegation.
 389      *
 390      * @apiNote If the parent is specified as {@code null} (for the
 391      * bootstrap class loader) then there is no guarantee that all platform
 392      * classes are visible.
 393      *
 394      * @param  name   class loader name; or {@code null} if not named
 395      * @param  parent the parent class loader
 396      *
 397      * @throws IllegalArgumentException if the given name is empty.
 398      *
 399      * @throws SecurityException
 400      *         If a security manager exists and its
 401      *         {@link SecurityManager#checkCreateClassLoader()}
 402      *         method doesn't allow creation of a new class loader.
 403      *
 404      * @since  9
 405      * @spec JPMS
 406      */
 407     protected ClassLoader(String name, ClassLoader parent) {
 408         this(checkCreateClassLoader(name), name, parent);
 409     }
 410 
 411     /**
 412      * Creates a new class loader using the specified parent class loader for
 413      * delegation.
 414      *
 415      * <p> If there is a security manager, its {@link
 416      * SecurityManager#checkCreateClassLoader() checkCreateClassLoader} method
 417      * is invoked.  This may result in a security exception.  </p>
 418      *
 419      * @apiNote If the parent is specified as {@code null} (for the
 420      * bootstrap class loader) then there is no guarantee that all platform
 421      * classes are visible.
 422      *
 423      * @param  parent
 424      *         The parent class loader
 425      *
 426      * @throws  SecurityException
 427      *          If a security manager exists and its
 428      *          {@code checkCreateClassLoader} method doesn't allow creation
 429      *          of a new class loader.
 430      *
 431      * @since  1.2
 432      */
 433     protected ClassLoader(ClassLoader parent) {
 434         this(checkCreateClassLoader(), null, parent);
 435     }
 436 
 437     /**
 438      * Creates a new class loader using the {@code ClassLoader} returned by
 439      * the method {@link #getSystemClassLoader()
 440      * getSystemClassLoader()} as the parent class loader.
 441      *
 442      * <p> If there is a security manager, its {@link
 443      * SecurityManager#checkCreateClassLoader()
 444      * checkCreateClassLoader} method is invoked.  This may result in
 445      * a security exception.  </p>
 446      *
 447      * @throws  SecurityException
 448      *          If a security manager exists and its
 449      *          {@code checkCreateClassLoader} method doesn't allow creation
 450      *          of a new class loader.
 451      */
 452     protected ClassLoader() {
 453         this(checkCreateClassLoader(), null, getSystemClassLoader());
 454     }
 455 
 456     /**
 457      * Returns the name of this class loader or {@code null} if
 458      * this class loader is not named.
 459      *
 460      * @apiNote This method is non-final for compatibility.  If this
 461      * method is overridden, this method must return the same name
 462      * as specified when this class loader was instantiated.
 463      *
 464      * @return name of this class loader; or {@code null} if
 465      * this class loader is not named.
 466      *
 467      * @since 9
 468      * @spec JPMS
 469      */
 470     public String getName() {
 471         return name;
 472     }
 473 
 474     // package-private used by StackTraceElement to avoid
 475     // calling the overrideable getName method
 476     final String name() {
 477         return name;
 478     }
 479 
 480     // -- Class --
 481 
 482     /**
 483      * Loads the class with the specified <a href="#name">binary name</a>.
 484      * This method searches for classes in the same manner as the {@link
 485      * #loadClass(String, boolean)} method.  It is invoked by the Java virtual
 486      * machine to resolve class references.  Invoking this method is equivalent
 487      * to invoking {@link #loadClass(String, boolean) loadClass(name,
 488      * false)}.
 489      *
 490      * @param  name
 491      *         The <a href="#name">binary name</a> of the class
 492      *
 493      * @return  The resulting {@code Class} object
 494      *
 495      * @throws  ClassNotFoundException
 496      *          If the class was not found
 497      */
 498     public Class<?> loadClass(String name) throws ClassNotFoundException {
 499         return loadClass(name, false);
 500     }
 501 
 502     /**
 503      * Loads the class with the specified <a href="#name">binary name</a>.  The
 504      * default implementation of this method searches for classes in the
 505      * following order:
 506      *
 507      * <ol>
 508      *
 509      *   <li><p> Invoke {@link #findLoadedClass(String)} to check if the class
 510      *   has already been loaded.  </p></li>
 511      *
 512      *   <li><p> Invoke the {@link #loadClass(String) loadClass} method
 513      *   on the parent class loader.  If the parent is {@code null} the class
 514      *   loader built into the virtual machine is used, instead.  </p></li>
 515      *
 516      *   <li><p> Invoke the {@link #findClass(String)} method to find the
 517      *   class.  </p></li>
 518      *
 519      * </ol>
 520      *
 521      * <p> If the class was found using the above steps, and the
 522      * {@code resolve} flag is true, this method will then invoke the {@link
 523      * #resolveClass(Class)} method on the resulting {@code Class} object.
 524      *
 525      * <p> Subclasses of {@code ClassLoader} are encouraged to override {@link
 526      * #findClass(String)}, rather than this method.  </p>
 527      *
 528      * <p> Unless overridden, this method synchronizes on the result of
 529      * {@link #getClassLoadingLock getClassLoadingLock} method
 530      * during the entire class loading process.
 531      *
 532      * @param  name
 533      *         The <a href="#name">binary name</a> of the class
 534      *
 535      * @param  resolve
 536      *         If {@code true} then resolve the class
 537      *
 538      * @return  The resulting {@code Class} object
 539      *
 540      * @throws  ClassNotFoundException
 541      *          If the class could not be found
 542      */
 543     protected Class<?> loadClass(String name, boolean resolve)
 544         throws ClassNotFoundException
 545     {
 546         synchronized (getClassLoadingLock(name)) {
 547             // First, check if the class has already been loaded
 548             Class<?> c = findLoadedClass(name);
 549             if (c == null) {
 550                 long t0 = System.nanoTime();
 551                 try {
 552                     if (parent != null) {
 553                         c = parent.loadClass(name, false);
 554                     } else {
 555                         c = findBootstrapClassOrNull(name);
 556                     }
 557                 } catch (ClassNotFoundException e) {
 558                     // ClassNotFoundException thrown if class not found
 559                     // from the non-null parent class loader
 560                 }
 561 
 562                 if (c == null) {
 563                     // If still not found, then invoke findClass in order
 564                     // to find the class.
 565                     long t1 = System.nanoTime();
 566                     c = findClass(name);
 567 
 568                     // this is the defining class loader; record the stats
 569                     PerfCounter.getParentDelegationTime().addTime(t1 - t0);
 570                     PerfCounter.getFindClassTime().addElapsedTimeFrom(t1);
 571                     PerfCounter.getFindClasses().increment();
 572                 }
 573             }
 574             if (resolve) {
 575                 resolveClass(c);
 576             }
 577             return c;
 578         }
 579     }
 580 
 581     /**
 582      * Loads the class with the specified <a href="#name">binary name</a>
 583      * in a module defined to this class loader.  This method returns {@code null}
 584      * if the class could not be found.
 585      *
 586      * @apiNote This method does not delegate to the parent class loader.
 587      *
 588      * @implSpec The default implementation of this method searches for classes
 589      * in the following order:
 590      *
 591      * <ol>
 592      *   <li>Invoke {@link #findLoadedClass(String)} to check if the class
 593      *   has already been loaded.</li>
 594      *   <li>Invoke the {@link #findClass(String, String)} method to find the
 595      *   class in the given module.</li>
 596      * </ol>
 597      *
 598      * @param  module
 599      *         The module
 600      * @param  name
 601      *         The <a href="#name">binary name</a> of the class
 602      *
 603      * @return The resulting {@code Class} object in a module defined by
 604      *         this class loader, or {@code null} if the class could not be found.
 605      */
 606     final Class<?> loadClass(Module module, String name) {
 607         synchronized (getClassLoadingLock(name)) {
 608             // First, check if the class has already been loaded
 609             Class<?> c = findLoadedClass(name);
 610             if (c == null) {
 611                 c = findClass(module.getName(), name);
 612             }
 613             if (c != null && c.getModule() == module) {
 614                 return c;
 615             } else {
 616                 return null;
 617             }
 618         }
 619     }
 620 
 621     /**
 622      * Returns the lock object for class loading operations.
 623      * For backward compatibility, the default implementation of this method
 624      * behaves as follows. If this ClassLoader object is registered as
 625      * parallel capable, the method returns a dedicated object associated
 626      * with the specified class name. Otherwise, the method returns this
 627      * ClassLoader object.
 628      *
 629      * @param  className
 630      *         The name of the to-be-loaded class
 631      *
 632      * @return the lock for class loading operations
 633      *
 634      * @throws NullPointerException
 635      *         If registered as parallel capable and {@code className} is null
 636      *
 637      * @see #loadClass(String, boolean)
 638      *
 639      * @since  1.7
 640      */
 641     protected Object getClassLoadingLock(String className) {
 642         Object lock = this;
 643         if (parallelLockMap != null) {
 644             Object newLock = new Object();
 645             lock = parallelLockMap.putIfAbsent(className, newLock);
 646             if (lock == null) {
 647                 lock = newLock;
 648             }
 649         }
 650         return lock;
 651     }
 652 
 653     // This method is invoked by the virtual machine to load a class.
 654     private Class<?> loadClassInternal(String name)
 655         throws ClassNotFoundException
 656     {
 657         // For backward compatibility, explicitly lock on 'this' when
 658         // the current class loader is not parallel capable.
 659         if (parallelLockMap == null) {
 660             synchronized (this) {
 661                  return loadClass(name);
 662             }
 663         } else {
 664             return loadClass(name);
 665         }
 666     }
 667 
 668     // Invoked by the VM after loading class with this loader.
 669     private void checkPackageAccess(Class<?> cls, ProtectionDomain pd) {
 670         final SecurityManager sm = System.getSecurityManager();
 671         if (sm != null) {
 672             if (ReflectUtil.isNonPublicProxyClass(cls)) {
 673                 for (Class<?> intf: cls.getInterfaces()) {
 674                     checkPackageAccess(intf, pd);
 675                 }
 676                 return;
 677             }
 678 
 679             final String packageName = cls.getPackageName();
 680             if (!packageName.isEmpty()) {
 681                 AccessController.doPrivileged(new PrivilegedAction<>() {
 682                     public Void run() {
 683                         sm.checkPackageAccess(packageName);
 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.  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.  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 {@code IllegalStateException} 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      * It reads the system property "{@code java.class.path}" during early
1880      * initialization of the VM to determine the class path.
1881      * An empty value of "{@code java.class.path}" property is interpreted
1882      * differently depending on whether the initial module is named or not:
1883      * If named, the built-in system class loader will have no class path
1884      * i.e. only find classes and resources only from the application module
1885      * path; otherwise, if unnamed, it will set the class path to
1886      * the current working directory.
1887      *
1888      * @return  The system {@code ClassLoader}
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 cannot be called during the system class loader instantiation";
1923                 throw new IllegalStateException(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                 Throwable cause = e;
1974                 if (e instanceof InvocationTargetException) {
1975                     cause = e.getCause();
1976                     if (cause instanceof Error) {
1977                         throw (Error) cause;
1978                     }
1979                 }
1980                 if (cause instanceof RuntimeException) {
1981                     throw (RuntimeException) cause;
1982                 }
1983                 throw new Error(cause.getMessage(), cause);
1984             }
1985         } else {
1986             scl = builtinLoader;
1987         }
1988         return scl;
1989     }
1990 
1991     // Returns true if the specified class loader can be found in this class
1992     // loader's delegation chain.
1993     boolean isAncestor(ClassLoader cl) {
1994         ClassLoader acl = this;
1995         do {
1996             acl = acl.parent;
1997             if (cl == acl) {
1998                 return true;
1999             }
2000         } while (acl != null);
2001         return false;
2002     }
2003 
2004     // Tests if class loader access requires "getClassLoader" permission
2005     // check.  A class loader 'from' can access class loader 'to' if
2006     // class loader 'from' is same as class loader 'to' or an ancestor
2007     // of 'to'.  The class loader in a system domain can access
2008     // any class loader.
2009     private static boolean needsClassLoaderPermissionCheck(ClassLoader from,
2010                                                            ClassLoader to)
2011     {
2012         if (from == to)
2013             return false;
2014 
2015         if (from == null)
2016             return false;
2017 
2018         return !to.isAncestor(from);
2019     }
2020 
2021     // Returns the class's class loader, or null if none.
2022     static ClassLoader getClassLoader(Class<?> caller) {
2023         // This can be null if the VM is requesting it
2024         if (caller == null) {
2025             return null;
2026         }
2027         // Circumvent security check since this is package-private
2028         return caller.getClassLoader0();
2029     }
2030 
2031     /*
2032      * Checks RuntimePermission("getClassLoader") permission
2033      * if caller's class loader is not null and caller's class loader
2034      * is not the same as or an ancestor of the given cl argument.
2035      */
2036     static void checkClassLoaderPermission(ClassLoader cl, Class<?> caller) {
2037         SecurityManager sm = System.getSecurityManager();
2038         if (sm != null) {
2039             // caller can be null if the VM is requesting it
2040             ClassLoader ccl = getClassLoader(caller);
2041             if (needsClassLoaderPermissionCheck(ccl, cl)) {
2042                 sm.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION);
2043             }
2044         }
2045     }
2046 
2047     // The system class loader
2048     // @GuardedBy("ClassLoader.class")
2049     private static volatile ClassLoader scl;
2050 
2051     // -- Package --
2052 
2053     /**
2054      * Define a Package of the given Class object.
2055      *
2056      * If the given class represents an array type, a primitive type or void,
2057      * this method returns {@code null}.
2058      *
2059      * This method does not throw IllegalArgumentException.
2060      */
2061     Package definePackage(Class<?> c) {
2062         if (c.isPrimitive() || c.isArray()) {
2063             return null;
2064         }
2065 
2066         return definePackage(c.getPackageName(), c.getModule());
2067     }
2068 
2069     /**
2070      * Defines a Package of the given name and module
2071      *
2072      * This method does not throw IllegalArgumentException.
2073      *
2074      * @param name package name
2075      * @param m    module
2076      */
2077     Package definePackage(String name, Module m) {
2078         if (name.isEmpty() && m.isNamed()) {
2079             throw new InternalError("unnamed package in  " + m);
2080         }
2081 
2082         // check if Package object is already defined
2083         NamedPackage pkg = packages.get(name);
2084         if (pkg instanceof Package)
2085             return (Package)pkg;
2086 
2087         return (Package)packages.compute(name, (n, p) -> toPackage(n, p, m));
2088     }
2089 
2090     /*
2091      * Returns a Package object for the named package
2092      */
2093     private Package toPackage(String name, NamedPackage p, Module m) {
2094         // define Package object if the named package is not yet defined
2095         if (p == null)
2096             return NamedPackage.toPackage(name, m);
2097 
2098         // otherwise, replace the NamedPackage object with Package object
2099         if (p instanceof Package)
2100             return (Package)p;
2101 
2102         return NamedPackage.toPackage(p.packageName(), p.module());
2103     }
2104 
2105     /**
2106      * Defines a package by <a href="#name">name</a> in this {@code ClassLoader}.
2107      * <p>
2108      * <a href="#name">Package names</a> must be unique within a class loader and
2109      * cannot be redefined or changed once created.
2110      * <p>
2111      * If a class loader wishes to define a package with specific properties,
2112      * such as version information, then the class loader should call this
2113      * {@code definePackage} method before calling {@code defineClass}.
2114      * Otherwise, the
2115      * {@link #defineClass(String, byte[], int, int, ProtectionDomain) defineClass}
2116      * method will define a package in this class loader corresponding to the package
2117      * of the newly defined class; the properties of this defined package are
2118      * specified by {@link Package}.
2119      *
2120      * @apiNote
2121      * A class loader that wishes to define a package for classes in a JAR
2122      * typically uses the specification and implementation titles, versions, and
2123      * vendors from the JAR's manifest. If the package is specified as
2124      * {@linkplain java.util.jar.Attributes.Name#SEALED sealed} in the JAR's manifest,
2125      * the {@code URL} of the JAR file is typically used as the {@code sealBase}.
2126      * If classes of package {@code 'p'} defined by this class loader
2127      * are loaded from multiple JARs, the {@code Package} object may contain
2128      * different information depending on the first class of package {@code 'p'}
2129      * defined and which JAR's manifest is read first to explicitly define
2130      * package {@code 'p'}.
2131      *
2132      * <p> It is strongly recommended that a class loader does not call this
2133      * method to explicitly define packages in <em>named modules</em>; instead,
2134      * the package will be automatically defined when a class is {@linkplain
2135      * #defineClass(String, byte[], int, int, ProtectionDomain) being defined}.
2136      * If it is desirable to define {@code Package} explicitly, it should ensure
2137      * that all packages in a named module are defined with the properties
2138      * specified by {@link Package}.  Otherwise, some {@code Package} objects
2139      * in a named module may be for example sealed with different seal base.
2140      *
2141      * @param  name
2142      *         The <a href="#name">package name</a>
2143      *
2144      * @param  specTitle
2145      *         The specification title
2146      *
2147      * @param  specVersion
2148      *         The specification version
2149      *
2150      * @param  specVendor
2151      *         The specification vendor
2152      *
2153      * @param  implTitle
2154      *         The implementation title
2155      *
2156      * @param  implVersion
2157      *         The implementation version
2158      *
2159      * @param  implVendor
2160      *         The implementation vendor
2161      *
2162      * @param  sealBase
2163      *         If not {@code null}, then this package is sealed with
2164      *         respect to the given code source {@link java.net.URL URL}
2165      *         object.  Otherwise, the package is not sealed.
2166      *
2167      * @return  The newly defined {@code Package} object
2168      *
2169      * @throws  NullPointerException
2170      *          if {@code name} is {@code null}.
2171      *
2172      * @throws  IllegalArgumentException
2173      *          if a package of the given {@code name} is already
2174      *          defined by this class loader
2175      *
2176      *
2177      * @since  1.2
2178      * @revised 9
2179      * @spec JPMS
2180      *
2181      * @jvms 5.3 Run-time package
2182      * @see <a href="{@docRoot}/../specs/jar/jar.html#package-sealing">
2183      *      The JAR File Specification: Package Sealing</a>
2184      */
2185     protected Package definePackage(String name, String specTitle,
2186                                     String specVersion, String specVendor,
2187                                     String implTitle, String implVersion,
2188                                     String implVendor, URL sealBase)
2189     {
2190         Objects.requireNonNull(name);
2191 
2192         // definePackage is not final and may be overridden by custom class loader
2193         Package p = new Package(name, specTitle, specVersion, specVendor,
2194                                 implTitle, implVersion, implVendor,
2195                                 sealBase, this);
2196 
2197         if (packages.putIfAbsent(name, p) != null)
2198             throw new IllegalArgumentException(name);
2199 
2200         return p;
2201     }
2202 
2203     /**
2204      * Returns a {@code Package} of the given <a href="#name">name</a> that
2205      * has been defined by this class loader.
2206      *
2207      * @param  name The <a href="#name">package name</a>
2208      *
2209      * @return The {@code Package} of the given name that has been defined
2210      *         by this class loader, or {@code null} if not found
2211      *
2212      * @throws  NullPointerException
2213      *          if {@code name} is {@code null}.
2214      *
2215      * @jvms 5.3 Run-time package
2216      *
2217      * @since  9
2218      * @spec JPMS
2219      */
2220     public final Package getDefinedPackage(String name) {
2221         Objects.requireNonNull(name, "name cannot be null");
2222 
2223         NamedPackage p = packages.get(name);
2224         if (p == null)
2225             return null;
2226 
2227         return definePackage(name, p.module());
2228     }
2229 
2230     /**
2231      * Returns all of the {@code Package}s that have been defined by
2232      * this class loader.  The returned array has no duplicated {@code Package}s
2233      * of the same name.
2234      *
2235      * @apiNote This method returns an array rather than a {@code Set} or {@code Stream}
2236      *          for consistency with the existing {@link #getPackages} method.
2237      *
2238      * @return The array of {@code Package} objects that have been defined by
2239      *         this class loader; or an zero length array if no package has been
2240      *         defined by this class loader.
2241      *
2242      * @jvms 5.3 Run-time package
2243      *
2244      * @since  9
2245      * @spec JPMS
2246      */
2247     public final Package[] getDefinedPackages() {
2248         return packages().toArray(Package[]::new);
2249     }
2250 
2251     /**
2252      * Finds a package by <a href="#name">name</a> in this class loader and its ancestors.
2253      * <p>
2254      * If this class loader defines a {@code Package} of the given name,
2255      * the {@code Package} is returned. Otherwise, the ancestors of
2256      * this class loader are searched recursively (parent by parent)
2257      * for a {@code Package} of the given name.
2258      *
2259      * @apiNote The {@link #getPlatformClassLoader() platform class loader}
2260      * may delegate to the application class loader but the application class
2261      * loader is not its ancestor.  When invoked on the platform class loader,
2262      * this method  will not find packages defined to the application
2263      * class loader.
2264      *
2265      * @param  name
2266      *         The <a href="#name">package name</a>
2267      *
2268      * @return The {@code Package} of the given name that has been defined by
2269      *         this class loader or its ancestors, or {@code null} if not found.
2270      *
2271      * @throws  NullPointerException
2272      *          if {@code name} is {@code null}.
2273      *
2274      * @deprecated
2275      * If multiple class loaders delegate to each other and define classes
2276      * with the same package name, and one such loader relies on the lookup
2277      * behavior of {@code getPackage} to return a {@code Package} from
2278      * a parent loader, then the properties exposed by the {@code Package}
2279      * may not be as expected in the rest of the program.
2280      * For example, the {@code Package} will only expose annotations from the
2281      * {@code package-info.class} file defined by the parent loader, even if
2282      * annotations exist in a {@code package-info.class} file defined by
2283      * a child loader.  A more robust approach is to use the
2284      * {@link ClassLoader#getDefinedPackage} method which returns
2285      * a {@code Package} for the specified class loader.
2286      *
2287      * @see ClassLoader#getDefinedPackage(String)
2288      *
2289      * @since  1.2
2290      * @revised 9
2291      * @spec JPMS
2292      */
2293     @Deprecated(since="9")
2294     protected Package getPackage(String name) {
2295         Package pkg = getDefinedPackage(name);
2296         if (pkg == null) {
2297             if (parent != null) {
2298                 pkg = parent.getPackage(name);
2299             } else {
2300                 pkg = BootLoader.getDefinedPackage(name);
2301             }
2302         }
2303         return pkg;
2304     }
2305 
2306     /**
2307      * Returns all of the {@code Package}s that have been defined by
2308      * this class loader and its ancestors.  The returned array may contain
2309      * more than one {@code Package} object of the same package name, each
2310      * defined by a different class loader in the class loader hierarchy.
2311      *
2312      * @apiNote The {@link #getPlatformClassLoader() platform class loader}
2313      * may delegate to the application class loader. In other words,
2314      * packages in modules defined to the application class loader may be
2315      * visible to the platform class loader.  On the other hand,
2316      * the application class loader is not its ancestor and hence
2317      * when invoked on the platform class loader, this method will not
2318      * return any packages defined to the application class loader.
2319      *
2320      * @return  The array of {@code Package} objects that have been defined by
2321      *          this class loader and its ancestors
2322      *
2323      * @see ClassLoader#getDefinedPackages()
2324      *
2325      * @since  1.2
2326      * @revised 9
2327      * @spec JPMS
2328      */
2329     protected Package[] getPackages() {
2330         Stream<Package> pkgs = packages();
2331         ClassLoader ld = parent;
2332         while (ld != null) {
2333             pkgs = Stream.concat(ld.packages(), pkgs);
2334             ld = ld.parent;
2335         }
2336         return Stream.concat(BootLoader.packages(), pkgs)
2337                      .toArray(Package[]::new);
2338     }
2339 
2340 
2341 
2342     // package-private
2343 
2344     /**
2345      * Returns a stream of Packages defined in this class loader
2346      */
2347     Stream<Package> packages() {
2348         return packages.values().stream()
2349                        .map(p -> definePackage(p.packageName(), p.module()));
2350     }
2351 
2352     // -- Native library access --
2353 
2354     /**
2355      * Returns the absolute path name of a native library.  The VM invokes this
2356      * method to locate the native libraries that belong to classes loaded with
2357      * this class loader. If this method returns {@code null}, the VM
2358      * searches the library along the path specified as the
2359      * "{@code java.library.path}" property.
2360      *
2361      * @param  libname
2362      *         The library name
2363      *
2364      * @return  The absolute path of the native library
2365      *
2366      * @see  System#loadLibrary(String)
2367      * @see  System#mapLibraryName(String)
2368      *
2369      * @since  1.2
2370      */
2371     protected String findLibrary(String libname) {
2372         return null;
2373     }
2374 
2375     /**
2376      * The inner class NativeLibrary denotes a loaded native library instance.
2377      * Every classloader contains a vector of loaded native libraries in the
2378      * private field {@code nativeLibraries}.  The native libraries loaded
2379      * into the system are entered into the {@code systemNativeLibraries}
2380      * vector.
2381      *
2382      * <p> Every native library requires a particular version of JNI. This is
2383      * denoted by the private {@code jniVersion} field.  This field is set by
2384      * the VM when it loads the library, and used by the VM to pass the correct
2385      * version of JNI to the native methods.  </p>
2386      *
2387      * @see      ClassLoader
2388      * @since    1.2
2389      */
2390     static class NativeLibrary {
2391         // the class from which the library is loaded, also indicates
2392         // the loader this native library belongs.
2393         final Class<?> fromClass;
2394         // the canonicalized name of the native library.
2395         // or static library name
2396         final String name;
2397         // Indicates if the native library is linked into the VM
2398         final boolean isBuiltin;
2399 
2400         // opaque handle to native library, used in native code.
2401         long handle;
2402         // the version of JNI environment the native library requires.
2403         int jniVersion;
2404 
2405         native boolean load0(String name, boolean isBuiltin);
2406 
2407         native long findEntry(String name);
2408 
2409         NativeLibrary(Class<?> fromClass, String name, boolean isBuiltin) {
2410             this.name = name;
2411             this.fromClass = fromClass;
2412             this.isBuiltin = isBuiltin;
2413         }
2414 
2415         /*
2416          * Loads the native library and registers for cleanup when its
2417          * associated class loader is unloaded
2418          */
2419         boolean load() {
2420             if (handle != 0) {
2421                 throw new InternalError("Native library " + name + " has been loaded");
2422             }
2423 
2424             if (!load0(name, isBuiltin)) return false;
2425 
2426             // register the class loader for cleanup when unloaded
2427             // built class loaders are never unloaded
2428             ClassLoader loader = fromClass.getClassLoader();
2429             if (loader != null &&
2430                 loader != getBuiltinPlatformClassLoader() &&
2431                 loader != getBuiltinAppClassLoader()) {
2432                 CleanerFactory.cleaner().register(loader,
2433                         new Unloader(name, handle, isBuiltin));
2434             }
2435             return true;
2436         }
2437 
2438         static boolean loadLibrary(Class<?> fromClass, String name, boolean isBuiltin) {
2439             ClassLoader loader =
2440                 fromClass == null ? null : fromClass.getClassLoader();
2441 
2442             synchronized (loadedLibraryNames) {
2443                 Map<String, NativeLibrary> libs =
2444                     loader != null ? loader.nativeLibraries() : systemNativeLibraries();
2445                 if (libs.containsKey(name)) {
2446                     return true;
2447                 }
2448 
2449                 if (loadedLibraryNames.contains(name)) {
2450                     throw new UnsatisfiedLinkError("Native Library " + name +
2451                         " already loaded in another classloader");
2452                 }
2453 
2454                 /*
2455                  * When a library is being loaded, JNI_OnLoad function can cause
2456                  * another loadLibrary invocation that should succeed.
2457                  *
2458                  * We use a static stack to hold the list of libraries we are
2459                  * loading because this can happen only when called by the
2460                  * same thread because Runtime.load and Runtime.loadLibrary
2461                  * are synchronous.
2462                  *
2463                  * If there is a pending load operation for the library, we
2464                  * immediately return success; otherwise, we raise
2465                  * UnsatisfiedLinkError.
2466                  */
2467                 for (NativeLibrary lib : nativeLibraryContext) {
2468                     if (name.equals(lib.name)) {
2469                         if (loader == lib.fromClass.getClassLoader()) {
2470                             return true;
2471                         } else {
2472                             throw new UnsatisfiedLinkError("Native Library " +
2473                                 name + " is being loaded in another classloader");
2474                         }
2475                     }
2476                 }
2477                 NativeLibrary lib = new NativeLibrary(fromClass, name, isBuiltin);
2478                 // load the native library
2479                 nativeLibraryContext.push(lib);
2480                 try {
2481                     if (!lib.load()) return false;
2482                 } finally {
2483                     nativeLibraryContext.pop();
2484                 }
2485                 // register the loaded native library
2486                 loadedLibraryNames.add(name);
2487                 libs.put(name, lib);
2488             }
2489             return true;
2490         }
2491 
2492         // Invoked in the VM to determine the context class in JNI_OnLoad
2493         // and JNI_OnUnload
2494         static Class<?> getFromClass() {
2495             return nativeLibraryContext.peek().fromClass;
2496         }
2497 
2498         // native libraries being loaded
2499         static Deque<NativeLibrary> nativeLibraryContext = new ArrayDeque<>(8);
2500 
2501         /*
2502          * The run() method will be invoked when this class loader becomes
2503          * phantom reachable to unload the native library.
2504          */
2505         static class Unloader implements Runnable {
2506             // This represents the context when a native library is unloaded
2507             // and getFromClass() will return null,
2508             static final NativeLibrary UNLOADER =
2509                 new NativeLibrary(null, "dummy", false);
2510             final String name;
2511             final long handle;
2512             final boolean isBuiltin;
2513 
2514             Unloader(String name, long handle, boolean isBuiltin) {
2515                 if (handle == 0) {
2516                     throw new IllegalArgumentException(
2517                         "Invalid handle for native library " + name);
2518                 }
2519 
2520                 this.name = name;
2521                 this.handle = handle;
2522                 this.isBuiltin = isBuiltin;
2523             }
2524 
2525             @Override
2526             public void run() {
2527                 synchronized (loadedLibraryNames) {
2528                     /* remove the native library name */
2529                     loadedLibraryNames.remove(name);
2530                     nativeLibraryContext.push(UNLOADER);
2531                     try {
2532                         unload(name, isBuiltin, handle);
2533                     } finally {
2534                         nativeLibraryContext.pop();
2535                     }
2536 
2537                 }
2538             }
2539         }
2540 
2541         // JNI FindClass expects the caller class if invoked from JNI_OnLoad
2542         // and JNI_OnUnload is NativeLibrary class
2543         static native void unload(String name, boolean isBuiltin, long handle);
2544     }
2545 
2546     // The paths searched for libraries
2547     private static String usr_paths[];
2548     private static String sys_paths[];
2549 
2550     private static String[] initializePath(String propName) {
2551         String ldPath = System.getProperty(propName, "");
2552         int ldLen = ldPath.length();
2553         char ps = File.pathSeparatorChar;
2554         int psCount = 0;
2555 
2556         if (ClassLoaderHelper.allowsQuotedPathElements &&
2557             ldPath.indexOf('\"') >= 0) {
2558             // First, remove quotes put around quoted parts of paths.
2559             // Second, use a quotation mark as a new path separator.
2560             // This will preserve any quoted old path separators.
2561             char[] buf = new char[ldLen];
2562             int bufLen = 0;
2563             for (int i = 0; i < ldLen; ++i) {
2564                 char ch = ldPath.charAt(i);
2565                 if (ch == '\"') {
2566                     while (++i < ldLen &&
2567                         (ch = ldPath.charAt(i)) != '\"') {
2568                         buf[bufLen++] = ch;
2569                     }
2570                 } else {
2571                     if (ch == ps) {
2572                         psCount++;
2573                         ch = '\"';
2574                     }
2575                     buf[bufLen++] = ch;
2576                 }
2577             }
2578             ldPath = new String(buf, 0, bufLen);
2579             ldLen = bufLen;
2580             ps = '\"';
2581         } else {
2582             for (int i = ldPath.indexOf(ps); i >= 0;
2583                  i = ldPath.indexOf(ps, i + 1)) {
2584                 psCount++;
2585             }
2586         }
2587 
2588         String[] paths = new String[psCount + 1];
2589         int pathStart = 0;
2590         for (int j = 0; j < psCount; ++j) {
2591             int pathEnd = ldPath.indexOf(ps, pathStart);
2592             paths[j] = (pathStart < pathEnd) ?
2593                 ldPath.substring(pathStart, pathEnd) : ".";
2594             pathStart = pathEnd + 1;
2595         }
2596         paths[psCount] = (pathStart < ldLen) ?
2597             ldPath.substring(pathStart, ldLen) : ".";
2598         return paths;
2599     }
2600 
2601     // Invoked in the java.lang.Runtime class to implement load and loadLibrary.
2602     static void loadLibrary(Class<?> fromClass, String name,
2603                             boolean isAbsolute) {
2604         ClassLoader loader =
2605             (fromClass == null) ? null : fromClass.getClassLoader();
2606         if (sys_paths == null) {
2607             usr_paths = initializePath("java.library.path");
2608             sys_paths = initializePath("sun.boot.library.path");
2609         }
2610         if (isAbsolute) {
2611             if (loadLibrary0(fromClass, new File(name))) {
2612                 return;
2613             }
2614             throw new UnsatisfiedLinkError("Can't load library: " + name);
2615         }
2616         if (loader != null) {
2617             String libfilename = loader.findLibrary(name);
2618             if (libfilename != null) {
2619                 File libfile = new File(libfilename);
2620                 if (!libfile.isAbsolute()) {
2621                     throw new UnsatisfiedLinkError(
2622                         "ClassLoader.findLibrary failed to return an absolute path: " + libfilename);
2623                 }
2624                 if (loadLibrary0(fromClass, libfile)) {
2625                     return;
2626                 }
2627                 throw new UnsatisfiedLinkError("Can't load " + libfilename);
2628             }
2629         }
2630         for (String sys_path : sys_paths) {
2631             File libfile = new File(sys_path, System.mapLibraryName(name));
2632             if (loadLibrary0(fromClass, libfile)) {
2633                 return;
2634             }
2635             libfile = ClassLoaderHelper.mapAlternativeName(libfile);
2636             if (libfile != null && loadLibrary0(fromClass, libfile)) {
2637                 return;
2638             }
2639         }
2640         if (loader != null) {
2641             for (String usr_path : usr_paths) {
2642                 File libfile = new File(usr_path, System.mapLibraryName(name));
2643                 if (loadLibrary0(fromClass, libfile)) {
2644                     return;
2645                 }
2646                 libfile = ClassLoaderHelper.mapAlternativeName(libfile);
2647                 if (libfile != null && loadLibrary0(fromClass, libfile)) {
2648                     return;
2649                 }
2650             }
2651         }
2652         // Oops, it failed
2653         throw new UnsatisfiedLinkError("no " + name +
2654             " in java.library.path: " + Arrays.toString(usr_paths));
2655     }
2656 
2657     private static native String findBuiltinLib(String name);
2658 
2659     private static boolean loadLibrary0(Class<?> fromClass, final File file) {
2660         // Check to see if we're attempting to access a static library
2661         String name = findBuiltinLib(file.getName());
2662         boolean isBuiltin = (name != null);
2663         if (!isBuiltin) {
2664             name = AccessController.doPrivileged(
2665                 new PrivilegedAction<>() {
2666                     public String run() {
2667                         try {
2668                             return file.exists() ? file.getCanonicalPath() : null;
2669                         } catch (IOException e) {
2670                             return null;
2671                         }
2672                     }
2673                 });
2674             if (name == null) {
2675                 return false;
2676             }
2677         }
2678         return NativeLibrary.loadLibrary(fromClass, name, isBuiltin);
2679     }
2680 
2681     /*
2682      * Invoked in the VM class linking code.
2683      */
2684     private static long findNative(ClassLoader loader, String entryName) {
2685         Map<String, NativeLibrary> libs =
2686             loader != null ? loader.nativeLibraries() : systemNativeLibraries();
2687         if (libs.isEmpty())
2688             return 0;
2689 
2690         // the native libraries map may be updated in another thread
2691         // when a native library is being loaded.  No symbol will be
2692         // searched from it yet.
2693         for (NativeLibrary lib : libs.values()) {
2694             long entry = lib.findEntry(entryName);
2695             if (entry != 0) return entry;
2696         }
2697         return 0;
2698     }
2699 
2700     // All native library names we've loaded.
2701     // This also serves as the lock to obtain nativeLibraries
2702     // and write to nativeLibraryContext.
2703     private static final Set<String> loadedLibraryNames = new HashSet<>();
2704 
2705     // Native libraries belonging to system classes.
2706     private static volatile Map<String, NativeLibrary> systemNativeLibraries;
2707 
2708     // Native libraries associated with the class loader.
2709     private volatile Map<String, NativeLibrary> nativeLibraries;
2710 
2711     /*
2712      * Returns the native libraries map associated with bootstrap class loader
2713      * This method will create the map at the first time when called.
2714      */
2715     private static Map<String, NativeLibrary> systemNativeLibraries() {
2716         Map<String, NativeLibrary> libs = systemNativeLibraries;
2717         if (libs == null) {
2718             synchronized (loadedLibraryNames) {
2719                 libs = systemNativeLibraries;
2720                 if (libs == null) {
2721                     libs = systemNativeLibraries = new ConcurrentHashMap<>();
2722                 }
2723             }
2724         }
2725         return libs;
2726     }
2727 
2728     /*
2729      * Returns the native libraries map associated with this class loader
2730      * This method will create the map at the first time when called.
2731      */
2732     private Map<String, NativeLibrary> nativeLibraries() {
2733         Map<String, NativeLibrary> libs = nativeLibraries;
2734         if (libs == null) {
2735             synchronized (loadedLibraryNames) {
2736                 libs = nativeLibraries;
2737                 if (libs == null) {
2738                     libs = nativeLibraries = new ConcurrentHashMap<>();
2739                 }
2740             }
2741         }
2742         return libs;
2743     }
2744 
2745     // -- Assertion management --
2746 
2747     final Object assertionLock;
2748 
2749     // The default toggle for assertion checking.
2750     // @GuardedBy("assertionLock")
2751     private boolean defaultAssertionStatus = false;
2752 
2753     // Maps String packageName to Boolean package default assertion status Note
2754     // that the default package is placed under a null map key.  If this field
2755     // is null then we are delegating assertion status queries to the VM, i.e.,
2756     // none of this ClassLoader's assertion status modification methods have
2757     // been invoked.
2758     // @GuardedBy("assertionLock")
2759     private Map<String, Boolean> packageAssertionStatus = null;
2760 
2761     // Maps String fullyQualifiedClassName to Boolean assertionStatus If this
2762     // field is null then we are delegating assertion status queries to the VM,
2763     // i.e., none of this ClassLoader's assertion status modification methods
2764     // have been invoked.
2765     // @GuardedBy("assertionLock")
2766     Map<String, Boolean> classAssertionStatus = null;
2767 
2768     /**
2769      * Sets the default assertion status for this class loader.  This setting
2770      * determines whether classes loaded by this class loader and initialized
2771      * in the future will have assertions enabled or disabled by default.
2772      * This setting may be overridden on a per-package or per-class basis by
2773      * invoking {@link #setPackageAssertionStatus(String, boolean)} or {@link
2774      * #setClassAssertionStatus(String, boolean)}.
2775      *
2776      * @param  enabled
2777      *         {@code true} if classes loaded by this class loader will
2778      *         henceforth have assertions enabled by default, {@code false}
2779      *         if they will have assertions disabled by default.
2780      *
2781      * @since  1.4
2782      */
2783     public void setDefaultAssertionStatus(boolean enabled) {
2784         synchronized (assertionLock) {
2785             if (classAssertionStatus == null)
2786                 initializeJavaAssertionMaps();
2787 
2788             defaultAssertionStatus = enabled;
2789         }
2790     }
2791 
2792     /**
2793      * Sets the package default assertion status for the named package.  The
2794      * package default assertion status determines the assertion status for
2795      * classes initialized in the future that belong to the named package or
2796      * any of its "subpackages".
2797      *
2798      * <p> A subpackage of a package named p is any package whose name begins
2799      * with "{@code p.}".  For example, {@code javax.swing.text} is a
2800      * subpackage of {@code javax.swing}, and both {@code java.util} and
2801      * {@code java.lang.reflect} are subpackages of {@code java}.
2802      *
2803      * <p> In the event that multiple package defaults apply to a given class,
2804      * the package default pertaining to the most specific package takes
2805      * precedence over the others.  For example, if {@code javax.lang} and
2806      * {@code javax.lang.reflect} both have package defaults associated with
2807      * them, the latter package default applies to classes in
2808      * {@code javax.lang.reflect}.
2809      *
2810      * <p> Package defaults take precedence over the class loader's default
2811      * assertion status, and may be overridden on a per-class basis by invoking
2812      * {@link #setClassAssertionStatus(String, boolean)}.  </p>
2813      *
2814      * @param  packageName
2815      *         The name of the package whose package default assertion status
2816      *         is to be set. A {@code null} value indicates the unnamed
2817      *         package that is "current"
2818      *         (see section 7.4.2 of
2819      *         <cite>The Java&trade; Language Specification</cite>.)
2820      *
2821      * @param  enabled
2822      *         {@code true} if classes loaded by this classloader and
2823      *         belonging to the named package or any of its subpackages will
2824      *         have assertions enabled by default, {@code false} if they will
2825      *         have assertions disabled by default.
2826      *
2827      * @since  1.4
2828      */
2829     public void setPackageAssertionStatus(String packageName,
2830                                           boolean enabled) {
2831         synchronized (assertionLock) {
2832             if (packageAssertionStatus == null)
2833                 initializeJavaAssertionMaps();
2834 
2835             packageAssertionStatus.put(packageName, enabled);
2836         }
2837     }
2838 
2839     /**
2840      * Sets the desired assertion status for the named top-level class in this
2841      * class loader and any nested classes contained therein.  This setting
2842      * takes precedence over the class loader's default assertion status, and
2843      * over any applicable per-package default.  This method has no effect if
2844      * the named class has already been initialized.  (Once a class is
2845      * initialized, its assertion status cannot change.)
2846      *
2847      * <p> If the named class is not a top-level class, this invocation will
2848      * have no effect on the actual assertion status of any class. </p>
2849      *
2850      * @param  className
2851      *         The fully qualified class name of the top-level class whose
2852      *         assertion status is to be set.
2853      *
2854      * @param  enabled
2855      *         {@code true} if the named class is to have assertions
2856      *         enabled when (and if) it is initialized, {@code false} if the
2857      *         class is to have assertions disabled.
2858      *
2859      * @since  1.4
2860      */
2861     public void setClassAssertionStatus(String className, boolean enabled) {
2862         synchronized (assertionLock) {
2863             if (classAssertionStatus == null)
2864                 initializeJavaAssertionMaps();
2865 
2866             classAssertionStatus.put(className, enabled);
2867         }
2868     }
2869 
2870     /**
2871      * Sets the default assertion status for this class loader to
2872      * {@code false} and discards any package defaults or class assertion
2873      * status settings associated with the class loader.  This method is
2874      * provided so that class loaders can be made to ignore any command line or
2875      * persistent assertion status settings and "start with a clean slate."
2876      *
2877      * @since  1.4
2878      */
2879     public void clearAssertionStatus() {
2880         /*
2881          * Whether or not "Java assertion maps" are initialized, set
2882          * them to empty maps, effectively ignoring any present settings.
2883          */
2884         synchronized (assertionLock) {
2885             classAssertionStatus = new HashMap<>();
2886             packageAssertionStatus = new HashMap<>();
2887             defaultAssertionStatus = false;
2888         }
2889     }
2890 
2891     /**
2892      * Returns the assertion status that would be assigned to the specified
2893      * class if it were to be initialized at the time this method is invoked.
2894      * If the named class has had its assertion status set, the most recent
2895      * setting will be returned; otherwise, if any package default assertion
2896      * status pertains to this class, the most recent setting for the most
2897      * specific pertinent package default assertion status is returned;
2898      * otherwise, this class loader's default assertion status is returned.
2899      * </p>
2900      *
2901      * @param  className
2902      *         The fully qualified class name of the class whose desired
2903      *         assertion status is being queried.
2904      *
2905      * @return  The desired assertion status of the specified class.
2906      *
2907      * @see  #setClassAssertionStatus(String, boolean)
2908      * @see  #setPackageAssertionStatus(String, boolean)
2909      * @see  #setDefaultAssertionStatus(boolean)
2910      *
2911      * @since  1.4
2912      */
2913     boolean desiredAssertionStatus(String className) {
2914         synchronized (assertionLock) {
2915             // assert classAssertionStatus   != null;
2916             // assert packageAssertionStatus != null;
2917 
2918             // Check for a class entry
2919             Boolean result = classAssertionStatus.get(className);
2920             if (result != null)
2921                 return result.booleanValue();
2922 
2923             // Check for most specific package entry
2924             int dotIndex = className.lastIndexOf('.');
2925             if (dotIndex < 0) { // default package
2926                 result = packageAssertionStatus.get(null);
2927                 if (result != null)
2928                     return result.booleanValue();
2929             }
2930             while(dotIndex > 0) {
2931                 className = className.substring(0, dotIndex);
2932                 result = packageAssertionStatus.get(className);
2933                 if (result != null)
2934                     return result.booleanValue();
2935                 dotIndex = className.lastIndexOf('.', dotIndex-1);
2936             }
2937 
2938             // Return the classloader default
2939             return defaultAssertionStatus;
2940         }
2941     }
2942 
2943     // Set up the assertions with information provided by the VM.
2944     // Note: Should only be called inside a synchronized block
2945     private void initializeJavaAssertionMaps() {
2946         // assert Thread.holdsLock(assertionLock);
2947 
2948         classAssertionStatus = new HashMap<>();
2949         packageAssertionStatus = new HashMap<>();
2950         AssertionStatusDirectives directives = retrieveDirectives();
2951 
2952         for(int i = 0; i < directives.classes.length; i++)
2953             classAssertionStatus.put(directives.classes[i],
2954                                      directives.classEnabled[i]);
2955 
2956         for(int i = 0; i < directives.packages.length; i++)
2957             packageAssertionStatus.put(directives.packages[i],
2958                                        directives.packageEnabled[i]);
2959 
2960         defaultAssertionStatus = directives.deflt;
2961     }
2962 
2963     // Retrieves the assertion directives from the VM.
2964     private static native AssertionStatusDirectives retrieveDirectives();
2965 
2966 
2967     // -- Misc --
2968 
2969     /**
2970      * Returns the ConcurrentHashMap used as a storage for ClassLoaderValue(s)
2971      * associated with this ClassLoader, creating it if it doesn't already exist.
2972      */
2973     ConcurrentHashMap<?, ?> createOrGetClassLoaderValueMap() {
2974         ConcurrentHashMap<?, ?> map = classLoaderValueMap;
2975         if (map == null) {
2976             map = new ConcurrentHashMap<>();
2977             boolean set = trySetObjectField("classLoaderValueMap", map);
2978             if (!set) {
2979                 // beaten by someone else
2980                 map = classLoaderValueMap;
2981             }
2982         }
2983         return map;
2984     }
2985 
2986     // the storage for ClassLoaderValue(s) associated with this ClassLoader
2987     private volatile ConcurrentHashMap<?, ?> classLoaderValueMap;
2988 
2989     /**
2990      * Attempts to atomically set a volatile field in this object. Returns
2991      * {@code true} if not beaten by another thread. Avoids the use of
2992      * AtomicReferenceFieldUpdater in this class.
2993      */
2994     private boolean trySetObjectField(String name, Object obj) {
2995         Unsafe unsafe = Unsafe.getUnsafe();
2996         Class<?> k = ClassLoader.class;
2997         long offset;
2998         offset = unsafe.objectFieldOffset(k, name);
2999         return unsafe.compareAndSetObject(this, offset, null, obj);
3000     }
3001 }
3002 
3003 /*
3004  * A utility class that will enumerate over an array of enumerations.
3005  */
3006 final class CompoundEnumeration<E> implements Enumeration<E> {
3007     private final Enumeration<E>[] enums;
3008     private int index;
3009 
3010     public CompoundEnumeration(Enumeration<E>[] enums) {
3011         this.enums = enums;
3012     }
3013 
3014     private boolean next() {
3015         while (index < enums.length) {
3016             if (enums[index] != null && enums[index].hasMoreElements()) {
3017                 return true;
3018             }
3019             index++;
3020         }
3021         return false;
3022     }
3023 
3024     public boolean hasMoreElements() {
3025         return next();
3026     }
3027 
3028     public E nextElement() {
3029         if (!next()) {
3030             throw new NoSuchElementException();
3031         }
3032         return enums[index].nextElement();
3033     }
3034 }
--- EOF ---