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