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