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