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