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