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