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