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