src/share/classes/java/lang/ClassLoader.java

Print this page




 241     // Hashtable that maps packages to certs
 242     private final Map <String, Certificate[]> package2certs;
 243 
 244     // Shared among all packages with unsigned classes
 245     private static final Certificate[] nocerts = new Certificate[0];
 246 
 247     // The classes loaded by this class loader. The only purpose of this table
 248     // is to keep the classes from being GC'ed until the loader is GC'ed.
 249     private final Vector<Class<?>> classes = new Vector<>();
 250 
 251     // The "default" domain. Set as the default ProtectionDomain on newly
 252     // created classes.
 253     private final ProtectionDomain defaultDomain =
 254         new ProtectionDomain(new CodeSource(null, (Certificate[]) null),
 255                              null, this, null);
 256 
 257     // The initiating protection domains for all classes loaded by this loader
 258     private final Set<ProtectionDomain> domains;
 259 
 260     // Invoked by the VM to record every loaded class with this loader.
 261     void addClass(Class c) {
 262         classes.addElement(c);
 263     }
 264 
 265     // The packages defined in this class loader.  Each package name is mapped
 266     // to its corresponding Package object.
 267     // @GuardedBy("itself")
 268     private final HashMap<String, Package> packages = new HashMap<>();
 269 
 270     private static Void checkCreateClassLoader() {
 271         SecurityManager security = System.getSecurityManager();
 272         if (security != null) {
 273             security.checkCreateClassLoader();
 274         }
 275         return null;
 276     }
 277 
 278     private ClassLoader(Void unused, ClassLoader parent) {
 279         this.parent = parent;
 280         if (ParallelLoaders.isRegistered(this.getClass())) {
 281             parallelLockMap = new ConcurrentHashMap<>();


 385      * <p> Unless overridden, this method synchronizes on the result of
 386      * {@link #getClassLoadingLock <tt>getClassLoadingLock</tt>} method
 387      * during the entire class loading process.
 388      *
 389      * @param  name
 390      *         The <a href="#name">binary name</a> of the class
 391      *
 392      * @param  resolve
 393      *         If <tt>true</tt> then resolve the class
 394      *
 395      * @return  The resulting <tt>Class</tt> object
 396      *
 397      * @throws  ClassNotFoundException
 398      *          If the class could not be found
 399      */
 400     protected Class<?> loadClass(String name, boolean resolve)
 401         throws ClassNotFoundException
 402     {
 403         synchronized (getClassLoadingLock(name)) {
 404             // First, check if the class has already been loaded
 405             Class c = findLoadedClass(name);
 406             if (c == null) {
 407                 long t0 = System.nanoTime();
 408                 try {
 409                     if (parent != null) {
 410                         c = parent.loadClass(name, false);
 411                     } else {
 412                         c = findBootstrapClassOrNull(name);
 413                     }
 414                 } catch (ClassNotFoundException e) {
 415                     // ClassNotFoundException thrown if class not found
 416                     // from the non-null parent class loader
 417                 }
 418 
 419                 if (c == null) {
 420                     // If still not found, then invoke findClass in order
 421                     // to find the class.
 422                     long t1 = System.nanoTime();
 423                     c = findClass(name);
 424 
 425                     // this is the defining class loader; record the stats


 451      * @throws NullPointerException
 452      *         If registered as parallel capable and <tt>className</tt> is null
 453      *
 454      * @see #loadClass(String, boolean)
 455      *
 456      * @since  1.7
 457      */
 458     protected Object getClassLoadingLock(String className) {
 459         Object lock = this;
 460         if (parallelLockMap != null) {
 461             Object newLock = new Object();
 462             lock = parallelLockMap.putIfAbsent(className, newLock);
 463             if (lock == null) {
 464                 lock = newLock;
 465             }
 466         }
 467         return lock;
 468     }
 469 
 470     // This method is invoked by the virtual machine to load a class.
 471     private Class loadClassInternal(String name)
 472         throws ClassNotFoundException
 473     {
 474         // For backward compatibility, explicitly lock on 'this' when
 475         // the current class loader is not parallel capable.
 476         if (parallelLockMap == null) {
 477             synchronized (this) {
 478                  return loadClass(name);
 479             }
 480         } else {
 481             return loadClass(name);
 482         }
 483     }
 484 
 485     // Invoked by the VM after loading class with this loader.
 486     private void checkPackageAccess(Class cls, ProtectionDomain pd) {
 487         final SecurityManager sm = System.getSecurityManager();
 488         if (sm != null) {
 489             final String name = cls.getName();
 490             final int i = name.lastIndexOf('.');
 491             if (i != -1) {
 492                 AccessController.doPrivileged(new PrivilegedAction<Void>() {
 493                     public Void run() {
 494                         sm.checkPackageAccess(name.substring(0, i));
 495                         return null;
 496                     }
 497                 }, new AccessControlContext(new ProtectionDomain[] {pd}));
 498             }
 499         }
 500         domains.add(pd);
 501     }
 502 
 503     /**
 504      * Finds the class with the specified <a href="#name">binary name</a>.
 505      * This method should be overridden by class loader implementations that
 506      * follow the delegation model for loading classes, and will be invoked by


 652         }
 653         if (pd == null) {
 654             pd = defaultDomain;
 655         }
 656 
 657         if (name != null) checkCerts(name, pd.getCodeSource());
 658 
 659         return pd;
 660     }
 661 
 662     private String defineClassSourceLocation(ProtectionDomain pd)
 663     {
 664         CodeSource cs = pd.getCodeSource();
 665         String source = null;
 666         if (cs != null && cs.getLocation() != null) {
 667             source = cs.getLocation().toString();
 668         }
 669         return source;
 670     }
 671 
 672     private Class defineTransformedClass(String name, byte[] b, int off, int len,
 673                                          ProtectionDomain pd,
 674                                          ClassFormatError cfe, String source)
 675       throws ClassFormatError
 676     {
 677         // Class format error - try to transform the bytecode and
 678         // define the class again
 679         //
 680         ClassFileTransformer[] transformers =
 681             ClassFileTransformer.getTransformers();
 682         Class c = null;
 683 
 684         if (transformers != null) {
 685             for (ClassFileTransformer transformer : transformers) {
 686                 try {
 687                     // Transform byte code using transformer
 688                     byte[] tb = transformer.transform(b, off, len);
 689                     c = defineClass1(name, tb, 0, tb.length,
 690                                      pd, source);
 691                     break;
 692                 } catch (ClassFormatError cfe2)     {
 693                     // If ClassFormatError occurs, try next transformer
 694                 }
 695             }
 696         }
 697 
 698         // Rethrow original ClassFormatError if unable to transform
 699         // bytecode to well-formed
 700         //
 701         if (c == null)
 702             throw cfe;
 703 
 704         return c;
 705     }
 706 
 707     private void postDefineClass(Class c, ProtectionDomain pd)
 708     {
 709         if (pd.getCodeSource() != null) {
 710             Certificate certs[] = pd.getCodeSource().getCertificates();
 711             if (certs != null)
 712                 setSigners(c, certs);
 713         }
 714     }
 715 
 716     /**
 717      * Converts an array of bytes into an instance of class <tt>Class</tt>,
 718      * with an optional <tt>ProtectionDomain</tt>.  If the domain is
 719      * <tt>null</tt>, then a default domain will be assigned to the class as
 720      * specified in the documentation for {@link #defineClass(String, byte[],
 721      * int, int)}.  Before the class can be used it must be resolved.
 722      *
 723      * <p> The first class defined in a package determines the exact set of
 724      * certificates that all subsequent classes defined in that package must
 725      * contain.  The set of certificates for a class is obtained from the
 726      * {@link java.security.CodeSource <tt>CodeSource</tt>} within the
 727      * <tt>ProtectionDomain</tt> of the class.  Any classes added to that


 767      * @throws  NoClassDefFoundError
 768      *          If <tt>name</tt> is not equal to the <a href="#name">binary
 769      *          name</a> of the class specified by <tt>b</tt>
 770      *
 771      * @throws  IndexOutOfBoundsException
 772      *          If either <tt>off</tt> or <tt>len</tt> is negative, or if
 773      *          <tt>off+len</tt> is greater than <tt>b.length</tt>.
 774      *
 775      * @throws  SecurityException
 776      *          If an attempt is made to add this class to a package that
 777      *          contains classes that were signed by a different set of
 778      *          certificates than this class, or if <tt>name</tt> begins with
 779      *          "<tt>java.</tt>".
 780      */
 781     protected final Class<?> defineClass(String name, byte[] b, int off, int len,
 782                                          ProtectionDomain protectionDomain)
 783         throws ClassFormatError
 784     {
 785         protectionDomain = preDefineClass(name, protectionDomain);
 786 
 787         Class c = null;
 788         String source = defineClassSourceLocation(protectionDomain);
 789 
 790         try {
 791             c = defineClass1(name, b, off, len, protectionDomain, source);
 792         } catch (ClassFormatError cfe) {
 793             c = defineTransformedClass(name, b, off, len, protectionDomain, cfe,
 794                                        source);
 795         }
 796 
 797         postDefineClass(c, protectionDomain);
 798         return c;
 799     }
 800 
 801     /**
 802      * Converts a {@link java.nio.ByteBuffer <tt>ByteBuffer</tt>}
 803      * into an instance of class <tt>Class</tt>,
 804      * with an optional <tt>ProtectionDomain</tt>.  If the domain is
 805      * <tt>null</tt>, then a default domain will be assigned to the class as
 806      * specified in the documentation for {@link #defineClass(String, byte[],
 807      * int, int)}.  Before the class can be used it must be resolved.


 865         throws ClassFormatError
 866     {
 867         int len = b.remaining();
 868 
 869         // Use byte[] if not a direct ByteBufer:
 870         if (!b.isDirect()) {
 871             if (b.hasArray()) {
 872                 return defineClass(name, b.array(),
 873                                    b.position() + b.arrayOffset(), len,
 874                                    protectionDomain);
 875             } else {
 876                 // no array, or read-only array
 877                 byte[] tb = new byte[len];
 878                 b.get(tb);  // get bytes out of byte buffer.
 879                 return defineClass(name, tb, 0, len, protectionDomain);
 880             }
 881         }
 882 
 883         protectionDomain = preDefineClass(name, protectionDomain);
 884 
 885         Class c = null;
 886         String source = defineClassSourceLocation(protectionDomain);
 887 
 888         try {
 889             c = defineClass2(name, b, b.position(), len, protectionDomain,
 890                              source);
 891         } catch (ClassFormatError cfe) {
 892             byte[] tb = new byte[len];
 893             b.get(tb);  // get bytes out of byte buffer.
 894             c = defineTransformedClass(name, tb, 0, len, protectionDomain, cfe,
 895                                        source);
 896         }
 897 
 898         postDefineClass(c, protectionDomain);
 899         return c;
 900     }
 901 
 902     private native Class defineClass0(String name, byte[] b, int off, int len,
 903                                       ProtectionDomain pd);
 904 
 905     private native Class defineClass1(String name, byte[] b, int off, int len,
 906                                       ProtectionDomain pd, String source);
 907 
 908     private native Class defineClass2(String name, java.nio.ByteBuffer b,
 909                                       int off, int len, ProtectionDomain pd,
 910                                       String source);
 911 
 912     // true if the name is null or has the potential to be a valid binary name
 913     private boolean checkName(String name) {
 914         if ((name == null) || (name.length() == 0))
 915             return true;
 916         if ((name.indexOf('/') != -1)
 917             || (!VM.allowArraySyntax() && (name.charAt(0) == '[')))
 918             return false;
 919         return true;
 920     }
 921 
 922     private void checkCerts(String name, CodeSource cs) {
 923         int i = name.lastIndexOf('.');
 924         String pname = (i == -1) ? "" : name.substring(0, i);
 925 
 926         Certificate[] certs = null;
 927         if (cs != null) {
 928             certs = cs.getCertificates();


 993     /**
 994      * Links the specified class.  This (misleadingly named) method may be
 995      * used by a class loader to link a class.  If the class <tt>c</tt> has
 996      * already been linked, then this method simply returns. Otherwise, the
 997      * class is linked as described in the "Execution" chapter of
 998      * <cite>The Java&trade; Language Specification</cite>.
 999      * </p>
1000      *
1001      * @param  c
1002      *         The class to link
1003      *
1004      * @throws  NullPointerException
1005      *          If <tt>c</tt> is <tt>null</tt>.
1006      *
1007      * @see  #defineClass(String, byte[], int, int)
1008      */
1009     protected final void resolveClass(Class<?> c) {
1010         resolveClass0(c);
1011     }
1012 
1013     private native void resolveClass0(Class c);
1014 
1015     /**
1016      * Finds a class with the specified <a href="#name">binary name</a>,
1017      * loading it if necessary.
1018      *
1019      * <p> This method loads the class through the system class loader (see
1020      * {@link #getSystemClassLoader()}).  The <tt>Class</tt> object returned
1021      * might have more than one <tt>ClassLoader</tt> associated with it.
1022      * Subclasses of <tt>ClassLoader</tt> need not usually invoke this method,
1023      * because most class loaders need to override just {@link
1024      * #findClass(String)}.  </p>
1025      *
1026      * @param  name
1027      *         The <a href="#name">binary name</a> of the class
1028      *
1029      * @return  The <tt>Class</tt> object for the specified <tt>name</tt>
1030      *
1031      * @throws  ClassNotFoundException
1032      *          If the class could not be found
1033      *
1034      * @see  #ClassLoader(ClassLoader)
1035      * @see  #getParent()
1036      */
1037     protected final Class<?> findSystemClass(String name)
1038         throws ClassNotFoundException
1039     {
1040         ClassLoader system = getSystemClassLoader();
1041         if (system == null) {
1042             if (!checkName(name))
1043                 throw new ClassNotFoundException(name);
1044             Class cls = findBootstrapClass(name);
1045             if (cls == null) {
1046                 throw new ClassNotFoundException(name);
1047             }
1048             return cls;
1049         }
1050         return system.loadClass(name);
1051     }
1052 
1053     /**
1054      * Returns a class loaded by the bootstrap class loader;
1055      * or return null if not found.
1056      */
1057     private Class findBootstrapClassOrNull(String name)
1058     {
1059         if (!checkName(name)) return null;
1060 
1061         return findBootstrapClass(name);
1062     }
1063 
1064     // return null if not found
1065     private native Class findBootstrapClass(String name);
1066 
1067     /**
1068      * Returns the class with the given <a href="#name">binary name</a> if this
1069      * loader has been recorded by the Java virtual machine as an initiating
1070      * loader of a class with that <a href="#name">binary name</a>.  Otherwise
1071      * <tt>null</tt> is returned.  </p>
1072      *
1073      * @param  name
1074      *         The <a href="#name">binary name</a> of the class
1075      *
1076      * @return  The <tt>Class</tt> object, or <tt>null</tt> if the class has
1077      *          not been loaded
1078      *
1079      * @since  1.1
1080      */
1081     protected final Class<?> findLoadedClass(String name) {
1082         if (!checkName(name))
1083             return null;
1084         return findLoadedClass0(name);
1085     }
1086 
1087     private native final Class findLoadedClass0(String name);
1088 
1089     /**
1090      * Sets the signers of a class.  This should be invoked after defining a
1091      * class.  </p>
1092      *
1093      * @param  c
1094      *         The <tt>Class</tt> object
1095      *
1096      * @param  signers
1097      *         The signers for the class
1098      *
1099      * @since  1.1
1100      */
1101     protected final void setSigners(Class<?> c, Object[] signers) {
1102         c.setSigners(signers);
1103     }
1104 
1105 
1106     // -- Resource --
1107 


1511 
1512     // Returns true if the specified class loader can be found in this class
1513     // loader's delegation chain.
1514     boolean isAncestor(ClassLoader cl) {
1515         ClassLoader acl = this;
1516         do {
1517             acl = acl.parent;
1518             if (cl == acl) {
1519                 return true;
1520             }
1521         } while (acl != null);
1522         return false;
1523     }
1524 
1525     // Returns the invoker's class loader, or null if none.
1526     // NOTE: This must always be invoked when there is exactly one intervening
1527     // frame from the core libraries on the stack between this method's
1528     // invocation and the desired invoker.
1529     static ClassLoader getCallerClassLoader() {
1530         // NOTE use of more generic Reflection.getCallerClass()
1531         Class caller = Reflection.getCallerClass(3);
1532         // This can be null if the VM is requesting it
1533         if (caller == null) {
1534             return null;
1535         }
1536         // Circumvent security check since this is package-private
1537         return caller.getClassLoader0();
1538     }
1539 
1540     // The class loader for the system
1541     // @GuardedBy("ClassLoader.class")
1542     private static ClassLoader scl;
1543 
1544     // Set to true once the system class loader has been set
1545     // @GuardedBy("ClassLoader.class")
1546     private static boolean sclSet;
1547 
1548 
1549     // -- Package --
1550 
1551     /**


1705      * Every classloader contains a vector of loaded native libraries in the
1706      * private field <tt>nativeLibraries</tt>.  The native libraries loaded
1707      * into the system are entered into the <tt>systemNativeLibraries</tt>
1708      * vector.
1709      *
1710      * <p> Every native library requires a particular version of JNI. This is
1711      * denoted by the private <tt>jniVersion</tt> field.  This field is set by
1712      * the VM when it loads the library, and used by the VM to pass the correct
1713      * version of JNI to the native methods.  </p>
1714      *
1715      * @see      ClassLoader
1716      * @since    1.2
1717      */
1718     static class NativeLibrary {
1719         // opaque handle to native library, used in native code.
1720         long handle;
1721         // the version of JNI environment the native library requires.
1722         private int jniVersion;
1723         // the class from which the library is loaded, also indicates
1724         // the loader this native library belongs.
1725         private Class fromClass;
1726         // the canonicalized name of the native library.
1727         String name;
1728 
1729         native void load(String name);
1730         native long find(String name);
1731         native void unload();
1732 
1733         public NativeLibrary(Class fromClass, String name) {
1734             this.name = name;
1735             this.fromClass = fromClass;
1736         }
1737 
1738         protected void finalize() {
1739             synchronized (loadedLibraryNames) {
1740                 if (fromClass.getClassLoader() != null && handle != 0) {
1741                     /* remove the native library name */
1742                     int size = loadedLibraryNames.size();
1743                     for (int i = 0; i < size; i++) {
1744                         if (name.equals(loadedLibraryNames.elementAt(i))) {
1745                             loadedLibraryNames.removeElementAt(i);
1746                             break;
1747                         }
1748                     }
1749                     /* unload the library. */
1750                     ClassLoader.nativeLibraryContext.push(this);
1751                     try {
1752                         unload();
1753                     } finally {
1754                         ClassLoader.nativeLibraryContext.pop();
1755                     }
1756                 }
1757             }
1758         }
1759         // Invoked in the VM to determine the context class in
1760         // JNI_Load/JNI_Unload
1761         static Class getFromClass() {
1762             return ClassLoader.nativeLibraryContext.peek().fromClass;
1763         }
1764     }
1765 
1766     // All native library names we've loaded.
1767     private static Vector<String> loadedLibraryNames = new Vector<>();
1768 
1769     // Native libraries belonging to system classes.
1770     private static Vector<NativeLibrary> systemNativeLibraries
1771         = new Vector<>();
1772 
1773     // Native libraries associated with the class loader.
1774     private Vector<NativeLibrary> nativeLibraries = new Vector<>();
1775 
1776     // native libraries being loaded/unloaded.
1777     private static Stack<NativeLibrary> nativeLibraryContext = new Stack<>();
1778 
1779     // The paths searched for libraries
1780     private static String usr_paths[];
1781     private static String sys_paths[];


1796         // allocate the array of paths - n :'s = n + 1 path elements
1797         String[] paths = new String[n + 1];
1798 
1799         // Fill the array with paths from the ldpath
1800         n = i = 0;
1801         j = ldpath.indexOf(ps);
1802         while (j >= 0) {
1803             if (j - i > 0) {
1804                 paths[n++] = ldpath.substring(i, j);
1805             } else if (j - i == 0) {
1806                 paths[n++] = ".";
1807             }
1808             i = j + 1;
1809             j = ldpath.indexOf(ps, i);
1810         }
1811         paths[n] = ldpath.substring(i, ldlen);
1812         return paths;
1813     }
1814 
1815     // Invoked in the java.lang.Runtime class to implement load and loadLibrary.
1816     static void loadLibrary(Class fromClass, String name,
1817                             boolean isAbsolute) {
1818         ClassLoader loader =
1819             (fromClass == null) ? null : fromClass.getClassLoader();
1820         if (sys_paths == null) {
1821             usr_paths = initializePath("java.library.path");
1822             sys_paths = initializePath("sun.boot.library.path");
1823         }
1824         if (isAbsolute) {
1825             if (loadLibrary0(fromClass, new File(name))) {
1826                 return;
1827             }
1828             throw new UnsatisfiedLinkError("Can't load library: " + name);
1829         }
1830         if (loader != null) {
1831             String libfilename = loader.findLibrary(name);
1832             if (libfilename != null) {
1833                 File libfile = new File(libfilename);
1834                 if (!libfile.isAbsolute()) {
1835                     throw new UnsatisfiedLinkError(
1836     "ClassLoader.findLibrary failed to return an absolute path: " + libfilename);


1843         }
1844         for (int i = 0 ; i < sys_paths.length ; i++) {
1845             File libfile = new File(sys_paths[i], System.mapLibraryName(name));
1846             if (loadLibrary0(fromClass, libfile)) {
1847                 return;
1848             }
1849         }
1850         if (loader != null) {
1851             for (int i = 0 ; i < usr_paths.length ; i++) {
1852                 File libfile = new File(usr_paths[i],
1853                                         System.mapLibraryName(name));
1854                 if (loadLibrary0(fromClass, libfile)) {
1855                     return;
1856                 }
1857             }
1858         }
1859         // Oops, it failed
1860         throw new UnsatisfiedLinkError("no " + name + " in java.library.path");
1861     }
1862 
1863     private static boolean loadLibrary0(Class fromClass, final File file) {
1864         boolean exists = AccessController.doPrivileged(
1865             new PrivilegedAction<Object>() {
1866                 public Object run() {
1867                     return file.exists() ? Boolean.TRUE : null;
1868                 }})
1869             != null;
1870         if (!exists) {
1871             return false;
1872         }
1873         String name;
1874         try {
1875             name = file.getCanonicalPath();
1876         } catch (IOException e) {
1877             return false;
1878         }
1879         ClassLoader loader =
1880             (fromClass == null) ? null : fromClass.getClassLoader();
1881         Vector<NativeLibrary> libs =
1882             loader != null ? loader.nativeLibraries : systemNativeLibraries;
1883         synchronized (libs) {


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 }


 241     // Hashtable that maps packages to certs
 242     private final Map <String, Certificate[]> package2certs;
 243 
 244     // Shared among all packages with unsigned classes
 245     private static final Certificate[] nocerts = new Certificate[0];
 246 
 247     // The classes loaded by this class loader. The only purpose of this table
 248     // is to keep the classes from being GC'ed until the loader is GC'ed.
 249     private final Vector<Class<?>> classes = new Vector<>();
 250 
 251     // The "default" domain. Set as the default ProtectionDomain on newly
 252     // created classes.
 253     private final ProtectionDomain defaultDomain =
 254         new ProtectionDomain(new CodeSource(null, (Certificate[]) null),
 255                              null, this, null);
 256 
 257     // The initiating protection domains for all classes loaded by this loader
 258     private final Set<ProtectionDomain> domains;
 259 
 260     // Invoked by the VM to record every loaded class with this loader.
 261     void addClass(Class<?> c) {
 262         classes.addElement(c);
 263     }
 264 
 265     // The packages defined in this class loader.  Each package name is mapped
 266     // to its corresponding Package object.
 267     // @GuardedBy("itself")
 268     private final HashMap<String, Package> packages = new HashMap<>();
 269 
 270     private static Void checkCreateClassLoader() {
 271         SecurityManager security = System.getSecurityManager();
 272         if (security != null) {
 273             security.checkCreateClassLoader();
 274         }
 275         return null;
 276     }
 277 
 278     private ClassLoader(Void unused, ClassLoader parent) {
 279         this.parent = parent;
 280         if (ParallelLoaders.isRegistered(this.getClass())) {
 281             parallelLockMap = new ConcurrentHashMap<>();


 385      * <p> Unless overridden, this method synchronizes on the result of
 386      * {@link #getClassLoadingLock <tt>getClassLoadingLock</tt>} method
 387      * during the entire class loading process.
 388      *
 389      * @param  name
 390      *         The <a href="#name">binary name</a> of the class
 391      *
 392      * @param  resolve
 393      *         If <tt>true</tt> then resolve the class
 394      *
 395      * @return  The resulting <tt>Class</tt> object
 396      *
 397      * @throws  ClassNotFoundException
 398      *          If the class could not be found
 399      */
 400     protected Class<?> loadClass(String name, boolean resolve)
 401         throws ClassNotFoundException
 402     {
 403         synchronized (getClassLoadingLock(name)) {
 404             // First, check if the class has already been loaded
 405             Class<?> c = findLoadedClass(name);
 406             if (c == null) {
 407                 long t0 = System.nanoTime();
 408                 try {
 409                     if (parent != null) {
 410                         c = parent.loadClass(name, false);
 411                     } else {
 412                         c = findBootstrapClassOrNull(name);
 413                     }
 414                 } catch (ClassNotFoundException e) {
 415                     // ClassNotFoundException thrown if class not found
 416                     // from the non-null parent class loader
 417                 }
 418 
 419                 if (c == null) {
 420                     // If still not found, then invoke findClass in order
 421                     // to find the class.
 422                     long t1 = System.nanoTime();
 423                     c = findClass(name);
 424 
 425                     // this is the defining class loader; record the stats


 451      * @throws NullPointerException
 452      *         If registered as parallel capable and <tt>className</tt> is null
 453      *
 454      * @see #loadClass(String, boolean)
 455      *
 456      * @since  1.7
 457      */
 458     protected Object getClassLoadingLock(String className) {
 459         Object lock = this;
 460         if (parallelLockMap != null) {
 461             Object newLock = new Object();
 462             lock = parallelLockMap.putIfAbsent(className, newLock);
 463             if (lock == null) {
 464                 lock = newLock;
 465             }
 466         }
 467         return lock;
 468     }
 469 
 470     // This method is invoked by the virtual machine to load a class.
 471     private Class<?> loadClassInternal(String name)
 472         throws ClassNotFoundException
 473     {
 474         // For backward compatibility, explicitly lock on 'this' when
 475         // the current class loader is not parallel capable.
 476         if (parallelLockMap == null) {
 477             synchronized (this) {
 478                  return loadClass(name);
 479             }
 480         } else {
 481             return loadClass(name);
 482         }
 483     }
 484 
 485     // Invoked by the VM after loading class with this loader.
 486     private void checkPackageAccess(Class<?> cls, ProtectionDomain pd) {
 487         final SecurityManager sm = System.getSecurityManager();
 488         if (sm != null) {
 489             final String name = cls.getName();
 490             final int i = name.lastIndexOf('.');
 491             if (i != -1) {
 492                 AccessController.doPrivileged(new PrivilegedAction<Void>() {
 493                     public Void run() {
 494                         sm.checkPackageAccess(name.substring(0, i));
 495                         return null;
 496                     }
 497                 }, new AccessControlContext(new ProtectionDomain[] {pd}));
 498             }
 499         }
 500         domains.add(pd);
 501     }
 502 
 503     /**
 504      * Finds the class with the specified <a href="#name">binary name</a>.
 505      * This method should be overridden by class loader implementations that
 506      * follow the delegation model for loading classes, and will be invoked by


 652         }
 653         if (pd == null) {
 654             pd = defaultDomain;
 655         }
 656 
 657         if (name != null) checkCerts(name, pd.getCodeSource());
 658 
 659         return pd;
 660     }
 661 
 662     private String defineClassSourceLocation(ProtectionDomain pd)
 663     {
 664         CodeSource cs = pd.getCodeSource();
 665         String source = null;
 666         if (cs != null && cs.getLocation() != null) {
 667             source = cs.getLocation().toString();
 668         }
 669         return source;
 670     }
 671 
 672     private Class<?> defineTransformedClass(String name, byte[] b, int off, int len,
 673                                             ProtectionDomain pd,
 674                                             ClassFormatError cfe, String source)
 675       throws ClassFormatError
 676     {
 677         // Class format error - try to transform the bytecode and
 678         // define the class again
 679         //
 680         ClassFileTransformer[] transformers =
 681             ClassFileTransformer.getTransformers();
 682         Class<?> c = null;
 683 
 684         if (transformers != null) {
 685             for (ClassFileTransformer transformer : transformers) {
 686                 try {
 687                     // Transform byte code using transformer
 688                     byte[] tb = transformer.transform(b, off, len);
 689                     c = defineClass1(name, tb, 0, tb.length,
 690                                      pd, source);
 691                     break;
 692                 } catch (ClassFormatError cfe2)     {
 693                     // If ClassFormatError occurs, try next transformer
 694                 }
 695             }
 696         }
 697 
 698         // Rethrow original ClassFormatError if unable to transform
 699         // bytecode to well-formed
 700         //
 701         if (c == null)
 702             throw cfe;
 703 
 704         return c;
 705     }
 706 
 707     private void postDefineClass(Class<?> c, ProtectionDomain pd)
 708     {
 709         if (pd.getCodeSource() != null) {
 710             Certificate certs[] = pd.getCodeSource().getCertificates();
 711             if (certs != null)
 712                 setSigners(c, certs);
 713         }
 714     }
 715 
 716     /**
 717      * Converts an array of bytes into an instance of class <tt>Class</tt>,
 718      * with an optional <tt>ProtectionDomain</tt>.  If the domain is
 719      * <tt>null</tt>, then a default domain will be assigned to the class as
 720      * specified in the documentation for {@link #defineClass(String, byte[],
 721      * int, int)}.  Before the class can be used it must be resolved.
 722      *
 723      * <p> The first class defined in a package determines the exact set of
 724      * certificates that all subsequent classes defined in that package must
 725      * contain.  The set of certificates for a class is obtained from the
 726      * {@link java.security.CodeSource <tt>CodeSource</tt>} within the
 727      * <tt>ProtectionDomain</tt> of the class.  Any classes added to that


 767      * @throws  NoClassDefFoundError
 768      *          If <tt>name</tt> is not equal to the <a href="#name">binary
 769      *          name</a> of the class specified by <tt>b</tt>
 770      *
 771      * @throws  IndexOutOfBoundsException
 772      *          If either <tt>off</tt> or <tt>len</tt> is negative, or if
 773      *          <tt>off+len</tt> is greater than <tt>b.length</tt>.
 774      *
 775      * @throws  SecurityException
 776      *          If an attempt is made to add this class to a package that
 777      *          contains classes that were signed by a different set of
 778      *          certificates than this class, or if <tt>name</tt> begins with
 779      *          "<tt>java.</tt>".
 780      */
 781     protected final Class<?> defineClass(String name, byte[] b, int off, int len,
 782                                          ProtectionDomain protectionDomain)
 783         throws ClassFormatError
 784     {
 785         protectionDomain = preDefineClass(name, protectionDomain);
 786 
 787         Class<?> c = null;
 788         String source = defineClassSourceLocation(protectionDomain);
 789 
 790         try {
 791             c = defineClass1(name, b, off, len, protectionDomain, source);
 792         } catch (ClassFormatError cfe) {
 793             c = defineTransformedClass(name, b, off, len, protectionDomain, cfe,
 794                                        source);
 795         }
 796 
 797         postDefineClass(c, protectionDomain);
 798         return c;
 799     }
 800 
 801     /**
 802      * Converts a {@link java.nio.ByteBuffer <tt>ByteBuffer</tt>}
 803      * into an instance of class <tt>Class</tt>,
 804      * with an optional <tt>ProtectionDomain</tt>.  If the domain is
 805      * <tt>null</tt>, then a default domain will be assigned to the class as
 806      * specified in the documentation for {@link #defineClass(String, byte[],
 807      * int, int)}.  Before the class can be used it must be resolved.


 865         throws ClassFormatError
 866     {
 867         int len = b.remaining();
 868 
 869         // Use byte[] if not a direct ByteBufer:
 870         if (!b.isDirect()) {
 871             if (b.hasArray()) {
 872                 return defineClass(name, b.array(),
 873                                    b.position() + b.arrayOffset(), len,
 874                                    protectionDomain);
 875             } else {
 876                 // no array, or read-only array
 877                 byte[] tb = new byte[len];
 878                 b.get(tb);  // get bytes out of byte buffer.
 879                 return defineClass(name, tb, 0, len, protectionDomain);
 880             }
 881         }
 882 
 883         protectionDomain = preDefineClass(name, protectionDomain);
 884 
 885         Class<?> c = null;
 886         String source = defineClassSourceLocation(protectionDomain);
 887 
 888         try {
 889             c = defineClass2(name, b, b.position(), len, protectionDomain,
 890                              source);
 891         } catch (ClassFormatError cfe) {
 892             byte[] tb = new byte[len];
 893             b.get(tb);  // get bytes out of byte buffer.
 894             c = defineTransformedClass(name, tb, 0, len, protectionDomain, cfe,
 895                                        source);
 896         }
 897 
 898         postDefineClass(c, protectionDomain);
 899         return c;
 900     }
 901 
 902     private native Class<?> defineClass0(String name, byte[] b, int off, int len,
 903                                          ProtectionDomain pd);
 904 
 905     private native Class<?> defineClass1(String name, byte[] b, int off, int len,
 906                                          ProtectionDomain pd, String source);
 907 
 908     private native Class<?> defineClass2(String name, java.nio.ByteBuffer b,
 909                                          int off, int len, ProtectionDomain pd,
 910                                          String source);
 911 
 912     // true if the name is null or has the potential to be a valid binary name
 913     private boolean checkName(String name) {
 914         if ((name == null) || (name.length() == 0))
 915             return true;
 916         if ((name.indexOf('/') != -1)
 917             || (!VM.allowArraySyntax() && (name.charAt(0) == '[')))
 918             return false;
 919         return true;
 920     }
 921 
 922     private void checkCerts(String name, CodeSource cs) {
 923         int i = name.lastIndexOf('.');
 924         String pname = (i == -1) ? "" : name.substring(0, i);
 925 
 926         Certificate[] certs = null;
 927         if (cs != null) {
 928             certs = cs.getCertificates();


 993     /**
 994      * Links the specified class.  This (misleadingly named) method may be
 995      * used by a class loader to link a class.  If the class <tt>c</tt> has
 996      * already been linked, then this method simply returns. Otherwise, the
 997      * class is linked as described in the "Execution" chapter of
 998      * <cite>The Java&trade; Language Specification</cite>.
 999      * </p>
1000      *
1001      * @param  c
1002      *         The class to link
1003      *
1004      * @throws  NullPointerException
1005      *          If <tt>c</tt> is <tt>null</tt>.
1006      *
1007      * @see  #defineClass(String, byte[], int, int)
1008      */
1009     protected final void resolveClass(Class<?> c) {
1010         resolveClass0(c);
1011     }
1012 
1013     private native void resolveClass0(Class<?> c);
1014 
1015     /**
1016      * Finds a class with the specified <a href="#name">binary name</a>,
1017      * loading it if necessary.
1018      *
1019      * <p> This method loads the class through the system class loader (see
1020      * {@link #getSystemClassLoader()}).  The <tt>Class</tt> object returned
1021      * might have more than one <tt>ClassLoader</tt> associated with it.
1022      * Subclasses of <tt>ClassLoader</tt> need not usually invoke this method,
1023      * because most class loaders need to override just {@link
1024      * #findClass(String)}.  </p>
1025      *
1026      * @param  name
1027      *         The <a href="#name">binary name</a> of the class
1028      *
1029      * @return  The <tt>Class</tt> object for the specified <tt>name</tt>
1030      *
1031      * @throws  ClassNotFoundException
1032      *          If the class could not be found
1033      *
1034      * @see  #ClassLoader(ClassLoader)
1035      * @see  #getParent()
1036      */
1037     protected final Class<?> findSystemClass(String name)
1038         throws ClassNotFoundException
1039     {
1040         ClassLoader system = getSystemClassLoader();
1041         if (system == null) {
1042             if (!checkName(name))
1043                 throw new ClassNotFoundException(name);
1044             Class<?> cls = findBootstrapClass(name);
1045             if (cls == null) {
1046                 throw new ClassNotFoundException(name);
1047             }
1048             return cls;
1049         }
1050         return system.loadClass(name);
1051     }
1052 
1053     /**
1054      * Returns a class loaded by the bootstrap class loader;
1055      * or return null if not found.
1056      */
1057     private Class<?> findBootstrapClassOrNull(String name)
1058     {
1059         if (!checkName(name)) return null;
1060 
1061         return findBootstrapClass(name);
1062     }
1063 
1064     // return null if not found
1065     private native Class<?> findBootstrapClass(String name);
1066 
1067     /**
1068      * Returns the class with the given <a href="#name">binary name</a> if this
1069      * loader has been recorded by the Java virtual machine as an initiating
1070      * loader of a class with that <a href="#name">binary name</a>.  Otherwise
1071      * <tt>null</tt> is returned.  </p>
1072      *
1073      * @param  name
1074      *         The <a href="#name">binary name</a> of the class
1075      *
1076      * @return  The <tt>Class</tt> object, or <tt>null</tt> if the class has
1077      *          not been loaded
1078      *
1079      * @since  1.1
1080      */
1081     protected final Class<?> findLoadedClass(String name) {
1082         if (!checkName(name))
1083             return null;
1084         return findLoadedClass0(name);
1085     }
1086 
1087     private native final Class<?> findLoadedClass0(String name);
1088 
1089     /**
1090      * Sets the signers of a class.  This should be invoked after defining a
1091      * class.  </p>
1092      *
1093      * @param  c
1094      *         The <tt>Class</tt> object
1095      *
1096      * @param  signers
1097      *         The signers for the class
1098      *
1099      * @since  1.1
1100      */
1101     protected final void setSigners(Class<?> c, Object[] signers) {
1102         c.setSigners(signers);
1103     }
1104 
1105 
1106     // -- Resource --
1107 


1511 
1512     // Returns true if the specified class loader can be found in this class
1513     // loader's delegation chain.
1514     boolean isAncestor(ClassLoader cl) {
1515         ClassLoader acl = this;
1516         do {
1517             acl = acl.parent;
1518             if (cl == acl) {
1519                 return true;
1520             }
1521         } while (acl != null);
1522         return false;
1523     }
1524 
1525     // Returns the invoker's class loader, or null if none.
1526     // NOTE: This must always be invoked when there is exactly one intervening
1527     // frame from the core libraries on the stack between this method's
1528     // invocation and the desired invoker.
1529     static ClassLoader getCallerClassLoader() {
1530         // NOTE use of more generic Reflection.getCallerClass()
1531         Class<?> caller = Reflection.getCallerClass(3);
1532         // This can be null if the VM is requesting it
1533         if (caller == null) {
1534             return null;
1535         }
1536         // Circumvent security check since this is package-private
1537         return caller.getClassLoader0();
1538     }
1539 
1540     // The class loader for the system
1541     // @GuardedBy("ClassLoader.class")
1542     private static ClassLoader scl;
1543 
1544     // Set to true once the system class loader has been set
1545     // @GuardedBy("ClassLoader.class")
1546     private static boolean sclSet;
1547 
1548 
1549     // -- Package --
1550 
1551     /**


1705      * Every classloader contains a vector of loaded native libraries in the
1706      * private field <tt>nativeLibraries</tt>.  The native libraries loaded
1707      * into the system are entered into the <tt>systemNativeLibraries</tt>
1708      * vector.
1709      *
1710      * <p> Every native library requires a particular version of JNI. This is
1711      * denoted by the private <tt>jniVersion</tt> field.  This field is set by
1712      * the VM when it loads the library, and used by the VM to pass the correct
1713      * version of JNI to the native methods.  </p>
1714      *
1715      * @see      ClassLoader
1716      * @since    1.2
1717      */
1718     static class NativeLibrary {
1719         // opaque handle to native library, used in native code.
1720         long handle;
1721         // the version of JNI environment the native library requires.
1722         private int jniVersion;
1723         // the class from which the library is loaded, also indicates
1724         // the loader this native library belongs.
1725         private Class<?> fromClass;
1726         // the canonicalized name of the native library.
1727         String name;
1728 
1729         native void load(String name);
1730         native long find(String name);
1731         native void unload();
1732 
1733         public NativeLibrary(Class<?> fromClass, String name) {
1734             this.name = name;
1735             this.fromClass = fromClass;
1736         }
1737 
1738         protected void finalize() {
1739             synchronized (loadedLibraryNames) {
1740                 if (fromClass.getClassLoader() != null && handle != 0) {
1741                     /* remove the native library name */
1742                     int size = loadedLibraryNames.size();
1743                     for (int i = 0; i < size; i++) {
1744                         if (name.equals(loadedLibraryNames.elementAt(i))) {
1745                             loadedLibraryNames.removeElementAt(i);
1746                             break;
1747                         }
1748                     }
1749                     /* unload the library. */
1750                     ClassLoader.nativeLibraryContext.push(this);
1751                     try {
1752                         unload();
1753                     } finally {
1754                         ClassLoader.nativeLibraryContext.pop();
1755                     }
1756                 }
1757             }
1758         }
1759         // Invoked in the VM to determine the context class in
1760         // JNI_Load/JNI_Unload
1761         static Class<?> getFromClass() {
1762             return ClassLoader.nativeLibraryContext.peek().fromClass;
1763         }
1764     }
1765 
1766     // All native library names we've loaded.
1767     private static Vector<String> loadedLibraryNames = new Vector<>();
1768 
1769     // Native libraries belonging to system classes.
1770     private static Vector<NativeLibrary> systemNativeLibraries
1771         = new Vector<>();
1772 
1773     // Native libraries associated with the class loader.
1774     private Vector<NativeLibrary> nativeLibraries = new Vector<>();
1775 
1776     // native libraries being loaded/unloaded.
1777     private static Stack<NativeLibrary> nativeLibraryContext = new Stack<>();
1778 
1779     // The paths searched for libraries
1780     private static String usr_paths[];
1781     private static String sys_paths[];


1796         // allocate the array of paths - n :'s = n + 1 path elements
1797         String[] paths = new String[n + 1];
1798 
1799         // Fill the array with paths from the ldpath
1800         n = i = 0;
1801         j = ldpath.indexOf(ps);
1802         while (j >= 0) {
1803             if (j - i > 0) {
1804                 paths[n++] = ldpath.substring(i, j);
1805             } else if (j - i == 0) {
1806                 paths[n++] = ".";
1807             }
1808             i = j + 1;
1809             j = ldpath.indexOf(ps, i);
1810         }
1811         paths[n] = ldpath.substring(i, ldlen);
1812         return paths;
1813     }
1814 
1815     // Invoked in the java.lang.Runtime class to implement load and loadLibrary.
1816     static void loadLibrary(Class<?> fromClass, String name,
1817                             boolean isAbsolute) {
1818         ClassLoader loader =
1819             (fromClass == null) ? null : fromClass.getClassLoader();
1820         if (sys_paths == null) {
1821             usr_paths = initializePath("java.library.path");
1822             sys_paths = initializePath("sun.boot.library.path");
1823         }
1824         if (isAbsolute) {
1825             if (loadLibrary0(fromClass, new File(name))) {
1826                 return;
1827             }
1828             throw new UnsatisfiedLinkError("Can't load library: " + name);
1829         }
1830         if (loader != null) {
1831             String libfilename = loader.findLibrary(name);
1832             if (libfilename != null) {
1833                 File libfile = new File(libfilename);
1834                 if (!libfile.isAbsolute()) {
1835                     throw new UnsatisfiedLinkError(
1836     "ClassLoader.findLibrary failed to return an absolute path: " + libfilename);


1843         }
1844         for (int i = 0 ; i < sys_paths.length ; i++) {
1845             File libfile = new File(sys_paths[i], System.mapLibraryName(name));
1846             if (loadLibrary0(fromClass, libfile)) {
1847                 return;
1848             }
1849         }
1850         if (loader != null) {
1851             for (int i = 0 ; i < usr_paths.length ; i++) {
1852                 File libfile = new File(usr_paths[i],
1853                                         System.mapLibraryName(name));
1854                 if (loadLibrary0(fromClass, libfile)) {
1855                     return;
1856                 }
1857             }
1858         }
1859         // Oops, it failed
1860         throw new UnsatisfiedLinkError("no " + name + " in java.library.path");
1861     }
1862 
1863     private static boolean loadLibrary0(Class<?> fromClass, final File file) {
1864         boolean exists = AccessController.doPrivileged(
1865             new PrivilegedAction<Object>() {
1866                 public Object run() {
1867                     return file.exists() ? Boolean.TRUE : null;
1868                 }})
1869             != null;
1870         if (!exists) {
1871             return false;
1872         }
1873         String name;
1874         try {
1875             name = file.getCanonicalPath();
1876         } catch (IOException e) {
1877             return false;
1878         }
1879         ClassLoader loader =
1880             (fromClass == null) ? null : fromClass.getClassLoader();
1881         Vector<NativeLibrary> libs =
1882             loader != null ? loader.nativeLibraries : systemNativeLibraries;
1883         synchronized (libs) {


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 }