1 /*
   2  * Copyright (c) 2013, 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 package java.lang;
  26 
  27 import java.io.InputStream;
  28 import java.io.IOException;
  29 import java.io.File;
  30 import java.lang.reflect.Constructor;
  31 import java.lang.reflect.InvocationTargetException;
  32 import java.net.URL;
  33 import java.security.AccessController;
  34 import java.security.AccessControlContext;
  35 import java.security.CodeSource;
  36 import java.security.PrivilegedAction;
  37 import java.security.PrivilegedActionException;
  38 import java.security.PrivilegedExceptionAction;
  39 import java.security.ProtectionDomain;
  40 import java.security.cert.Certificate;
  41 import java.util.Collections;
  42 import java.util.Enumeration;
  43 import java.util.HashMap;
  44 import java.util.HashSet;
  45 import java.util.Set;
  46 import java.util.Stack;
  47 import java.util.Map;
  48 import java.util.Vector;
  49 import java.util.Hashtable;
  50 import java.util.WeakHashMap;
  51 import java.util.concurrent.ConcurrentHashMap;
  52 import sun.misc.CompoundEnumeration;
  53 import sun.misc.Resource;
  54 import sun.misc.URLClassPath;
  55 import sun.reflect.CallerSensitive;
  56 import sun.reflect.Reflection;
  57 import sun.reflect.misc.ReflectUtil;
  58 import sun.security.util.SecurityConstants;
  59 
  60 /**
  61  * A class loader is an object that is responsible for loading classes. The
  62  * class <tt>ClassLoader</tt> is an abstract class.  Given the <a
  63  * href="#name">binary name</a> of a class, a class loader should attempt to
  64  * locate or generate data that constitutes a definition for the class.  A
  65  * typical strategy is to transform the name into a file name and then read a
  66  * "class file" of that name from a file system.
  67  *
  68  * <p> Every {@link Class <tt>Class</tt>} object contains a {@link
  69  * Class#getClassLoader() reference} to the <tt>ClassLoader</tt> that defined
  70  * it.
  71  *
  72  * <p> <tt>Class</tt> objects for array classes are not created by class
  73  * loaders, but are created automatically as required by the Java runtime.
  74  * The class loader for an array class, as returned by {@link
  75  * Class#getClassLoader()} is the same as the class loader for its element
  76  * type; if the element type is a primitive type, then the array class has no
  77  * class loader.
  78  *
  79  * <p> Applications implement subclasses of <tt>ClassLoader</tt> in order to
  80  * extend the manner in which the Java virtual machine dynamically loads
  81  * classes.
  82  *
  83  * <p> Class loaders may typically be used by security managers to indicate
  84  * security domains.
  85  *
  86  * <p> The <tt>ClassLoader</tt> class uses a delegation model to search for
  87  * classes and resources.  Each instance of <tt>ClassLoader</tt> has an
  88  * associated parent class loader.  When requested to find a class or
  89  * resource, a <tt>ClassLoader</tt> instance will delegate the search for the
  90  * class or resource to its parent class loader before attempting to find the
  91  * class or resource itself.  The virtual machine's built-in class loader,
  92  * called the "bootstrap class loader", does not itself have a parent but may
  93  * serve as the parent of a <tt>ClassLoader</tt> instance.
  94  *
  95  * <p> Class loaders that support concurrent loading of classes are known as
  96  * <em>parallel capable</em> class loaders and are required to register
  97  * themselves at their class initialization time by invoking the
  98  * {@link
  99  * #registerAsParallelCapable <tt>ClassLoader.registerAsParallelCapable</tt>}
 100  * method. Note that the <tt>ClassLoader</tt> class is registered as parallel
 101  * capable by default. However, its subclasses still need to register themselves
 102  * if they are parallel capable. <br>
 103  * In environments in which the delegation model is not strictly
 104  * hierarchical, class loaders need to be parallel capable, otherwise class
 105  * loading can lead to deadlocks because the loader lock is held for the
 106  * duration of the class loading process (see {@link #loadClass
 107  * <tt>loadClass</tt>} methods).
 108  *
 109  * <p> Normally, the Java virtual machine loads classes from the local file
 110  * system in a platform-dependent manner.  For example, on UNIX systems, the
 111  * virtual machine loads classes from the directory defined by the
 112  * <tt>CLASSPATH</tt> environment variable.
 113  *
 114  * <p> However, some classes may not originate from a file; they may originate
 115  * from other sources, such as the network, or they could be constructed by an
 116  * application.  The method {@link #defineClass(String, byte[], int, int)
 117  * <tt>defineClass</tt>} converts an array of bytes into an instance of class
 118  * <tt>Class</tt>. Instances of this newly defined class can be created using
 119  * {@link Class#newInstance <tt>Class.newInstance</tt>}.
 120  *
 121  * <p> The methods and constructors of objects created by a class loader may
 122  * reference other classes.  To determine the class(es) referred to, the Java
 123  * virtual machine invokes the {@link #loadClass <tt>loadClass</tt>} method of
 124  * the class loader that originally created the class.
 125  *
 126  * <p> For example, an application could create a network class loader to
 127  * download class files from a server.  Sample code might look like:
 128  *
 129  * <blockquote><pre>
 130  *   ClassLoader loader&nbsp;= new NetworkClassLoader(host,&nbsp;port);
 131  *   Object main&nbsp;= loader.loadClass("Main", true).newInstance();
 132  *       &nbsp;.&nbsp;.&nbsp;.
 133  * </pre></blockquote>
 134  *
 135  * <p> The network class loader subclass must define the methods {@link
 136  * #findClass <tt>findClass</tt>} and <tt>loadClassData</tt> to load a class
 137  * from the network.  Once it has downloaded the bytes that make up the class,
 138  * it should use the method {@link #defineClass <tt>defineClass</tt>} to
 139  * create a class instance.  A sample implementation is:
 140  *
 141  * <blockquote><pre>
 142  *     class NetworkClassLoader extends ClassLoader {
 143  *         String host;
 144  *         int port;
 145  *
 146  *         public Class findClass(String name) {
 147  *             byte[] b = loadClassData(name);
 148  *             return defineClass(name, b, 0, b.length);
 149  *         }
 150  *
 151  *         private byte[] loadClassData(String name) {
 152  *             // load the class data from the connection
 153  *             &nbsp;.&nbsp;.&nbsp;.
 154  *         }
 155  *     }
 156  * </pre></blockquote>
 157  *
 158  * <h3> <a name="name">Binary names</a> </h3>
 159  *
 160  * <p> Any class name provided as a {@link String} parameter to methods in
 161  * <tt>ClassLoader</tt> must be a binary name as defined by
 162  * <cite>The Java&trade; Language Specification</cite>.
 163  *
 164  * <p> Examples of valid class names include:
 165  * <blockquote><pre>
 166  *   "java.lang.String"
 167  *   "javax.swing.JSpinner$DefaultEditor"
 168  *   "java.security.KeyStore$Builder$FileBuilder$1"
 169  *   "java.net.URLClassLoader$3$1"
 170  * </pre></blockquote>
 171  *
 172  * {@code Class} objects for array classes are not created by {@code ClassLoader};
 173  * use the {@link Class#forName} method instead.
 174  *
 175  * @jls 13.1 The Form of a Binary
 176  * @see      #resolveClass(Class)
 177  * @since 1.0
 178  */
 179 public abstract class ClassLoader {
 180 
 181     private static native void registerNatives();
 182     static {
 183         registerNatives();
 184     }
 185 
 186     // The parent class loader for delegation
 187     // Note: VM hardcoded the offset of this field, thus all new fields
 188     // must be added *after* it.
 189     private final ClassLoader parent;
 190 
 191     /**
 192      * Encapsulates the set of parallel capable loader types.
 193      */
 194     private static class ParallelLoaders {
 195         private ParallelLoaders() {}
 196 
 197         // the set of parallel capable loader types
 198         private static final Set<Class<? extends ClassLoader>> loaderTypes =
 199             Collections.newSetFromMap(new WeakHashMap<>());
 200         static {
 201             synchronized (loaderTypes) { loaderTypes.add(ClassLoader.class); }
 202         }
 203 
 204         /**
 205          * Registers the given class loader type as parallel capable.
 206          * Returns {@code true} is successfully registered; {@code false} if
 207          * loader's super class is not registered.
 208          */
 209         static boolean register(Class<? extends ClassLoader> c) {
 210             synchronized (loaderTypes) {
 211                 if (loaderTypes.contains(c.getSuperclass())) {
 212                     // register the class loader as parallel capable
 213                     // if and only if all of its super classes are.
 214                     // Note: given current classloading sequence, if
 215                     // the immediate super class is parallel capable,
 216                     // all the super classes higher up must be too.
 217                     loaderTypes.add(c);
 218                     return true;
 219                 } else {
 220                     return false;
 221                 }
 222             }
 223         }
 224 
 225         /**
 226          * Returns {@code true} if the given class loader type is
 227          * registered as parallel capable.
 228          */
 229         static boolean isRegistered(Class<? extends ClassLoader> c) {
 230             synchronized (loaderTypes) {
 231                 return loaderTypes.contains(c);
 232             }
 233         }
 234     }
 235 
 236     // Maps class name to the corresponding lock object when the current
 237     // class loader is parallel capable.
 238     // Note: VM also uses this field to decide if the current class loader
 239     // is parallel capable and the appropriate lock object for class loading.
 240     private final ConcurrentHashMap<String, Object> parallelLockMap;
 241 
 242     // Hashtable that maps packages to certs
 243     private final Map <String, Certificate[]> package2certs;
 244 
 245     // Shared among all packages with unsigned classes
 246     private static final Certificate[] nocerts = new Certificate[0];
 247 
 248     // The classes loaded by this class loader. The only purpose of this table
 249     // is to keep the classes from being GC'ed until the loader is GC'ed.
 250     private final Vector<Class<?>> classes = new Vector<>();
 251 
 252     // The "default" domain. Set as the default ProtectionDomain on newly
 253     // created classes.
 254     private final ProtectionDomain defaultDomain =
 255         new ProtectionDomain(new CodeSource(null, (Certificate[]) null),
 256                              null, this, null);
 257 
 258     // The initiating protection domains for all classes loaded by this loader
 259     private final Set<ProtectionDomain> domains;
 260 
 261     // Invoked by the VM to record every loaded class with this loader.
 262     void addClass(Class<?> c) {
 263         classes.addElement(c);
 264     }
 265 
 266     // The packages defined in this class loader.  Each package name is mapped
 267     // to its corresponding Package object.
 268     // @GuardedBy("itself")
 269     private final ConcurrentHashMap<String, Package> packages
 270             = new ConcurrentHashMap<>();
 271 
 272     private static Void checkCreateClassLoader() {
 273         SecurityManager security = System.getSecurityManager();
 274         if (security != null) {
 275             security.checkCreateClassLoader();
 276         }
 277         return null;
 278     }
 279 
 280     private ClassLoader(Void unused, ClassLoader parent) {
 281         this.parent = parent;
 282         if (ParallelLoaders.isRegistered(this.getClass())) {
 283             parallelLockMap = new ConcurrentHashMap<>();
 284             package2certs = new ConcurrentHashMap<>();
 285             domains = Collections.synchronizedSet(new HashSet<>());
 286             assertionLock = new Object();
 287         } else {
 288             // no finer-grained lock; lock on the classloader instance
 289             parallelLockMap = null;
 290             package2certs = new Hashtable<>();
 291             domains = new HashSet<>();
 292             assertionLock = this;
 293         }
 294     }
 295 
 296     /**
 297      * Creates a new class loader using the specified parent class loader for
 298      * delegation.
 299      *
 300      * <p> If there is a security manager, its {@link
 301      * SecurityManager#checkCreateClassLoader()
 302      * <tt>checkCreateClassLoader</tt>} method is invoked.  This may result in
 303      * a security exception.  </p>
 304      *
 305      * @param  parent
 306      *         The parent class loader
 307      *
 308      * @throws  SecurityException
 309      *          If a security manager exists and its
 310      *          <tt>checkCreateClassLoader</tt> method doesn't allow creation
 311      *          of a new class loader.
 312      *
 313      * @since  1.2
 314      */
 315     protected ClassLoader(ClassLoader parent) {
 316         this(checkCreateClassLoader(), parent);
 317     }
 318 
 319     /**
 320      * Creates a new class loader using the <tt>ClassLoader</tt> returned by
 321      * the method {@link #getSystemClassLoader()
 322      * <tt>getSystemClassLoader()</tt>} as the parent class loader.
 323      *
 324      * <p> If there is a security manager, its {@link
 325      * SecurityManager#checkCreateClassLoader()
 326      * <tt>checkCreateClassLoader</tt>} method is invoked.  This may result in
 327      * a security exception.  </p>
 328      *
 329      * @throws  SecurityException
 330      *          If a security manager exists and its
 331      *          <tt>checkCreateClassLoader</tt> method doesn't allow creation
 332      *          of a new class loader.
 333      */
 334     protected ClassLoader() {
 335         this(checkCreateClassLoader(), getSystemClassLoader());
 336     }
 337 
 338     // -- Class --
 339 
 340     /**
 341      * Loads the class with the specified <a href="#name">binary name</a>.
 342      * This method searches for classes in the same manner as the {@link
 343      * #loadClass(String, boolean)} method.  It is invoked by the Java virtual
 344      * machine to resolve class references.  Invoking this method is equivalent
 345      * to invoking {@link #loadClass(String, boolean) <tt>loadClass(name,
 346      * false)</tt>}.
 347      *
 348      * @param  name
 349      *         The <a href="#name">binary name</a> of the class
 350      *
 351      * @return  The resulting <tt>Class</tt> object
 352      *
 353      * @throws  ClassNotFoundException
 354      *          If the class was not found
 355      */
 356     public Class<?> loadClass(String name) throws ClassNotFoundException {
 357         return loadClass(name, false);
 358     }
 359 
 360     /**
 361      * Loads the class with the specified <a href="#name">binary name</a>.  The
 362      * default implementation of this method searches for classes in the
 363      * following order:
 364      *
 365      * <ol>
 366      *
 367      *   <li><p> Invoke {@link #findLoadedClass(String)} to check if the class
 368      *   has already been loaded.  </p></li>
 369      *
 370      *   <li><p> Invoke the {@link #loadClass(String) <tt>loadClass</tt>} method
 371      *   on the parent class loader.  If the parent is <tt>null</tt> the class
 372      *   loader built-in to the virtual machine is used, instead.  </p></li>
 373      *
 374      *   <li><p> Invoke the {@link #findClass(String)} method to find the
 375      *   class.  </p></li>
 376      *
 377      * </ol>
 378      *
 379      * <p> If the class was found using the above steps, and the
 380      * <tt>resolve</tt> flag is true, this method will then invoke the {@link
 381      * #resolveClass(Class)} method on the resulting <tt>Class</tt> object.
 382      *
 383      * <p> Subclasses of <tt>ClassLoader</tt> are encouraged to override {@link
 384      * #findClass(String)}, rather than this method.  </p>
 385      *
 386      * <p> Unless overridden, this method synchronizes on the result of
 387      * {@link #getClassLoadingLock <tt>getClassLoadingLock</tt>} method
 388      * during the entire class loading process.
 389      *
 390      * @param  name
 391      *         The <a href="#name">binary name</a> of the class
 392      *
 393      * @param  resolve
 394      *         If <tt>true</tt> then resolve the class
 395      *
 396      * @return  The resulting <tt>Class</tt> object
 397      *
 398      * @throws  ClassNotFoundException
 399      *          If the class could not be found
 400      */
 401     protected Class<?> loadClass(String name, boolean resolve)
 402         throws ClassNotFoundException
 403     {
 404         synchronized (getClassLoadingLock(name)) {
 405             // First, check if the class has already been loaded
 406             Class<?> c = findLoadedClass(name);
 407             if (c == null) {
 408                 long t0 = System.nanoTime();
 409                 try {
 410                     if (parent != null) {
 411                         c = parent.loadClass(name, false);
 412                     } else {
 413                         c = findBootstrapClassOrNull(name);
 414                     }
 415                 } catch (ClassNotFoundException e) {
 416                     // ClassNotFoundException thrown if class not found
 417                     // from the non-null parent class loader
 418                 }
 419 
 420                 if (c == null) {
 421                     // If still not found, then invoke findClass in order
 422                     // to find the class.
 423                     long t1 = System.nanoTime();
 424                     c = findClass(name);
 425 
 426                     // this is the defining class loader; record the stats
 427                     sun.misc.PerfCounter.getParentDelegationTime().addTime(t1 - t0);
 428                     sun.misc.PerfCounter.getFindClassTime().addElapsedTimeFrom(t1);
 429                     sun.misc.PerfCounter.getFindClasses().increment();
 430                 }
 431             }
 432             if (resolve) {
 433                 resolveClass(c);
 434             }
 435             return c;
 436         }
 437     }
 438 
 439     /**
 440      * Returns the lock object for class loading operations.
 441      * For backward compatibility, the default implementation of this method
 442      * behaves as follows. If this ClassLoader object is registered as
 443      * parallel capable, the method returns a dedicated object associated
 444      * with the specified class name. Otherwise, the method returns this
 445      * ClassLoader object.
 446      *
 447      * @param  className
 448      *         The name of the to-be-loaded class
 449      *
 450      * @return the lock for class loading operations
 451      *
 452      * @throws NullPointerException
 453      *         If registered as parallel capable and <tt>className</tt> is null
 454      *
 455      * @see #loadClass(String, boolean)
 456      *
 457      * @since  1.7
 458      */
 459     protected Object getClassLoadingLock(String className) {
 460         Object lock = this;
 461         if (parallelLockMap != null) {
 462             Object newLock = new Object();
 463             lock = parallelLockMap.putIfAbsent(className, newLock);
 464             if (lock == null) {
 465                 lock = newLock;
 466             }
 467         }
 468         return lock;
 469     }
 470 
 471     // This method is invoked by the virtual machine to load a class.
 472     private Class<?> loadClassInternal(String name)
 473         throws ClassNotFoundException
 474     {
 475         // For backward compatibility, explicitly lock on 'this' when
 476         // the current class loader is not parallel capable.
 477         if (parallelLockMap == null) {
 478             synchronized (this) {
 479                  return loadClass(name);
 480             }
 481         } else {
 482             return loadClass(name);
 483         }
 484     }
 485 
 486     // Invoked by the VM after loading class with this loader.
 487     private void checkPackageAccess(Class<?> cls, ProtectionDomain pd) {
 488         final SecurityManager sm = System.getSecurityManager();
 489         if (sm != null) {
 490             if (ReflectUtil.isNonPublicProxyClass(cls)) {
 491                 for (Class<?> intf: cls.getInterfaces()) {
 492                     checkPackageAccess(intf, pd);
 493                 }
 494                 return;
 495             }
 496 
 497             final String name = cls.getName();
 498             final int i = name.lastIndexOf('.');
 499             if (i != -1) {
 500                 AccessController.doPrivileged(new PrivilegedAction<Void>() {
 501                     public Void run() {
 502                         sm.checkPackageAccess(name.substring(0, i));
 503                         return null;
 504                     }
 505                 }, new AccessControlContext(new ProtectionDomain[] {pd}));
 506             }
 507         }
 508         domains.add(pd);
 509     }
 510 
 511     /**
 512      * Finds the class with the specified <a href="#name">binary name</a>.
 513      * This method should be overridden by class loader implementations that
 514      * follow the delegation model for loading classes, and will be invoked by
 515      * the {@link #loadClass <tt>loadClass</tt>} method after checking the
 516      * parent class loader for the requested class.  The default implementation
 517      * throws a <tt>ClassNotFoundException</tt>.
 518      *
 519      * @param  name
 520      *         The <a href="#name">binary name</a> of the class
 521      *
 522      * @return  The resulting <tt>Class</tt> object
 523      *
 524      * @throws  ClassNotFoundException
 525      *          If the class could not be found
 526      *
 527      * @since  1.2
 528      */
 529     protected Class<?> findClass(String name) throws ClassNotFoundException {
 530         throw new ClassNotFoundException(name);
 531     }
 532 
 533     /**
 534      * Converts an array of bytes into an instance of class <tt>Class</tt>.
 535      * Before the <tt>Class</tt> can be used it must be resolved.  This method
 536      * is deprecated in favor of the version that takes a <a
 537      * href="#name">binary name</a> as its first argument, and is more secure.
 538      *
 539      * @param  b
 540      *         The bytes that make up the class data.  The bytes in positions
 541      *         <tt>off</tt> through <tt>off+len-1</tt> should have the format
 542      *         of a valid class file as defined by
 543      *         <cite>The Java&trade; Virtual Machine Specification</cite>.
 544      *
 545      * @param  off
 546      *         The start offset in <tt>b</tt> of the class data
 547      *
 548      * @param  len
 549      *         The length of the class data
 550      *
 551      * @return  The <tt>Class</tt> object that was created from the specified
 552      *          class data
 553      *
 554      * @throws  ClassFormatError
 555      *          If the data did not contain a valid class
 556      *
 557      * @throws  IndexOutOfBoundsException
 558      *          If either <tt>off</tt> or <tt>len</tt> is negative, or if
 559      *          <tt>off+len</tt> is greater than <tt>b.length</tt>.
 560      *
 561      * @throws  SecurityException
 562      *          If an attempt is made to add this class to a package that
 563      *          contains classes that were signed by a different set of
 564      *          certificates than this class, or if an attempt is made
 565      *          to define a class in a package with a fully-qualified name
 566      *          that starts with "{@code java.}".
 567      *
 568      * @see  #loadClass(String, boolean)
 569      * @see  #resolveClass(Class)
 570      *
 571      * @deprecated  Replaced by {@link #defineClass(String, byte[], int, int)
 572      * defineClass(String, byte[], int, int)}
 573      */
 574     @Deprecated
 575     protected final Class<?> defineClass(byte[] b, int off, int len)
 576         throws ClassFormatError
 577     {
 578         return defineClass(null, b, off, len, null);
 579     }
 580 
 581     /**
 582      * Converts an array of bytes into an instance of class <tt>Class</tt>.
 583      * Before the <tt>Class</tt> can be used it must be resolved.
 584      *
 585      * <p> This method assigns a default {@link java.security.ProtectionDomain
 586      * <tt>ProtectionDomain</tt>} to the newly defined class.  The
 587      * <tt>ProtectionDomain</tt> is effectively granted the same set of
 588      * permissions returned when {@link
 589      * java.security.Policy#getPermissions(java.security.CodeSource)
 590      * <tt>Policy.getPolicy().getPermissions(new CodeSource(null, null))</tt>}
 591      * is invoked.  The default domain is created on the first invocation of
 592      * {@link #defineClass(String, byte[], int, int) <tt>defineClass</tt>},
 593      * and re-used on subsequent invocations.
 594      *
 595      * <p> To assign a specific <tt>ProtectionDomain</tt> to the class, use
 596      * the {@link #defineClass(String, byte[], int, int,
 597      * java.security.ProtectionDomain) <tt>defineClass</tt>} method that takes a
 598      * <tt>ProtectionDomain</tt> as one of its arguments.  </p>
 599      *
 600      * @param  name
 601      *         The expected <a href="#name">binary name</a> of the class, or
 602      *         <tt>null</tt> if not known
 603      *
 604      * @param  b
 605      *         The bytes that make up the class data.  The bytes in positions
 606      *         <tt>off</tt> through <tt>off+len-1</tt> should have the format
 607      *         of a valid class file as defined by
 608      *         <cite>The Java&trade; Virtual Machine Specification</cite>.
 609      *
 610      * @param  off
 611      *         The start offset in <tt>b</tt> of the class data
 612      *
 613      * @param  len
 614      *         The length of the class data
 615      *
 616      * @return  The <tt>Class</tt> object that was created from the specified
 617      *          class data.
 618      *
 619      * @throws  ClassFormatError
 620      *          If the data did not contain a valid class
 621      *
 622      * @throws  IndexOutOfBoundsException
 623      *          If either <tt>off</tt> or <tt>len</tt> is negative, or if
 624      *          <tt>off+len</tt> is greater than <tt>b.length</tt>.
 625      *
 626      * @throws  SecurityException
 627      *          If an attempt is made to add this class to a package that
 628      *          contains classes that were signed by a different set of
 629      *          certificates than this class (which is unsigned), or if
 630      *          <tt>name</tt> begins with "<tt>java.</tt>".
 631      *
 632      * @see  #loadClass(String, boolean)
 633      * @see  #resolveClass(Class)
 634      * @see  java.security.CodeSource
 635      * @see  java.security.SecureClassLoader
 636      *
 637      * @since  1.1
 638      */
 639     protected final Class<?> defineClass(String name, byte[] b, int off, int len)
 640         throws ClassFormatError
 641     {
 642         return defineClass(name, b, off, len, null);
 643     }
 644 
 645     /* Determine protection domain, and check that:
 646         - not define java.* class,
 647         - signer of this class matches signers for the rest of the classes in
 648           package.
 649     */
 650     private ProtectionDomain preDefineClass(String name,
 651                                             ProtectionDomain pd)
 652     {
 653         if (!checkName(name))
 654             throw new NoClassDefFoundError("IllegalName: " + name);
 655 
 656         if ((name != null) && name.startsWith("java.")) {
 657             throw new SecurityException
 658                 ("Prohibited package name: " +
 659                  name.substring(0, name.lastIndexOf('.')));
 660         }
 661         if (pd == null) {
 662             pd = defaultDomain;
 663         }
 664 
 665         if (name != null) checkCerts(name, pd.getCodeSource());
 666 
 667         return pd;
 668     }
 669 
 670     private String defineClassSourceLocation(ProtectionDomain pd)
 671     {
 672         CodeSource cs = pd.getCodeSource();
 673         String source = null;
 674         if (cs != null && cs.getLocation() != null) {
 675             source = cs.getLocation().toString();
 676         }
 677         return source;
 678     }
 679 
 680     private void postDefineClass(Class<?> c, ProtectionDomain pd)
 681     {
 682         if (pd.getCodeSource() != null) {
 683             Certificate certs[] = pd.getCodeSource().getCertificates();
 684             if (certs != null)
 685                 setSigners(c, certs);
 686         }
 687     }
 688 
 689     /**
 690      * Converts an array of bytes into an instance of class <tt>Class</tt>,
 691      * with an optional <tt>ProtectionDomain</tt>.  If the domain is
 692      * <tt>null</tt>, then a default domain will be assigned to the class as
 693      * specified in the documentation for {@link #defineClass(String, byte[],
 694      * int, int)}.  Before the class can be used it must be resolved.
 695      *
 696      * <p> The first class defined in a package determines the exact set of
 697      * certificates that all subsequent classes defined in that package must
 698      * contain.  The set of certificates for a class is obtained from the
 699      * {@link java.security.CodeSource <tt>CodeSource</tt>} within the
 700      * <tt>ProtectionDomain</tt> of the class.  Any classes added to that
 701      * package must contain the same set of certificates or a
 702      * <tt>SecurityException</tt> will be thrown.  Note that if
 703      * <tt>name</tt> is <tt>null</tt>, this check is not performed.
 704      * You should always pass in the <a href="#name">binary name</a> of the
 705      * class you are defining as well as the bytes.  This ensures that the
 706      * class you are defining is indeed the class you think it is.
 707      *
 708      * <p> The specified <tt>name</tt> cannot begin with "<tt>java.</tt>", since
 709      * all classes in the "<tt>java.*</tt> packages can only be defined by the
 710      * bootstrap class loader.  If <tt>name</tt> is not <tt>null</tt>, it
 711      * must be equal to the <a href="#name">binary name</a> of the class
 712      * specified by the byte array "<tt>b</tt>", otherwise a {@link
 713      * NoClassDefFoundError <tt>NoClassDefFoundError</tt>} will be thrown. </p>
 714      *
 715      * @param  name
 716      *         The expected <a href="#name">binary name</a> of the class, or
 717      *         <tt>null</tt> if not known
 718      *
 719      * @param  b
 720      *         The bytes that make up the class data. The bytes in positions
 721      *         <tt>off</tt> through <tt>off+len-1</tt> should have the format
 722      *         of a valid class file as defined by
 723      *         <cite>The Java&trade; Virtual Machine Specification</cite>.
 724      *
 725      * @param  off
 726      *         The start offset in <tt>b</tt> of the class data
 727      *
 728      * @param  len
 729      *         The length of the class data
 730      *
 731      * @param  protectionDomain
 732      *         The ProtectionDomain of the class
 733      *
 734      * @return  The <tt>Class</tt> object created from the data,
 735      *          and optional <tt>ProtectionDomain</tt>.
 736      *
 737      * @throws  ClassFormatError
 738      *          If the data did not contain a valid class
 739      *
 740      * @throws  NoClassDefFoundError
 741      *          If <tt>name</tt> is not equal to the <a href="#name">binary
 742      *          name</a> of the class specified by <tt>b</tt>
 743      *
 744      * @throws  IndexOutOfBoundsException
 745      *          If either <tt>off</tt> or <tt>len</tt> is negative, or if
 746      *          <tt>off+len</tt> is greater than <tt>b.length</tt>.
 747      *
 748      * @throws  SecurityException
 749      *          If an attempt is made to add this class to a package that
 750      *          contains classes that were signed by a different set of
 751      *          certificates than this class, or if <tt>name</tt> begins with
 752      *          "<tt>java.</tt>".
 753      */
 754     protected final Class<?> defineClass(String name, byte[] b, int off, int len,
 755                                          ProtectionDomain protectionDomain)
 756         throws ClassFormatError
 757     {
 758         protectionDomain = preDefineClass(name, protectionDomain);
 759         String source = defineClassSourceLocation(protectionDomain);
 760         Class<?> c = defineClass1(name, b, off, len, protectionDomain, source);
 761         postDefineClass(c, protectionDomain);
 762         return c;
 763     }
 764 
 765     /**
 766      * Converts a {@link java.nio.ByteBuffer <tt>ByteBuffer</tt>}
 767      * into an instance of class <tt>Class</tt>,
 768      * with an optional <tt>ProtectionDomain</tt>.  If the domain is
 769      * <tt>null</tt>, then a default domain will be assigned to the class as
 770      * specified in the documentation for {@link #defineClass(String, byte[],
 771      * int, int)}.  Before the class can be used it must be resolved.
 772      *
 773      * <p>The rules about the first class defined in a package determining the
 774      * set of certificates for the package, and the restrictions on class names
 775      * are identical to those specified in the documentation for {@link
 776      * #defineClass(String, byte[], int, int, ProtectionDomain)}.
 777      *
 778      * <p> An invocation of this method of the form
 779      * <i>cl</i><tt>.defineClass(</tt><i>name</i><tt>,</tt>
 780      * <i>bBuffer</i><tt>,</tt> <i>pd</i><tt>)</tt> yields exactly the same
 781      * result as the statements
 782      *
 783      *<p> <tt>
 784      * ...<br>
 785      * byte[] temp = new byte[bBuffer.{@link
 786      * java.nio.ByteBuffer#remaining remaining}()];<br>
 787      *     bBuffer.{@link java.nio.ByteBuffer#get(byte[])
 788      * get}(temp);<br>
 789      *     return {@link #defineClass(String, byte[], int, int, ProtectionDomain)
 790      * cl.defineClass}(name, temp, 0,
 791      * temp.length, pd);<br>
 792      * </tt></p>
 793      *
 794      * @param  name
 795      *         The expected <a href="#name">binary name</a>. of the class, or
 796      *         <tt>null</tt> if not known
 797      *
 798      * @param  b
 799      *         The bytes that make up the class data. The bytes from positions
 800      *         <tt>b.position()</tt> through <tt>b.position() + b.limit() -1
 801      *         </tt> should have the format of a valid class file as defined by
 802      *         <cite>The Java&trade; Virtual Machine Specification</cite>.
 803      *
 804      * @param  protectionDomain
 805      *         The ProtectionDomain of the class, or <tt>null</tt>.
 806      *
 807      * @return  The <tt>Class</tt> object created from the data,
 808      *          and optional <tt>ProtectionDomain</tt>.
 809      *
 810      * @throws  ClassFormatError
 811      *          If the data did not contain a valid class.
 812      *
 813      * @throws  NoClassDefFoundError
 814      *          If <tt>name</tt> is not equal to the <a href="#name">binary
 815      *          name</a> of the class specified by <tt>b</tt>
 816      *
 817      * @throws  SecurityException
 818      *          If an attempt is made to add this class to a package that
 819      *          contains classes that were signed by a different set of
 820      *          certificates than this class, or if <tt>name</tt> begins with
 821      *          "<tt>java.</tt>".
 822      *
 823      * @see      #defineClass(String, byte[], int, int, ProtectionDomain)
 824      *
 825      * @since  1.5
 826      */
 827     protected final Class<?> defineClass(String name, java.nio.ByteBuffer b,
 828                                          ProtectionDomain protectionDomain)
 829         throws ClassFormatError
 830     {
 831         int len = b.remaining();
 832 
 833         // Use byte[] if not a direct ByteBuffer:
 834         if (!b.isDirect()) {
 835             if (b.hasArray()) {
 836                 return defineClass(name, b.array(),
 837                                    b.position() + b.arrayOffset(), len,
 838                                    protectionDomain);
 839             } else {
 840                 // no array, or read-only array
 841                 byte[] tb = new byte[len];
 842                 b.get(tb);  // get bytes out of byte buffer.
 843                 return defineClass(name, tb, 0, len, protectionDomain);
 844             }
 845         }
 846 
 847         protectionDomain = preDefineClass(name, protectionDomain);
 848         String source = defineClassSourceLocation(protectionDomain);
 849         Class<?> c = defineClass2(name, b, b.position(), len, protectionDomain, source);
 850         postDefineClass(c, protectionDomain);
 851         return c;
 852     }
 853 
 854     private native Class<?> defineClass1(String name, byte[] b, int off, int len,
 855                                          ProtectionDomain pd, String source);
 856 
 857     private native Class<?> defineClass2(String name, java.nio.ByteBuffer b,
 858                                          int off, int len, ProtectionDomain pd,
 859                                          String source);
 860 
 861     // true if the name is null or has the potential to be a valid binary name
 862     private boolean checkName(String name) {
 863         if ((name == null) || (name.length() == 0))
 864             return true;
 865         if ((name.indexOf('/') != -1) || (name.charAt(0) == '['))
 866             return false;
 867         return true;
 868     }
 869 
 870     private void checkCerts(String name, CodeSource cs) {
 871         int i = name.lastIndexOf('.');
 872         String pname = (i == -1) ? "" : name.substring(0, i);
 873 
 874         Certificate[] certs = null;
 875         if (cs != null) {
 876             certs = cs.getCertificates();
 877         }
 878         Certificate[] pcerts = null;
 879         if (parallelLockMap == null) {
 880             synchronized (this) {
 881                 pcerts = package2certs.get(pname);
 882                 if (pcerts == null) {
 883                     package2certs.put(pname, (certs == null? nocerts:certs));
 884                 }
 885             }
 886         } else {
 887             pcerts = ((ConcurrentHashMap<String, Certificate[]>)package2certs).
 888                 putIfAbsent(pname, (certs == null? nocerts:certs));
 889         }
 890         if (pcerts != null && !compareCerts(pcerts, certs)) {
 891             throw new SecurityException("class \""+ name +
 892                  "\"'s signer information does not match signer information of other classes in the same package");
 893         }
 894     }
 895 
 896     /**
 897      * check to make sure the certs for the new class (certs) are the same as
 898      * the certs for the first class inserted in the package (pcerts)
 899      */
 900     private boolean compareCerts(Certificate[] pcerts,
 901                                  Certificate[] certs)
 902     {
 903         // certs can be null, indicating no certs.
 904         if ((certs == null) || (certs.length == 0)) {
 905             return pcerts.length == 0;
 906         }
 907 
 908         // the length must be the same at this point
 909         if (certs.length != pcerts.length)
 910             return false;
 911 
 912         // go through and make sure all the certs in one array
 913         // are in the other and vice-versa.
 914         boolean match;
 915         for (Certificate cert : certs) {
 916             match = false;
 917             for (Certificate pcert : pcerts) {
 918                 if (cert.equals(pcert)) {
 919                     match = true;
 920                     break;
 921                 }
 922             }
 923             if (!match) return false;
 924         }
 925 
 926         // now do the same for pcerts
 927         for (Certificate pcert : pcerts) {
 928             match = false;
 929             for (Certificate cert : certs) {
 930                 if (pcert.equals(cert)) {
 931                     match = true;
 932                     break;
 933                 }
 934             }
 935             if (!match) return false;
 936         }
 937 
 938         return true;
 939     }
 940 
 941     /**
 942      * Links the specified class.  This (misleadingly named) method may be
 943      * used by a class loader to link a class.  If the class <tt>c</tt> has
 944      * already been linked, then this method simply returns. Otherwise, the
 945      * class is linked as described in the "Execution" chapter of
 946      * <cite>The Java&trade; Language Specification</cite>.
 947      *
 948      * @param  c
 949      *         The class to link
 950      *
 951      * @throws  NullPointerException
 952      *          If <tt>c</tt> is <tt>null</tt>.
 953      *
 954      * @see  #defineClass(String, byte[], int, int)
 955      */
 956     protected final void resolveClass(Class<?> c) {
 957         resolveClass0(c);
 958     }
 959 
 960     private native void resolveClass0(Class<?> c);
 961 
 962     /**
 963      * Finds a class with the specified <a href="#name">binary name</a>,
 964      * loading it if necessary.
 965      *
 966      * <p> This method loads the class through the system class loader (see
 967      * {@link #getSystemClassLoader()}).  The <tt>Class</tt> object returned
 968      * might have more than one <tt>ClassLoader</tt> associated with it.
 969      * Subclasses of <tt>ClassLoader</tt> need not usually invoke this method,
 970      * because most class loaders need to override just {@link
 971      * #findClass(String)}.  </p>
 972      *
 973      * @param  name
 974      *         The <a href="#name">binary name</a> of the class
 975      *
 976      * @return  The <tt>Class</tt> object for the specified <tt>name</tt>
 977      *
 978      * @throws  ClassNotFoundException
 979      *          If the class could not be found
 980      *
 981      * @see  #ClassLoader(ClassLoader)
 982      * @see  #getParent()
 983      */
 984     protected final Class<?> findSystemClass(String name)
 985         throws ClassNotFoundException
 986     {
 987         ClassLoader system = getSystemClassLoader();
 988         if (system == null) {
 989             if (!checkName(name))
 990                 throw new ClassNotFoundException(name);
 991             Class<?> cls = findBootstrapClass(name);
 992             if (cls == null) {
 993                 throw new ClassNotFoundException(name);
 994             }
 995             return cls;
 996         }
 997         return system.loadClass(name);
 998     }
 999 
1000     /**
1001      * Returns a class loaded by the bootstrap class loader;
1002      * or return null if not found.
1003      */
1004     private Class<?> findBootstrapClassOrNull(String name)
1005     {
1006         if (!checkName(name)) return null;
1007 
1008         return findBootstrapClass(name);
1009     }
1010 
1011     // return null if not found
1012     private native Class<?> findBootstrapClass(String name);
1013 
1014     /**
1015      * Returns the class with the given <a href="#name">binary name</a> if this
1016      * loader has been recorded by the Java virtual machine as an initiating
1017      * loader of a class with that <a href="#name">binary name</a>.  Otherwise
1018      * <tt>null</tt> is returned.
1019      *
1020      * @param  name
1021      *         The <a href="#name">binary name</a> of the class
1022      *
1023      * @return  The <tt>Class</tt> object, or <tt>null</tt> if the class has
1024      *          not been loaded
1025      *
1026      * @since  1.1
1027      */
1028     protected final Class<?> findLoadedClass(String name) {
1029         if (!checkName(name))
1030             return null;
1031         return findLoadedClass0(name);
1032     }
1033 
1034     private native final Class<?> findLoadedClass0(String name);
1035 
1036     /**
1037      * Sets the signers of a class.  This should be invoked after defining a
1038      * class.
1039      *
1040      * @param  c
1041      *         The <tt>Class</tt> object
1042      *
1043      * @param  signers
1044      *         The signers for the class
1045      *
1046      * @since  1.1
1047      */
1048     protected final void setSigners(Class<?> c, Object[] signers) {
1049         c.setSigners(signers);
1050     }
1051 
1052 
1053     // -- Resource --
1054 
1055     /**
1056      * Finds the resource with the given name.  A resource is some data
1057      * (images, audio, text, etc) that can be accessed by class code in a way
1058      * that is independent of the location of the code.
1059      *
1060      * <p> The name of a resource is a '<tt>/</tt>'-separated path name that
1061      * identifies the resource.
1062      *
1063      * <p> This method will first search the parent class loader for the
1064      * resource; if the parent is <tt>null</tt> the path of the class loader
1065      * built-in to the virtual machine is searched.  That failing, this method
1066      * will invoke {@link #findResource(String)} to find the resource.  </p>
1067      *
1068      * @apiNote When overriding this method it is recommended that an
1069      * implementation ensures that any delegation is consistent with the {@link
1070      * #getResources(java.lang.String) getResources(String)} method.
1071      *
1072      * @param  name
1073      *         The resource name
1074      *
1075      * @return  A <tt>URL</tt> object for reading the resource, or
1076      *          <tt>null</tt> if the resource could not be found or the invoker
1077      *          doesn't have adequate  privileges to get the resource.
1078      *
1079      * @since  1.1
1080      */
1081     public URL getResource(String name) {
1082         URL url;
1083         if (parent != null) {
1084             url = parent.getResource(name);
1085         } else {
1086             url = getBootstrapResource(name);
1087         }
1088         if (url == null) {
1089             url = findResource(name);
1090         }
1091         return url;
1092     }
1093 
1094     /**
1095      * Finds all the resources with the given name. A resource is some data
1096      * (images, audio, text, etc) that can be accessed by class code in a way
1097      * that is independent of the location of the code.
1098      *
1099      * <p>The name of a resource is a <tt>/</tt>-separated path name that
1100      * identifies the resource.
1101      *
1102      * <p> The search order is described in the documentation for {@link
1103      * #getResource(String)}.  </p>
1104      *
1105      * @apiNote When overriding this method it is recommended that an
1106      * implementation ensures that any delegation is consistent with the {@link
1107      * #getResource(java.lang.String) getResource(String)} method. This should
1108      * ensure that the first element returned by the Enumeration's
1109      * {@code nextElement} method is the same resource that the
1110      * {@code getResource(String)} method would return.
1111      *
1112      * @param  name
1113      *         The resource name
1114      *
1115      * @return  An enumeration of {@link java.net.URL <tt>URL</tt>} objects for
1116      *          the resource.  If no resources could  be found, the enumeration
1117      *          will be empty.  Resources that the class loader doesn't have
1118      *          access to will not be in the enumeration.
1119      *
1120      * @throws  IOException
1121      *          If I/O errors occur
1122      *
1123      * @see  #findResources(String)
1124      *
1125      * @since  1.2
1126      */
1127     public Enumeration<URL> getResources(String name) throws IOException {
1128         @SuppressWarnings("unchecked")
1129         Enumeration<URL>[] tmp = (Enumeration<URL>[]) new Enumeration<?>[2];
1130         if (parent != null) {
1131             tmp[0] = parent.getResources(name);
1132         } else {
1133             tmp[0] = getBootstrapResources(name);
1134         }
1135         tmp[1] = findResources(name);
1136 
1137         return new CompoundEnumeration<>(tmp);
1138     }
1139 
1140     /**
1141      * Finds the resource with the given name. Class loader implementations
1142      * should override this method to specify where to find resources.
1143      *
1144      * @param  name
1145      *         The resource name
1146      *
1147      * @return  A <tt>URL</tt> object for reading the resource, or
1148      *          <tt>null</tt> if the resource could not be found
1149      *
1150      * @since  1.2
1151      */
1152     protected URL findResource(String name) {
1153         return null;
1154     }
1155 
1156     /**
1157      * Returns an enumeration of {@link java.net.URL <tt>URL</tt>} objects
1158      * representing all the resources with the given name. Class loader
1159      * implementations should override this method to specify where to load
1160      * resources from.
1161      *
1162      * @param  name
1163      *         The resource name
1164      *
1165      * @return  An enumeration of {@link java.net.URL <tt>URL</tt>} objects for
1166      *          the resources
1167      *
1168      * @throws  IOException
1169      *          If I/O errors occur
1170      *
1171      * @since  1.2
1172      */
1173     protected Enumeration<URL> findResources(String name) throws IOException {
1174         return java.util.Collections.emptyEnumeration();
1175     }
1176 
1177     /**
1178      * Registers the caller as parallel capable.
1179      * The registration succeeds if and only if all of the following
1180      * conditions are met:
1181      * <ol>
1182      * <li> no instance of the caller has been created</li>
1183      * <li> all of the super classes (except class Object) of the caller are
1184      * registered as parallel capable</li>
1185      * </ol>
1186      * <p>Note that once a class loader is registered as parallel capable, there
1187      * is no way to change it back.</p>
1188      *
1189      * @return  true if the caller is successfully registered as
1190      *          parallel capable and false if otherwise.
1191      *
1192      * @since   1.7
1193      */
1194     @CallerSensitive
1195     protected static boolean registerAsParallelCapable() {
1196         Class<? extends ClassLoader> callerClass =
1197             Reflection.getCallerClass().asSubclass(ClassLoader.class);
1198         return ParallelLoaders.register(callerClass);
1199     }
1200 
1201     /**
1202      * Find a resource of the specified name from the search path used to load
1203      * classes.  This method locates the resource through the system class
1204      * loader (see {@link #getSystemClassLoader()}).
1205      *
1206      * @param  name
1207      *         The resource name
1208      *
1209      * @return  A {@link java.net.URL <tt>URL</tt>} object for reading the
1210      *          resource, or <tt>null</tt> if the resource could not be found
1211      *
1212      * @since  1.1
1213      */
1214     public static URL getSystemResource(String name) {
1215         ClassLoader system = getSystemClassLoader();
1216         if (system == null) {
1217             return getBootstrapResource(name);
1218         }
1219         return system.getResource(name);
1220     }
1221 
1222     /**
1223      * Finds all resources of the specified name from the search path used to
1224      * load classes.  The resources thus found are returned as an
1225      * {@link java.util.Enumeration <tt>Enumeration</tt>} of {@link
1226      * java.net.URL <tt>URL</tt>} objects.
1227      *
1228      * <p> The search order is described in the documentation for {@link
1229      * #getSystemResource(String)}.  </p>
1230      *
1231      * @param  name
1232      *         The resource name
1233      *
1234      * @return  An enumeration of resource {@link java.net.URL <tt>URL</tt>}
1235      *          objects
1236      *
1237      * @throws  IOException
1238      *          If I/O errors occur
1239 
1240      * @since  1.2
1241      */
1242     public static Enumeration<URL> getSystemResources(String name)
1243         throws IOException
1244     {
1245         ClassLoader system = getSystemClassLoader();
1246         if (system == null) {
1247             return getBootstrapResources(name);
1248         }
1249         return system.getResources(name);
1250     }
1251 
1252     /**
1253      * Find resources from the VM's built-in classloader.
1254      */
1255     private static URL getBootstrapResource(String name) {
1256         URLClassPath ucp = getBootstrapClassPath();
1257         Resource res = ucp.getResource(name);
1258         return res != null ? res.getURL() : null;
1259     }
1260 
1261     /**
1262      * Find resources from the VM's built-in classloader.
1263      */
1264     private static Enumeration<URL> getBootstrapResources(String name)
1265         throws IOException
1266     {
1267         final Enumeration<Resource> e =
1268             getBootstrapClassPath().getResources(name);
1269         return new Enumeration<URL> () {
1270             public URL nextElement() {
1271                 return e.nextElement().getURL();
1272             }
1273             public boolean hasMoreElements() {
1274                 return e.hasMoreElements();
1275             }
1276         };
1277     }
1278 
1279     // Returns the URLClassPath that is used for finding system resources.
1280     static URLClassPath getBootstrapClassPath() {
1281         return sun.misc.Launcher.getBootstrapClassPath();
1282     }
1283 
1284 
1285     /**
1286      * Returns an input stream for reading the specified resource.
1287      *
1288      * <p> The search order is described in the documentation for {@link
1289      * #getResource(String)}.  </p>
1290      *
1291      * @param  name
1292      *         The resource name
1293      *
1294      * @return  An input stream for reading the resource, or <tt>null</tt>
1295      *          if the resource could not be found
1296      *
1297      * @since  1.1
1298      */
1299     public InputStream getResourceAsStream(String name) {
1300         URL url = getResource(name);
1301         try {
1302             return url != null ? url.openStream() : null;
1303         } catch (IOException e) {
1304             return null;
1305         }
1306     }
1307 
1308     /**
1309      * Open for reading, a resource of the specified name from the search path
1310      * used to load classes.  This method locates the resource through the
1311      * system class loader (see {@link #getSystemClassLoader()}).
1312      *
1313      * @param  name
1314      *         The resource name
1315      *
1316      * @return  An input stream for reading the resource, or <tt>null</tt>
1317      *          if the resource could not be found
1318      *
1319      * @since  1.1
1320      */
1321     public static InputStream getSystemResourceAsStream(String name) {
1322         URL url = getSystemResource(name);
1323         try {
1324             return url != null ? url.openStream() : null;
1325         } catch (IOException e) {
1326             return null;
1327         }
1328     }
1329 
1330 
1331     // -- Hierarchy --
1332 
1333     /**
1334      * Returns the parent class loader for delegation. Some implementations may
1335      * use <tt>null</tt> to represent the bootstrap class loader. This method
1336      * will return <tt>null</tt> in such implementations if this class loader's
1337      * parent is the bootstrap class loader.
1338      *
1339      * <p> If a security manager is present, and the invoker's class loader is
1340      * not <tt>null</tt> and is not an ancestor of this class loader, then this
1341      * method invokes the security manager's {@link
1342      * SecurityManager#checkPermission(java.security.Permission)
1343      * <tt>checkPermission</tt>} method with a {@link
1344      * RuntimePermission#RuntimePermission(String)
1345      * <tt>RuntimePermission("getClassLoader")</tt>} permission to verify
1346      * access to the parent class loader is permitted.  If not, a
1347      * <tt>SecurityException</tt> will be thrown.  </p>
1348      *
1349      * @return  The parent <tt>ClassLoader</tt>
1350      *
1351      * @throws  SecurityException
1352      *          If a security manager exists and its <tt>checkPermission</tt>
1353      *          method doesn't allow access to this class loader's parent class
1354      *          loader.
1355      *
1356      * @since  1.2
1357      */
1358     @CallerSensitive
1359     public final ClassLoader getParent() {
1360         if (parent == null)
1361             return null;
1362         SecurityManager sm = System.getSecurityManager();
1363         if (sm != null) {
1364             checkClassLoaderPermission(this, Reflection.getCallerClass());
1365         }
1366         return parent;
1367     }
1368 
1369     /**
1370      * Returns the system class loader for delegation.  This is the default
1371      * delegation parent for new <tt>ClassLoader</tt> instances, and is
1372      * typically the class loader used to start the application.
1373      *
1374      * <p> This method is first invoked early in the runtime's startup
1375      * sequence, at which point it creates the system class loader and sets it
1376      * as the context class loader of the invoking <tt>Thread</tt>.
1377      *
1378      * <p> The default system class loader is an implementation-dependent
1379      * instance of this class.
1380      *
1381      * <p> If the system property "<tt>java.system.class.loader</tt>" is defined
1382      * when this method is first invoked then the value of that property is
1383      * taken to be the name of a class that will be returned as the system
1384      * class loader.  The class is loaded using the default system class loader
1385      * and must define a public constructor that takes a single parameter of
1386      * type <tt>ClassLoader</tt> which is used as the delegation parent.  An
1387      * instance is then created using this constructor with the default system
1388      * class loader as the parameter.  The resulting class loader is defined
1389      * to be the system class loader.
1390      *
1391      * <p> If a security manager is present, and the invoker's class loader is
1392      * not <tt>null</tt> and the invoker's class loader is not the same as or
1393      * an ancestor of the system class loader, then this method invokes the
1394      * security manager's {@link
1395      * SecurityManager#checkPermission(java.security.Permission)
1396      * <tt>checkPermission</tt>} method with a {@link
1397      * RuntimePermission#RuntimePermission(String)
1398      * <tt>RuntimePermission("getClassLoader")</tt>} permission to verify
1399      * access to the system class loader.  If not, a
1400      * <tt>SecurityException</tt> will be thrown.  </p>
1401      *
1402      * @return  The system <tt>ClassLoader</tt> for delegation, or
1403      *          <tt>null</tt> if none
1404      *
1405      * @throws  SecurityException
1406      *          If a security manager exists and its <tt>checkPermission</tt>
1407      *          method doesn't allow access to the system class loader.
1408      *
1409      * @throws  IllegalStateException
1410      *          If invoked recursively during the construction of the class
1411      *          loader specified by the "<tt>java.system.class.loader</tt>"
1412      *          property.
1413      *
1414      * @throws  Error
1415      *          If the system property "<tt>java.system.class.loader</tt>"
1416      *          is defined but the named class could not be loaded, the
1417      *          provider class does not define the required constructor, or an
1418      *          exception is thrown by that constructor when it is invoked. The
1419      *          underlying cause of the error can be retrieved via the
1420      *          {@link Throwable#getCause()} method.
1421      *
1422      * @revised  1.4
1423      */
1424     @CallerSensitive
1425     public static ClassLoader getSystemClassLoader() {
1426         initSystemClassLoader();
1427         if (scl == null) {
1428             return null;
1429         }
1430         SecurityManager sm = System.getSecurityManager();
1431         if (sm != null) {
1432             checkClassLoaderPermission(scl, Reflection.getCallerClass());
1433         }
1434         return scl;
1435     }
1436 
1437     private static synchronized void initSystemClassLoader() {
1438         if (!sclSet) {
1439             if (scl != null)
1440                 throw new IllegalStateException("recursive invocation");
1441             sun.misc.Launcher l = sun.misc.Launcher.getLauncher();
1442             if (l != null) {
1443                 Throwable oops = null;
1444                 scl = l.getClassLoader();
1445                 try {
1446                     scl = AccessController.doPrivileged(
1447                         new SystemClassLoaderAction(scl));
1448                 } catch (PrivilegedActionException pae) {
1449                     oops = pae.getCause();
1450                     if (oops instanceof InvocationTargetException) {
1451                         oops = oops.getCause();
1452                     }
1453                 }
1454                 if (oops != null) {
1455                     if (oops instanceof Error) {
1456                         throw (Error) oops;
1457                     } else {
1458                         // wrap the exception
1459                         throw new Error(oops);
1460                     }
1461                 }
1462             }
1463             sclSet = true;
1464         }
1465     }
1466 
1467     // Returns true if the specified class loader can be found in this class
1468     // loader's delegation chain.
1469     boolean isAncestor(ClassLoader cl) {
1470         ClassLoader acl = this;
1471         do {
1472             acl = acl.parent;
1473             if (cl == acl) {
1474                 return true;
1475             }
1476         } while (acl != null);
1477         return false;
1478     }
1479 
1480     // Tests if class loader access requires "getClassLoader" permission
1481     // check.  A class loader 'from' can access class loader 'to' if
1482     // class loader 'from' is same as class loader 'to' or an ancestor
1483     // of 'to'.  The class loader in a system domain can access
1484     // any class loader.
1485     private static boolean needsClassLoaderPermissionCheck(ClassLoader from,
1486                                                            ClassLoader to)
1487     {
1488         if (from == to)
1489             return false;
1490 
1491         if (from == null)
1492             return false;
1493 
1494         return !to.isAncestor(from);
1495     }
1496 
1497     // Returns the class's class loader, or null if none.
1498     static ClassLoader getClassLoader(Class<?> caller) {
1499         // This can be null if the VM is requesting it
1500         if (caller == null) {
1501             return null;
1502         }
1503         // Circumvent security check since this is package-private
1504         return caller.getClassLoader0();
1505     }
1506 
1507     static void checkClassLoaderPermission(ClassLoader cl, Class<?> caller) {
1508         SecurityManager sm = System.getSecurityManager();
1509         if (sm != null) {
1510             // caller can be null if the VM is requesting it
1511             ClassLoader ccl = getClassLoader(caller);
1512             if (needsClassLoaderPermissionCheck(ccl, cl)) {
1513                 sm.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION);
1514             }
1515         }
1516     }
1517 
1518     // The class loader for the system
1519     // @GuardedBy("ClassLoader.class")
1520     private static ClassLoader scl;
1521 
1522     // Set to true once the system class loader has been set
1523     // @GuardedBy("ClassLoader.class")
1524     private static boolean sclSet;
1525 
1526 
1527     // -- Package --
1528 
1529     /**
1530      * Defines a package by name in this <tt>ClassLoader</tt>.  This allows
1531      * class loaders to define the packages for their classes. Packages must
1532      * be created before the class is defined, and package names must be
1533      * unique within a class loader and cannot be redefined or changed once
1534      * created.
1535      *
1536      * @param  name
1537      *         The package name
1538      *
1539      * @param  specTitle
1540      *         The specification title
1541      *
1542      * @param  specVersion
1543      *         The specification version
1544      *
1545      * @param  specVendor
1546      *         The specification vendor
1547      *
1548      * @param  implTitle
1549      *         The implementation title
1550      *
1551      * @param  implVersion
1552      *         The implementation version
1553      *
1554      * @param  implVendor
1555      *         The implementation vendor
1556      *
1557      * @param  sealBase
1558      *         If not <tt>null</tt>, then this package is sealed with
1559      *         respect to the given code source {@link java.net.URL
1560      *         <tt>URL</tt>}  object.  Otherwise, the package is not sealed.
1561      *
1562      * @return  The newly defined <tt>Package</tt> object
1563      *
1564      * @throws  IllegalArgumentException
1565      *          If package name duplicates an existing package either in this
1566      *          class loader or one of its ancestors
1567      *
1568      * @since  1.2
1569      */
1570     protected Package definePackage(String name, String specTitle,
1571                                     String specVersion, String specVendor,
1572                                     String implTitle, String implVersion,
1573                                     String implVendor, URL sealBase)
1574         throws IllegalArgumentException
1575     {
1576         Package pkg = getPackage(name);
1577         if (pkg != null) {
1578             throw new IllegalArgumentException(name);
1579         }
1580         pkg = new Package(name, specTitle, specVersion, specVendor,
1581                           implTitle, implVersion, implVendor,
1582                           sealBase, this);
1583         // Races here can be safely dealt with by ensuring we always return
1584         // the same package object
1585         Package oldPkg = packages.putIfAbsent(name, pkg);
1586         return (oldPkg != null ? oldPkg : pkg);
1587     }
1588 
1589     /**
1590      * Returns a <tt>Package</tt> that has been defined by this class loader
1591      * or any of its ancestors.
1592      *
1593      * @param  name
1594      *         The package name
1595      *
1596      * @return  The <tt>Package</tt> corresponding to the given name, or
1597      *          <tt>null</tt> if not found
1598      *
1599      * @since  1.2
1600      */
1601     protected Package getPackage(String name) {
1602         Package pkg = packages.get(name);
1603         if (pkg == null) {
1604             if (parent != null) {
1605                 pkg = parent.getPackage(name);
1606             } else {
1607                 pkg = Package.getSystemPackage(name);
1608             }
1609         }
1610         return pkg;
1611     }
1612 
1613     /**
1614      * Returns all of the <tt>Packages</tt> defined by this class loader and
1615      * its ancestors.
1616      *
1617      * @return  The array of <tt>Package</tt> objects defined by this
1618      *          <tt>ClassLoader</tt>
1619      *
1620      * @since  1.2
1621      */
1622     protected Package[] getPackages() {
1623         Map<String, Package> map;
1624         Package[] pkgs;
1625         if (parent != null) {
1626             pkgs = parent.getPackages();
1627         } else {
1628             pkgs = Package.getSystemPackages();
1629         }
1630 
1631         if (pkgs == null) {
1632             map = packages;
1633         } else {
1634             map = new HashMap<>(packages);
1635             for (Package pkg : pkgs) {
1636                 String pkgName = pkg.getName();
1637                 if (!map.containsKey(pkgName)) {
1638                     map.put(pkgName, pkg);
1639                 }
1640             }
1641         }
1642         return map.values().toArray(new Package[map.size()]);
1643 
1644     }
1645 
1646 
1647     // -- Native library access --
1648 
1649     /**
1650      * Returns the absolute path name of a native library.  The VM invokes this
1651      * method to locate the native libraries that belong to classes loaded with
1652      * this class loader. If this method returns <tt>null</tt>, the VM
1653      * searches the library along the path specified as the
1654      * "<tt>java.library.path</tt>" property.
1655      *
1656      * @param  libname
1657      *         The library name
1658      *
1659      * @return  The absolute path of the native library
1660      *
1661      * @see  System#loadLibrary(String)
1662      * @see  System#mapLibraryName(String)
1663      *
1664      * @since  1.2
1665      */
1666     protected String findLibrary(String libname) {
1667         return null;
1668     }
1669 
1670     /**
1671      * The inner class NativeLibrary denotes a loaded native library instance.
1672      * Every classloader contains a vector of loaded native libraries in the
1673      * private field <tt>nativeLibraries</tt>.  The native libraries loaded
1674      * into the system are entered into the <tt>systemNativeLibraries</tt>
1675      * vector.
1676      *
1677      * <p> Every native library requires a particular version of JNI. This is
1678      * denoted by the private <tt>jniVersion</tt> field.  This field is set by
1679      * the VM when it loads the library, and used by the VM to pass the correct
1680      * version of JNI to the native methods.  </p>
1681      *
1682      * @see      ClassLoader
1683      * @since    1.2
1684      */
1685     static class NativeLibrary {
1686         // opaque handle to native library, used in native code.
1687         long handle;
1688         // the version of JNI environment the native library requires.
1689         private int jniVersion;
1690         // the class from which the library is loaded, also indicates
1691         // the loader this native library belongs.
1692         private final Class<?> fromClass;
1693         // the canonicalized name of the native library.
1694         // or static library name
1695         String name;
1696         // Indicates if the native library is linked into the VM
1697         boolean isBuiltin;
1698         // Indicates if the native library is loaded
1699         boolean loaded;
1700         native void load(String name, boolean isBuiltin);
1701 
1702         native long find(String name);
1703         native void unload(String name, boolean isBuiltin);
1704         static native String findBuiltinLib(String name);
1705 
1706         public NativeLibrary(Class<?> fromClass, String name, boolean isBuiltin) {
1707             this.name = name;
1708             this.fromClass = fromClass;
1709             this.isBuiltin = isBuiltin;
1710         }
1711 
1712         protected void finalize() {
1713             synchronized (loadedLibraryNames) {
1714                 if (fromClass.getClassLoader() != null && loaded) {
1715                     /* remove the native library name */
1716                     int size = loadedLibraryNames.size();
1717                     for (int i = 0; i < size; i++) {
1718                         if (name.equals(loadedLibraryNames.elementAt(i))) {
1719                             loadedLibraryNames.removeElementAt(i);
1720                             break;
1721                         }
1722                     }
1723                     /* unload the library. */
1724                     ClassLoader.nativeLibraryContext.push(this);
1725                     try {
1726                         unload(name, isBuiltin);
1727                     } finally {
1728                         ClassLoader.nativeLibraryContext.pop();
1729                     }
1730                 }
1731             }
1732         }
1733         // Invoked in the VM to determine the context class in
1734         // JNI_Load/JNI_Unload
1735         static Class<?> getFromClass() {
1736             return ClassLoader.nativeLibraryContext.peek().fromClass;
1737         }
1738     }
1739 
1740     // All native library names we've loaded.
1741     private static Vector<String> loadedLibraryNames = new Vector<>();
1742 
1743     // Native libraries belonging to system classes.
1744     private static Vector<NativeLibrary> systemNativeLibraries
1745         = new Vector<>();
1746 
1747     // Native libraries associated with the class loader.
1748     private Vector<NativeLibrary> nativeLibraries = new Vector<>();
1749 
1750     // native libraries being loaded/unloaded.
1751     private static Stack<NativeLibrary> nativeLibraryContext = new Stack<>();
1752 
1753     // The paths searched for libraries
1754     private static String usr_paths[];
1755     private static String sys_paths[];
1756 
1757     private static String[] initializePath(String propname) {
1758         String ldpath = System.getProperty(propname, "");
1759         String ps = File.pathSeparator;
1760         int ldlen = ldpath.length();
1761         int i, j, n;
1762         // Count the separators in the path
1763         i = ldpath.indexOf(ps);
1764         n = 0;
1765         while (i >= 0) {
1766             n++;
1767             i = ldpath.indexOf(ps, i + 1);
1768         }
1769 
1770         // allocate the array of paths - n :'s = n + 1 path elements
1771         String[] paths = new String[n + 1];
1772 
1773         // Fill the array with paths from the ldpath
1774         n = i = 0;
1775         j = ldpath.indexOf(ps);
1776         while (j >= 0) {
1777             if (j - i > 0) {
1778                 paths[n++] = ldpath.substring(i, j);
1779             } else if (j - i == 0) {
1780                 paths[n++] = ".";
1781             }
1782             i = j + 1;
1783             j = ldpath.indexOf(ps, i);
1784         }
1785         paths[n] = ldpath.substring(i, ldlen);
1786         return paths;
1787     }
1788 
1789     // Invoked in the java.lang.Runtime class to implement load and loadLibrary.
1790     static void loadLibrary(Class<?> fromClass, String name,
1791                             boolean isAbsolute) {
1792         ClassLoader loader =
1793             (fromClass == null) ? null : fromClass.getClassLoader();
1794         if (sys_paths == null) {
1795             usr_paths = initializePath("java.library.path");
1796             sys_paths = initializePath("sun.boot.library.path");
1797         }
1798         if (isAbsolute) {
1799             if (loadLibrary0(fromClass, new File(name))) {
1800                 return;
1801             }
1802             throw new UnsatisfiedLinkError("Can't load library: " + name);
1803         }
1804         if (loader != null) {
1805             String libfilename = loader.findLibrary(name);
1806             if (libfilename != null) {
1807                 File libfile = new File(libfilename);
1808                 if (!libfile.isAbsolute()) {
1809                     throw new UnsatisfiedLinkError(
1810     "ClassLoader.findLibrary failed to return an absolute path: " + libfilename);
1811                 }
1812                 if (loadLibrary0(fromClass, libfile)) {
1813                     return;
1814                 }
1815                 throw new UnsatisfiedLinkError("Can't load " + libfilename);
1816             }
1817         }
1818         for (String sys_path : sys_paths) {
1819             File libfile = new File(sys_path, System.mapLibraryName(name));
1820             if (loadLibrary0(fromClass, libfile)) {
1821                 return;
1822             }
1823             libfile = ClassLoaderHelper.mapAlternativeName(libfile);
1824             if (libfile != null && loadLibrary0(fromClass, libfile)) {
1825                 return;
1826             }
1827         }
1828         if (loader != null) {
1829             for (String usr_path : usr_paths) {
1830                 File libfile = new File(usr_path, System.mapLibraryName(name));
1831                 if (loadLibrary0(fromClass, libfile)) {
1832                     return;
1833                 }
1834                 libfile = ClassLoaderHelper.mapAlternativeName(libfile);
1835                 if (libfile != null && loadLibrary0(fromClass, libfile)) {
1836                     return;
1837                 }
1838             }
1839         }
1840         // Oops, it failed
1841         throw new UnsatisfiedLinkError("no " + name + " in java.library.path");
1842     }
1843 
1844     private static boolean loadLibrary0(Class<?> fromClass, final File file) {
1845         // Check to see if we're attempting to access a static library
1846         String name = NativeLibrary.findBuiltinLib(file.getName());
1847         boolean isBuiltin = (name != null);
1848         if (!isBuiltin) {
1849             name = AccessController.doPrivileged(
1850                 new PrivilegedAction<String>() {
1851                     public String run() {
1852                         try {
1853                             return file.exists() ? file.getCanonicalPath() : null;
1854                         } catch (IOException e) {
1855                             return null;
1856                         }
1857                     }
1858                 });
1859             if (name == null) {
1860                 return false;
1861             }
1862         }
1863         ClassLoader loader =
1864             (fromClass == null) ? null : fromClass.getClassLoader();
1865         Vector<NativeLibrary> libs =
1866             loader != null ? loader.nativeLibraries : systemNativeLibraries;
1867         synchronized (libs) {
1868             int size = libs.size();
1869             for (int i = 0; i < size; i++) {
1870                 NativeLibrary lib = libs.elementAt(i);
1871                 if (name.equals(lib.name)) {
1872                     return true;
1873                 }
1874             }
1875 
1876             synchronized (loadedLibraryNames) {
1877                 if (loadedLibraryNames.contains(name)) {
1878                     throw new UnsatisfiedLinkError
1879                         ("Native Library " +
1880                          name +
1881                          " already loaded in another classloader");
1882                 }
1883                 /* If the library is being loaded (must be by the same thread,
1884                  * because Runtime.load and Runtime.loadLibrary are
1885                  * synchronous). The reason is can occur is that the JNI_OnLoad
1886                  * function can cause another loadLibrary invocation.
1887                  *
1888                  * Thus we can use a static stack to hold the list of libraries
1889                  * we are loading.
1890                  *
1891                  * If there is a pending load operation for the library, we
1892                  * immediately return success; otherwise, we raise
1893                  * UnsatisfiedLinkError.
1894                  */
1895                 int n = nativeLibraryContext.size();
1896                 for (int i = 0; i < n; i++) {
1897                     NativeLibrary lib = nativeLibraryContext.elementAt(i);
1898                     if (name.equals(lib.name)) {
1899                         if (loader == lib.fromClass.getClassLoader()) {
1900                             return true;
1901                         } else {
1902                             throw new UnsatisfiedLinkError
1903                                 ("Native Library " +
1904                                  name +
1905                                  " is being loaded in another classloader");
1906                         }
1907                     }
1908                 }
1909                 NativeLibrary lib = new NativeLibrary(fromClass, name, isBuiltin);
1910                 nativeLibraryContext.push(lib);
1911                 try {
1912                     lib.load(name, isBuiltin);
1913                 } finally {
1914                     nativeLibraryContext.pop();
1915                 }
1916                 if (lib.loaded) {
1917                     loadedLibraryNames.addElement(name);
1918                     libs.addElement(lib);
1919                     return true;
1920                 }
1921                 return false;
1922             }
1923         }
1924     }
1925 
1926     // Invoked in the VM class linking code.
1927     static long findNative(ClassLoader loader, String name) {
1928         Vector<NativeLibrary> libs =
1929             loader != null ? loader.nativeLibraries : systemNativeLibraries;
1930         synchronized (libs) {
1931             int size = libs.size();
1932             for (int i = 0; i < size; i++) {
1933                 NativeLibrary lib = libs.elementAt(i);
1934                 long entry = lib.find(name);
1935                 if (entry != 0)
1936                     return entry;
1937             }
1938         }
1939         return 0;
1940     }
1941 
1942 
1943     // -- Assertion management --
1944 
1945     final Object assertionLock;
1946 
1947     // The default toggle for assertion checking.
1948     // @GuardedBy("assertionLock")
1949     private boolean defaultAssertionStatus = false;
1950 
1951     // Maps String packageName to Boolean package default assertion status Note
1952     // that the default package is placed under a null map key.  If this field
1953     // is null then we are delegating assertion status queries to the VM, i.e.,
1954     // none of this ClassLoader's assertion status modification methods have
1955     // been invoked.
1956     // @GuardedBy("assertionLock")
1957     private Map<String, Boolean> packageAssertionStatus = null;
1958 
1959     // Maps String fullyQualifiedClassName to Boolean assertionStatus If this
1960     // field is null then we are delegating assertion status queries to the VM,
1961     // i.e., none of this ClassLoader's assertion status modification methods
1962     // have been invoked.
1963     // @GuardedBy("assertionLock")
1964     Map<String, Boolean> classAssertionStatus = null;
1965 
1966     /**
1967      * Sets the default assertion status for this class loader.  This setting
1968      * determines whether classes loaded by this class loader and initialized
1969      * in the future will have assertions enabled or disabled by default.
1970      * This setting may be overridden on a per-package or per-class basis by
1971      * invoking {@link #setPackageAssertionStatus(String, boolean)} or {@link
1972      * #setClassAssertionStatus(String, boolean)}.
1973      *
1974      * @param  enabled
1975      *         <tt>true</tt> if classes loaded by this class loader will
1976      *         henceforth have assertions enabled by default, <tt>false</tt>
1977      *         if they will have assertions disabled by default.
1978      *
1979      * @since  1.4
1980      */
1981     public void setDefaultAssertionStatus(boolean enabled) {
1982         synchronized (assertionLock) {
1983             if (classAssertionStatus == null)
1984                 initializeJavaAssertionMaps();
1985 
1986             defaultAssertionStatus = enabled;
1987         }
1988     }
1989 
1990     /**
1991      * Sets the package default assertion status for the named package.  The
1992      * package default assertion status determines the assertion status for
1993      * classes initialized in the future that belong to the named package or
1994      * any of its "subpackages".
1995      *
1996      * <p> A subpackage of a package named p is any package whose name begins
1997      * with "<tt>p.</tt>".  For example, <tt>javax.swing.text</tt> is a
1998      * subpackage of <tt>javax.swing</tt>, and both <tt>java.util</tt> and
1999      * <tt>java.lang.reflect</tt> are subpackages of <tt>java</tt>.
2000      *
2001      * <p> In the event that multiple package defaults apply to a given class,
2002      * the package default pertaining to the most specific package takes
2003      * precedence over the others.  For example, if <tt>javax.lang</tt> and
2004      * <tt>javax.lang.reflect</tt> both have package defaults associated with
2005      * them, the latter package default applies to classes in
2006      * <tt>javax.lang.reflect</tt>.
2007      *
2008      * <p> Package defaults take precedence over the class loader's default
2009      * assertion status, and may be overridden on a per-class basis by invoking
2010      * {@link #setClassAssertionStatus(String, boolean)}.  </p>
2011      *
2012      * @param  packageName
2013      *         The name of the package whose package default assertion status
2014      *         is to be set. A <tt>null</tt> value indicates the unnamed
2015      *         package that is "current"
2016      *         (see section 7.4.2 of
2017      *         <cite>The Java&trade; Language Specification</cite>.)
2018      *
2019      * @param  enabled
2020      *         <tt>true</tt> if classes loaded by this classloader and
2021      *         belonging to the named package or any of its subpackages will
2022      *         have assertions enabled by default, <tt>false</tt> if they will
2023      *         have assertions disabled by default.
2024      *
2025      * @since  1.4
2026      */
2027     public void setPackageAssertionStatus(String packageName,
2028                                           boolean enabled) {
2029         synchronized (assertionLock) {
2030             if (packageAssertionStatus == null)
2031                 initializeJavaAssertionMaps();
2032 
2033             packageAssertionStatus.put(packageName, enabled);
2034         }
2035     }
2036 
2037     /**
2038      * Sets the desired assertion status for the named top-level class in this
2039      * class loader and any nested classes contained therein.  This setting
2040      * takes precedence over the class loader's default assertion status, and
2041      * over any applicable per-package default.  This method has no effect if
2042      * the named class has already been initialized.  (Once a class is
2043      * initialized, its assertion status cannot change.)
2044      *
2045      * <p> If the named class is not a top-level class, this invocation will
2046      * have no effect on the actual assertion status of any class. </p>
2047      *
2048      * @param  className
2049      *         The fully qualified class name of the top-level class whose
2050      *         assertion status is to be set.
2051      *
2052      * @param  enabled
2053      *         <tt>true</tt> if the named class is to have assertions
2054      *         enabled when (and if) it is initialized, <tt>false</tt> if the
2055      *         class is to have assertions disabled.
2056      *
2057      * @since  1.4
2058      */
2059     public void setClassAssertionStatus(String className, boolean enabled) {
2060         synchronized (assertionLock) {
2061             if (classAssertionStatus == null)
2062                 initializeJavaAssertionMaps();
2063 
2064             classAssertionStatus.put(className, enabled);
2065         }
2066     }
2067 
2068     /**
2069      * Sets the default assertion status for this class loader to
2070      * <tt>false</tt> and discards any package defaults or class assertion
2071      * status settings associated with the class loader.  This method is
2072      * provided so that class loaders can be made to ignore any command line or
2073      * persistent assertion status settings and "start with a clean slate."
2074      *
2075      * @since  1.4
2076      */
2077     public void clearAssertionStatus() {
2078         /*
2079          * Whether or not "Java assertion maps" are initialized, set
2080          * them to empty maps, effectively ignoring any present settings.
2081          */
2082         synchronized (assertionLock) {
2083             classAssertionStatus = new HashMap<>();
2084             packageAssertionStatus = new HashMap<>();
2085             defaultAssertionStatus = false;
2086         }
2087     }
2088 
2089     /**
2090      * Returns the assertion status that would be assigned to the specified
2091      * class if it were to be initialized at the time this method is invoked.
2092      * If the named class has had its assertion status set, the most recent
2093      * setting will be returned; otherwise, if any package default assertion
2094      * status pertains to this class, the most recent setting for the most
2095      * specific pertinent package default assertion status is returned;
2096      * otherwise, this class loader's default assertion status is returned.
2097      * </p>
2098      *
2099      * @param  className
2100      *         The fully qualified class name of the class whose desired
2101      *         assertion status is being queried.
2102      *
2103      * @return  The desired assertion status of the specified class.
2104      *
2105      * @see  #setClassAssertionStatus(String, boolean)
2106      * @see  #setPackageAssertionStatus(String, boolean)
2107      * @see  #setDefaultAssertionStatus(boolean)
2108      *
2109      * @since  1.4
2110      */
2111     boolean desiredAssertionStatus(String className) {
2112         synchronized (assertionLock) {
2113             // assert classAssertionStatus   != null;
2114             // assert packageAssertionStatus != null;
2115 
2116             // Check for a class entry
2117             Boolean result = classAssertionStatus.get(className);
2118             if (result != null)
2119                 return result.booleanValue();
2120 
2121             // Check for most specific package entry
2122             int dotIndex = className.lastIndexOf('.');
2123             if (dotIndex < 0) { // default package
2124                 result = packageAssertionStatus.get(null);
2125                 if (result != null)
2126                     return result.booleanValue();
2127             }
2128             while(dotIndex > 0) {
2129                 className = className.substring(0, dotIndex);
2130                 result = packageAssertionStatus.get(className);
2131                 if (result != null)
2132                     return result.booleanValue();
2133                 dotIndex = className.lastIndexOf('.', dotIndex-1);
2134             }
2135 
2136             // Return the classloader default
2137             return defaultAssertionStatus;
2138         }
2139     }
2140 
2141     // Set up the assertions with information provided by the VM.
2142     // Note: Should only be called inside a synchronized block
2143     private void initializeJavaAssertionMaps() {
2144         // assert Thread.holdsLock(assertionLock);
2145 
2146         classAssertionStatus = new HashMap<>();
2147         packageAssertionStatus = new HashMap<>();
2148         AssertionStatusDirectives directives = retrieveDirectives();
2149 
2150         for(int i = 0; i < directives.classes.length; i++)
2151             classAssertionStatus.put(directives.classes[i],
2152                                      directives.classEnabled[i]);
2153 
2154         for(int i = 0; i < directives.packages.length; i++)
2155             packageAssertionStatus.put(directives.packages[i],
2156                                        directives.packageEnabled[i]);
2157 
2158         defaultAssertionStatus = directives.deflt;
2159     }
2160 
2161     // Retrieves the assertion directives from the VM.
2162     private static native AssertionStatusDirectives retrieveDirectives();
2163 }
2164 
2165 
2166 class SystemClassLoaderAction
2167     implements PrivilegedExceptionAction<ClassLoader> {
2168     private ClassLoader parent;
2169 
2170     SystemClassLoaderAction(ClassLoader parent) {
2171         this.parent = parent;
2172     }
2173 
2174     public ClassLoader run() throws Exception {
2175         String cls = System.getProperty("java.system.class.loader");
2176         if (cls == null) {
2177             return parent;
2178         }
2179 
2180         Constructor<?> ctor = Class.forName(cls, true, parent)
2181             .getDeclaredConstructor(new Class<?>[] { ClassLoader.class });
2182         ClassLoader sys = (ClassLoader) ctor.newInstance(
2183             new Object[] { parent });
2184         Thread.currentThread().setContextClassLoader(sys);
2185         return sys;
2186     }
2187 }