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