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