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