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