ClassLoader.java 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152
  1. /* ClassLoader.java -- responsible for loading classes into the VM
  2. Copyright (C) 1998, 1999, 2001, 2002, 2003, 2004, 2005 Free Software Foundation, Inc.
  3. This file is part of GNU Classpath.
  4. GNU Classpath is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; either version 2, or (at your option)
  7. any later version.
  8. GNU Classpath is distributed in the hope that it will be useful, but
  9. WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  11. General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with GNU Classpath; see the file COPYING. If not, write to the
  14. Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
  15. 02110-1301 USA.
  16. Linking this library statically or dynamically with other modules is
  17. making a combined work based on this library. Thus, the terms and
  18. conditions of the GNU General Public License cover the whole
  19. combination.
  20. As a special exception, the copyright holders of this library give you
  21. permission to link this library with independent modules to produce an
  22. executable, regardless of the license terms of these independent
  23. modules, and to copy and distribute the resulting executable under
  24. terms of your choice, provided that you also meet, for each linked
  25. independent module, the terms and conditions of the license of that
  26. module. An independent module is a module which is not derived from
  27. or based on this library. If you modify this library, you may extend
  28. this exception to your version of the library, but you are not
  29. obligated to do so. If you do not wish to do so, delete this
  30. exception statement from your version. */
  31. package java.lang;
  32. import gnu.classpath.SystemProperties;
  33. import gnu.classpath.VMStackWalker;
  34. import gnu.java.util.DoubleEnumeration;
  35. import gnu.java.util.EmptyEnumeration;
  36. import java.io.File;
  37. import java.io.IOException;
  38. import java.io.InputStream;
  39. import java.lang.reflect.Constructor;
  40. import java.net.URL;
  41. import java.net.URLClassLoader;
  42. import java.nio.ByteBuffer;
  43. import java.security.CodeSource;
  44. import java.security.PermissionCollection;
  45. import java.security.Policy;
  46. import java.security.ProtectionDomain;
  47. import java.util.ArrayList;
  48. import java.util.Enumeration;
  49. import java.util.HashMap;
  50. import java.util.Map;
  51. import java.util.StringTokenizer;
  52. /**
  53. * The ClassLoader is a way of customizing the way Java gets its classes
  54. * and loads them into memory. The verifier and other standard Java things
  55. * still run, but the ClassLoader is allowed great flexibility in determining
  56. * where to get the classfiles and when to load and resolve them. For that
  57. * matter, a custom ClassLoader can perform on-the-fly code generation or
  58. * modification!
  59. *
  60. * <p>Every classloader has a parent classloader that is consulted before
  61. * the 'child' classloader when classes or resources should be loaded.
  62. * This is done to make sure that classes can be loaded from an hierarchy of
  63. * multiple classloaders and classloaders do not accidentially redefine
  64. * already loaded classes by classloaders higher in the hierarchy.
  65. *
  66. * <p>The grandparent of all classloaders is the bootstrap classloader, which
  67. * loads all the standard system classes as implemented by GNU Classpath. The
  68. * other special classloader is the system classloader (also called
  69. * application classloader) that loads all classes from the CLASSPATH
  70. * (<code>java.class.path</code> system property). The system classloader
  71. * is responsible for finding the application classes from the classpath,
  72. * and delegates all requests for the standard library classes to its parent
  73. * the bootstrap classloader. Most programs will load all their classes
  74. * through the system classloaders.
  75. *
  76. * <p>The bootstrap classloader in GNU Classpath is implemented as a couple of
  77. * static (native) methods on the package private class
  78. * <code>java.lang.VMClassLoader</code>, the system classloader is an
  79. * anonymous inner class of ClassLoader and a subclass of
  80. * <code>java.net.URLClassLoader</code>.
  81. *
  82. * <p>Users of a <code>ClassLoader</code> will normally just use the methods
  83. * <ul>
  84. * <li> <code>loadClass()</code> to load a class.</li>
  85. * <li> <code>getResource()</code> or <code>getResourceAsStream()</code>
  86. * to access a resource.</li>
  87. * <li> <code>getResources()</code> to get an Enumeration of URLs to all
  88. * the resources provided by the classloader and its parents with the
  89. * same name.</li>
  90. * </ul>
  91. *
  92. * <p>Subclasses should implement the methods
  93. * <ul>
  94. * <li> <code>findClass()</code> which is called by <code>loadClass()</code>
  95. * when the parent classloader cannot provide a named class.</li>
  96. * <li> <code>findResource()</code> which is called by
  97. * <code>getResource()</code> when the parent classloader cannot provide
  98. * a named resource.</li>
  99. * <li> <code>findResources()</code> which is called by
  100. * <code>getResource()</code> to combine all the resources with the
  101. * same name from the classloader and its parents.</li>
  102. * <li> <code>findLibrary()</code> which is called by
  103. * <code>Runtime.loadLibrary()</code> when a class defined by the
  104. * classloader wants to load a native library.</li>
  105. * </ul>
  106. *
  107. * @author John Keiser
  108. * @author Mark Wielaard
  109. * @author Eric Blake (ebb9@email.byu.edu)
  110. * @see Class
  111. * @since 1.0
  112. */
  113. public abstract class ClassLoader
  114. {
  115. /**
  116. * All packages defined by this classloader. It is not private in order to
  117. * allow native code (and trusted subclasses) access to this field.
  118. */
  119. final HashMap<String, Package> definedPackages = new HashMap<String, Package>();
  120. /**
  121. * The classloader that is consulted before this classloader.
  122. * If null then the parent is the bootstrap classloader.
  123. */
  124. private final ClassLoader parent;
  125. /**
  126. * This is true if this classloader was successfully initialized.
  127. * This flag is needed to avoid a class loader attack: even if the
  128. * security manager rejects an attempt to create a class loader, the
  129. * malicious class could have a finalize method which proceeds to
  130. * define classes.
  131. */
  132. private final boolean initialized;
  133. static class StaticData
  134. {
  135. /**
  136. * The System Class Loader (a.k.a. Application Class Loader). The one
  137. * returned by ClassLoader.getSystemClassLoader.
  138. */
  139. static final ClassLoader systemClassLoader =
  140. VMClassLoader.getSystemClassLoader();
  141. static
  142. {
  143. // Find out if we have to install a default security manager. Note that
  144. // this is done here because we potentially need the system class loader
  145. // to load the security manager and note also that we don't need the
  146. // security manager until the system class loader is created.
  147. // If the runtime chooses to use a class loader that doesn't have the
  148. // system class loader as its parent, it is responsible for setting
  149. // up a security manager before doing so.
  150. String secman = SystemProperties.getProperty("java.security.manager");
  151. if (secman != null && SecurityManager.current == null)
  152. {
  153. if (secman.equals("") || secman.equals("default"))
  154. {
  155. SecurityManager.current = new SecurityManager();
  156. }
  157. else
  158. {
  159. try
  160. {
  161. Class cl = Class.forName(secman, false, StaticData.systemClassLoader);
  162. SecurityManager.current = (SecurityManager)cl.newInstance();
  163. }
  164. catch (Exception x)
  165. {
  166. throw (InternalError)
  167. new InternalError("Unable to create SecurityManager")
  168. .initCause(x);
  169. }
  170. }
  171. }
  172. }
  173. /**
  174. * The default protection domain, used when defining a class with a null
  175. * parameter for the domain.
  176. */
  177. static final ProtectionDomain defaultProtectionDomain;
  178. static
  179. {
  180. CodeSource cs = new CodeSource(null, null);
  181. PermissionCollection perm = Policy.getPolicy().getPermissions(cs);
  182. defaultProtectionDomain = new ProtectionDomain(cs, perm);
  183. }
  184. /**
  185. * The command-line state of the package assertion status overrides. This
  186. * map is never modified, so it does not need to be synchronized.
  187. */
  188. // Package visible for use by Class.
  189. static final Map systemPackageAssertionStatus
  190. = VMClassLoader.packageAssertionStatus();
  191. /**
  192. * The command-line state of the class assertion status overrides. This
  193. * map is never modified, so it does not need to be synchronized.
  194. */
  195. // Package visible for use by Class.
  196. static final Map systemClassAssertionStatus
  197. = VMClassLoader.classAssertionStatus();
  198. }
  199. /**
  200. * The desired assertion status of classes loaded by this loader, if not
  201. * overridden by package or class instructions.
  202. */
  203. // Package visible for use by Class.
  204. boolean defaultAssertionStatus = VMClassLoader.defaultAssertionStatus();
  205. /**
  206. * The map of package assertion status overrides, or null if no package
  207. * overrides have been specified yet. The values of the map should be
  208. * Boolean.TRUE or Boolean.FALSE, and the unnamed package is represented
  209. * by the null key. This map must be synchronized on this instance.
  210. */
  211. // Package visible for use by Class.
  212. Map<String, Boolean> packageAssertionStatus;
  213. /**
  214. * The map of class assertion status overrides, or null if no class
  215. * overrides have been specified yet. The values of the map should be
  216. * Boolean.TRUE or Boolean.FALSE. This map must be synchronized on this
  217. * instance.
  218. */
  219. // Package visible for use by Class.
  220. Map<String, Boolean> classAssertionStatus;
  221. /**
  222. * VM private data.
  223. */
  224. transient Object vmdata;
  225. /**
  226. * Create a new ClassLoader with as parent the system classloader. There
  227. * may be a security check for <code>checkCreateClassLoader</code>.
  228. *
  229. * @throws SecurityException if the security check fails
  230. */
  231. protected ClassLoader() throws SecurityException
  232. {
  233. this(StaticData.systemClassLoader);
  234. }
  235. /**
  236. * Create a new ClassLoader with the specified parent. The parent will
  237. * be consulted when a class or resource is requested through
  238. * <code>loadClass()</code> or <code>getResource()</code>. Only when the
  239. * parent classloader cannot provide the requested class or resource the
  240. * <code>findClass()</code> or <code>findResource()</code> method
  241. * of this classloader will be called. There may be a security check for
  242. * <code>checkCreateClassLoader</code>.
  243. *
  244. * @param parent the classloader's parent, or null for the bootstrap
  245. * classloader
  246. * @throws SecurityException if the security check fails
  247. * @since 1.2
  248. */
  249. protected ClassLoader(ClassLoader parent)
  250. {
  251. // May we create a new classloader?
  252. SecurityManager sm = SecurityManager.current;
  253. if (sm != null)
  254. sm.checkCreateClassLoader();
  255. this.parent = parent;
  256. this.initialized = true;
  257. }
  258. /**
  259. * Load a class using this ClassLoader or its parent, without resolving
  260. * it. Calls <code>loadClass(name, false)</code>.
  261. *
  262. * <p>Subclasses should not override this method but should override
  263. * <code>findClass()</code> which is called by this method.</p>
  264. *
  265. * @param name the name of the class relative to this ClassLoader
  266. * @return the loaded class
  267. * @throws ClassNotFoundException if the class cannot be found
  268. */
  269. public Class<?> loadClass(String name) throws ClassNotFoundException
  270. {
  271. return loadClass(name, false);
  272. }
  273. /**
  274. * Load a class using this ClassLoader or its parent, possibly resolving
  275. * it as well using <code>resolveClass()</code>. It first tries to find
  276. * out if the class has already been loaded through this classloader by
  277. * calling <code>findLoadedClass()</code>. Then it calls
  278. * <code>loadClass()</code> on the parent classloader (or when there is
  279. * no parent it uses the VM bootclassloader). If the class is still
  280. * not loaded it tries to create a new class by calling
  281. * <code>findClass()</code>. Finally when <code>resolve</code> is
  282. * <code>true</code> it also calls <code>resolveClass()</code> on the
  283. * newly loaded class.
  284. *
  285. * <p>Subclasses should not override this method but should override
  286. * <code>findClass()</code> which is called by this method.</p>
  287. *
  288. * @param name the fully qualified name of the class to load
  289. * @param resolve whether or not to resolve the class
  290. * @return the loaded class
  291. * @throws ClassNotFoundException if the class cannot be found
  292. */
  293. protected synchronized Class<?> loadClass(String name, boolean resolve)
  294. throws ClassNotFoundException
  295. {
  296. // Have we already loaded this class?
  297. Class<?> c = findLoadedClass(name);
  298. if (c == null)
  299. {
  300. // Can the class be loaded by a parent?
  301. try
  302. {
  303. if (parent == null)
  304. {
  305. c = VMClassLoader.loadClass(name, resolve);
  306. if (c != null)
  307. return c;
  308. }
  309. else
  310. {
  311. return parent.loadClass(name, resolve);
  312. }
  313. }
  314. catch (ClassNotFoundException e)
  315. {
  316. }
  317. // Still not found, we have to do it ourself.
  318. c = findClass(name);
  319. }
  320. if (resolve)
  321. resolveClass(c);
  322. return c;
  323. }
  324. /**
  325. * Called for every class name that is needed but has not yet been
  326. * defined by this classloader or one of its parents. It is called by
  327. * <code>loadClass()</code> after both <code>findLoadedClass()</code> and
  328. * <code>parent.loadClass()</code> couldn't provide the requested class.
  329. *
  330. * <p>The default implementation throws a
  331. * <code>ClassNotFoundException</code>. Subclasses should override this
  332. * method. An implementation of this method in a subclass should get the
  333. * class bytes of the class (if it can find them), if the package of the
  334. * requested class doesn't exist it should define the package and finally
  335. * it should call define the actual class. It does not have to resolve the
  336. * class. It should look something like the following:<br>
  337. *
  338. * <pre>
  339. * // Get the bytes that describe the requested class
  340. * byte[] classBytes = classLoaderSpecificWayToFindClassBytes(name);
  341. * // Get the package name
  342. * int lastDot = name.lastIndexOf('.');
  343. * if (lastDot != -1)
  344. * {
  345. * String packageName = name.substring(0, lastDot);
  346. * // Look if the package already exists
  347. * if (getPackage(packageName) == null)
  348. * {
  349. * // define the package
  350. * definePackage(packageName, ...);
  351. * }
  352. * }
  353. * // Define and return the class
  354. * return defineClass(name, classBytes, 0, classBytes.length);
  355. * </pre>
  356. *
  357. * <p><code>loadClass()</code> makes sure that the <code>Class</code>
  358. * returned by <code>findClass()</code> will later be returned by
  359. * <code>findLoadedClass()</code> when the same class name is requested.
  360. *
  361. * @param name class name to find (including the package name)
  362. * @return the requested Class
  363. * @throws ClassNotFoundException when the class can not be found
  364. * @since 1.2
  365. */
  366. protected Class<?> findClass(String name) throws ClassNotFoundException
  367. {
  368. throw new ClassNotFoundException(name);
  369. }
  370. /**
  371. * Helper to define a class using a string of bytes. This version is not
  372. * secure.
  373. *
  374. * @param data the data representing the classfile, in classfile format
  375. * @param offset the offset into the data where the classfile starts
  376. * @param len the length of the classfile data in the array
  377. * @return the class that was defined
  378. * @throws ClassFormatError if data is not in proper classfile format
  379. * @throws IndexOutOfBoundsException if offset or len is negative, or
  380. * offset + len exceeds data
  381. * @deprecated use {@link #defineClass(String, byte[], int, int)} instead
  382. */
  383. protected final Class<?> defineClass(byte[] data, int offset, int len)
  384. throws ClassFormatError
  385. {
  386. return defineClass(null, data, offset, len);
  387. }
  388. /**
  389. * Helper to define a class using a string of bytes without a
  390. * ProtectionDomain. Subclasses should call this method from their
  391. * <code>findClass()</code> implementation. The name should use '.'
  392. * separators, and discard the trailing ".class". The default protection
  393. * domain has the permissions of
  394. * <code>Policy.getPolicy().getPermissions(new CodeSource(null, null))</code>.
  395. *
  396. * @param name the name to give the class, or null if unknown
  397. * @param data the data representing the classfile, in classfile format
  398. * @param offset the offset into the data where the classfile starts
  399. * @param len the length of the classfile data in the array
  400. * @return the class that was defined
  401. * @throws ClassFormatError if data is not in proper classfile format
  402. * @throws IndexOutOfBoundsException if offset or len is negative, or
  403. * offset + len exceeds data
  404. * @throws SecurityException if name starts with "java."
  405. * @since 1.1
  406. */
  407. protected final Class<?> defineClass(String name, byte[] data, int offset,
  408. int len) throws ClassFormatError
  409. {
  410. return defineClass(name, data, offset, len, null);
  411. }
  412. /**
  413. * Helper to define a class using a string of bytes. Subclasses should call
  414. * this method from their <code>findClass()</code> implementation. If the
  415. * domain is null, the default of
  416. * <code>Policy.getPolicy().getPermissions(new CodeSource(null, null))</code>
  417. * is used. Once a class has been defined in a package, all further classes
  418. * in that package must have the same set of certificates or a
  419. * SecurityException is thrown.
  420. *
  421. * @param name the name to give the class. null if unknown
  422. * @param data the data representing the classfile, in classfile format
  423. * @param offset the offset into the data where the classfile starts
  424. * @param len the length of the classfile data in the array
  425. * @param domain the ProtectionDomain to give to the class, null for the
  426. * default protection domain
  427. * @return the class that was defined
  428. * @throws ClassFormatError if data is not in proper classfile format
  429. * @throws IndexOutOfBoundsException if offset or len is negative, or
  430. * offset + len exceeds data
  431. * @throws SecurityException if name starts with "java.", or if certificates
  432. * do not match up
  433. * @since 1.2
  434. */
  435. protected final synchronized Class<?> defineClass(String name, byte[] data,
  436. int offset, int len,
  437. ProtectionDomain domain)
  438. throws ClassFormatError
  439. {
  440. checkInitialized();
  441. if (domain == null)
  442. domain = StaticData.defaultProtectionDomain;
  443. return VMClassLoader.defineClassWithTransformers(this, name, data, offset,
  444. len, domain);
  445. }
  446. /**
  447. * Helper to define a class using the contents of a byte buffer. If
  448. * the domain is null, the default of
  449. * <code>Policy.getPolicy().getPermissions(new CodeSource(null,
  450. * null))</code> is used. Once a class has been defined in a
  451. * package, all further classes in that package must have the same
  452. * set of certificates or a SecurityException is thrown.
  453. *
  454. * @param name the name to give the class. null if unknown
  455. * @param buf a byte buffer containing bytes that form a class.
  456. * @param domain the ProtectionDomain to give to the class, null for the
  457. * default protection domain
  458. * @return the class that was defined
  459. * @throws ClassFormatError if data is not in proper classfile format
  460. * @throws NoClassDefFoundError if the supplied name is not the same as
  461. * the one specified by the byte buffer.
  462. * @throws SecurityException if name starts with "java.", or if certificates
  463. * do not match up
  464. * @since 1.5
  465. */
  466. protected final Class<?> defineClass(String name, ByteBuffer buf,
  467. ProtectionDomain domain)
  468. throws ClassFormatError
  469. {
  470. byte[] data = new byte[buf.remaining()];
  471. buf.get(data);
  472. return defineClass(name, data, 0, data.length, domain);
  473. }
  474. /**
  475. * Links the class, if that has not already been done. Linking basically
  476. * resolves all references to other classes made by this class.
  477. *
  478. * @param c the class to resolve
  479. * @throws NullPointerException if c is null
  480. * @throws LinkageError if linking fails
  481. */
  482. protected final void resolveClass(Class<?> c)
  483. {
  484. checkInitialized();
  485. VMClassLoader.resolveClass(c);
  486. }
  487. /**
  488. * Helper to find a Class using the system classloader, possibly loading it.
  489. * A subclass usually does not need to call this, if it correctly
  490. * overrides <code>findClass(String)</code>.
  491. *
  492. * @param name the name of the class to find
  493. * @return the found class
  494. * @throws ClassNotFoundException if the class cannot be found
  495. */
  496. protected final Class<?> findSystemClass(String name)
  497. throws ClassNotFoundException
  498. {
  499. checkInitialized();
  500. return Class.forName(name, false, StaticData.systemClassLoader);
  501. }
  502. /**
  503. * Returns the parent of this classloader. If the parent of this
  504. * classloader is the bootstrap classloader then this method returns
  505. * <code>null</code>. A security check may be performed on
  506. * <code>RuntimePermission("getClassLoader")</code>.
  507. *
  508. * @return the parent <code>ClassLoader</code>
  509. * @throws SecurityException if the security check fails
  510. * @since 1.2
  511. */
  512. public final ClassLoader getParent()
  513. {
  514. // Check if we may return the parent classloader.
  515. SecurityManager sm = SecurityManager.current;
  516. if (sm != null)
  517. {
  518. ClassLoader cl = VMStackWalker.getCallingClassLoader();
  519. if (cl != null && ! cl.isAncestorOf(this))
  520. sm.checkPermission(new RuntimePermission("getClassLoader"));
  521. }
  522. return parent;
  523. }
  524. /**
  525. * Helper to set the signers of a class. This should be called after
  526. * defining the class.
  527. *
  528. * @param c the Class to set signers of
  529. * @param signers the signers to set
  530. * @since 1.1
  531. */
  532. protected final void setSigners(Class<?> c, Object[] signers)
  533. {
  534. checkInitialized();
  535. c.setSigners(signers);
  536. }
  537. /**
  538. * Helper to find an already-loaded class in this ClassLoader.
  539. *
  540. * @param name the name of the class to find
  541. * @return the found Class, or null if it is not found
  542. * @since 1.1
  543. */
  544. protected final synchronized Class<?> findLoadedClass(String name)
  545. {
  546. checkInitialized();
  547. return VMClassLoader.findLoadedClass(this, name);
  548. }
  549. /**
  550. * Get the URL to a resource using this classloader or one of its parents.
  551. * First tries to get the resource by calling <code>getResource()</code>
  552. * on the parent classloader. If the parent classloader returns null then
  553. * it tries finding the resource by calling <code>findResource()</code> on
  554. * this classloader. The resource name should be separated by '/' for path
  555. * elements.
  556. *
  557. * <p>Subclasses should not override this method but should override
  558. * <code>findResource()</code> which is called by this method.
  559. *
  560. * @param name the name of the resource relative to this classloader
  561. * @return the URL to the resource or null when not found
  562. */
  563. public URL getResource(String name)
  564. {
  565. URL result;
  566. if (parent == null)
  567. result = VMClassLoader.getResource(name);
  568. else
  569. result = parent.getResource(name);
  570. if (result == null)
  571. result = findResource(name);
  572. return result;
  573. }
  574. /**
  575. * Returns an Enumeration of all resources with a given name that can
  576. * be found by this classloader and its parents. Certain classloaders
  577. * (such as the URLClassLoader when given multiple jar files) can have
  578. * multiple resources with the same name that come from multiple locations.
  579. * It can also occur that a parent classloader offers a resource with a
  580. * certain name and the child classloader also offers a resource with that
  581. * same name. <code>getResource()</code> only offers the first resource (of the
  582. * parent) with a given name. This method lists all resources with the
  583. * same name. The name should use '/' as path separators.
  584. *
  585. * <p>The Enumeration is created by first calling <code>getResources()</code>
  586. * on the parent classloader and then calling <code>findResources()</code>
  587. * on this classloader.</p>
  588. *
  589. * @param name the resource name
  590. * @return an enumaration of all resources found
  591. * @throws IOException if I/O errors occur in the process
  592. * @since 1.2
  593. * @specnote this was <code>final</code> prior to 1.5
  594. */
  595. public Enumeration<URL> getResources(String name) throws IOException
  596. {
  597. Enumeration<URL> parentResources;
  598. if (parent == null)
  599. parentResources = VMClassLoader.getResources(name);
  600. else
  601. parentResources = parent.getResources(name);
  602. return new DoubleEnumeration<URL>(parentResources, findResources(name));
  603. }
  604. /**
  605. * Called whenever all locations of a named resource are needed.
  606. * It is called by <code>getResources()</code> after it has called
  607. * <code>parent.getResources()</code>. The results are combined by
  608. * the <code>getResources()</code> method.
  609. *
  610. * <p>The default implementation always returns an empty Enumeration.
  611. * Subclasses should override it when they can provide an Enumeration of
  612. * URLs (possibly just one element) to the named resource.
  613. * The first URL of the Enumeration should be the same as the one
  614. * returned by <code>findResource</code>.
  615. *
  616. * @param name the name of the resource to be found
  617. * @return a possibly empty Enumeration of URLs to the named resource
  618. * @throws IOException if I/O errors occur in the process
  619. * @since 1.2
  620. */
  621. protected Enumeration<URL> findResources(String name) throws IOException
  622. {
  623. return new EmptyEnumeration<URL>();
  624. }
  625. /**
  626. * Called whenever a resource is needed that could not be provided by
  627. * one of the parents of this classloader. It is called by
  628. * <code>getResource()</code> after <code>parent.getResource()</code>
  629. * couldn't provide the requested resource.
  630. *
  631. * <p>The default implementation always returns null. Subclasses should
  632. * override this method when they can provide a way to return a URL
  633. * to a named resource.
  634. *
  635. * @param name the name of the resource to be found
  636. * @return a URL to the named resource or null when not found
  637. * @since 1.2
  638. */
  639. protected URL findResource(String name)
  640. {
  641. return null;
  642. }
  643. /**
  644. * Get the URL to a resource using the system classloader.
  645. *
  646. * @param name the name of the resource relative to the system classloader
  647. * @return the URL to the resource
  648. * @since 1.1
  649. */
  650. public static final URL getSystemResource(String name)
  651. {
  652. return StaticData.systemClassLoader.getResource(name);
  653. }
  654. /**
  655. * Get an Enumeration of URLs to resources with a given name using the
  656. * the system classloader. The enumeration firsts lists the resources with
  657. * the given name that can be found by the bootstrap classloader followed
  658. * by the resources with the given name that can be found on the classpath.
  659. *
  660. * @param name the name of the resource relative to the system classloader
  661. * @return an Enumeration of URLs to the resources
  662. * @throws IOException if I/O errors occur in the process
  663. * @since 1.2
  664. */
  665. public static Enumeration<URL> getSystemResources(String name)
  666. throws IOException
  667. {
  668. return StaticData.systemClassLoader.getResources(name);
  669. }
  670. /**
  671. * Get a resource as stream using this classloader or one of its parents.
  672. * First calls <code>getResource()</code> and if that returns a URL to
  673. * the resource then it calls and returns the InputStream given by
  674. * <code>URL.openStream()</code>.
  675. *
  676. * <p>Subclasses should not override this method but should override
  677. * <code>findResource()</code> which is called by this method.
  678. *
  679. * @param name the name of the resource relative to this classloader
  680. * @return an InputStream to the resource, or null
  681. * @since 1.1
  682. */
  683. public InputStream getResourceAsStream(String name)
  684. {
  685. try
  686. {
  687. URL url = getResource(name);
  688. if (url == null)
  689. return null;
  690. return url.openStream();
  691. }
  692. catch (IOException e)
  693. {
  694. return null;
  695. }
  696. }
  697. /**
  698. * Get a resource using the system classloader.
  699. *
  700. * @param name the name of the resource relative to the system classloader
  701. * @return an input stream for the resource, or null
  702. * @since 1.1
  703. */
  704. public static final InputStream getSystemResourceAsStream(String name)
  705. {
  706. try
  707. {
  708. URL url = getSystemResource(name);
  709. if (url == null)
  710. return null;
  711. return url.openStream();
  712. }
  713. catch (IOException e)
  714. {
  715. return null;
  716. }
  717. }
  718. /**
  719. * Returns the system classloader. The system classloader (also called
  720. * the application classloader) is the classloader that is used to
  721. * load the application classes on the classpath (given by the system
  722. * property <code>java.class.path</code>. This is set as the context
  723. * class loader for a thread. The system property
  724. * <code>java.system.class.loader</code>, if defined, is taken to be the
  725. * name of the class to use as the system class loader, which must have
  726. * a public constructor which takes a ClassLoader as a parent. The parent
  727. * class loader passed in the constructor is the default system class
  728. * loader.
  729. *
  730. * <p>Note that this is different from the bootstrap classloader that
  731. * actually loads all the real "system" classes.
  732. *
  733. * <p>A security check will be performed for
  734. * <code>RuntimePermission("getClassLoader")</code> if the calling class
  735. * is not a parent of the system class loader.
  736. *
  737. * @return the system class loader
  738. * @throws SecurityException if the security check fails
  739. * @throws IllegalStateException if this is called recursively
  740. * @throws Error if <code>java.system.class.loader</code> fails to load
  741. * @since 1.2
  742. */
  743. public static ClassLoader getSystemClassLoader()
  744. {
  745. // Check if we may return the system classloader
  746. SecurityManager sm = SecurityManager.current;
  747. if (sm != null)
  748. {
  749. ClassLoader cl = VMStackWalker.getCallingClassLoader();
  750. if (cl != null && cl != StaticData.systemClassLoader)
  751. sm.checkPermission(new RuntimePermission("getClassLoader"));
  752. }
  753. return StaticData.systemClassLoader;
  754. }
  755. /**
  756. * Defines a new package and creates a Package object. The package should
  757. * be defined before any class in the package is defined with
  758. * <code>defineClass()</code>. The package should not yet be defined
  759. * before in this classloader or in one of its parents (which means that
  760. * <code>getPackage()</code> should return <code>null</code>). All
  761. * parameters except the <code>name</code> of the package may be
  762. * <code>null</code>.
  763. *
  764. * <p>Subclasses should call this method from their <code>findClass()</code>
  765. * implementation before calling <code>defineClass()</code> on a Class
  766. * in a not yet defined Package (which can be checked by calling
  767. * <code>getPackage()</code>).
  768. *
  769. * @param name the name of the Package
  770. * @param specTitle the name of the specification
  771. * @param specVendor the name of the specification designer
  772. * @param specVersion the version of this specification
  773. * @param implTitle the name of the implementation
  774. * @param implVendor the vendor that wrote this implementation
  775. * @param implVersion the version of this implementation
  776. * @param sealed if sealed the origin of the package classes
  777. * @return the Package object for the specified package
  778. * @throws IllegalArgumentException if the package name is null or it
  779. * was already defined by this classloader or one of its parents
  780. * @see Package
  781. * @since 1.2
  782. */
  783. protected Package definePackage(String name, String specTitle,
  784. String specVendor, String specVersion,
  785. String implTitle, String implVendor,
  786. String implVersion, URL sealed)
  787. {
  788. if (getPackage(name) != null)
  789. throw new IllegalArgumentException("Package " + name
  790. + " already defined");
  791. Package p = new Package(name, specTitle, specVendor, specVersion,
  792. implTitle, implVendor, implVersion, sealed, this);
  793. synchronized (definedPackages)
  794. {
  795. definedPackages.put(name, p);
  796. }
  797. return p;
  798. }
  799. /**
  800. * Returns the Package object for the requested package name. It returns
  801. * null when the package is not defined by this classloader or one of its
  802. * parents.
  803. *
  804. * @param name the package name to find
  805. * @return the package, if defined
  806. * @since 1.2
  807. */
  808. protected Package getPackage(String name)
  809. {
  810. Package p;
  811. if (parent == null)
  812. p = VMClassLoader.getPackage(name);
  813. else
  814. p = parent.getPackage(name);
  815. if (p == null)
  816. {
  817. synchronized (definedPackages)
  818. {
  819. p = definedPackages.get(name);
  820. }
  821. }
  822. return p;
  823. }
  824. /**
  825. * Returns all Package objects defined by this classloader and its parents.
  826. *
  827. * @return an array of all defined packages
  828. * @since 1.2
  829. */
  830. protected Package[] getPackages()
  831. {
  832. // Get all our packages.
  833. Package[] packages;
  834. synchronized(definedPackages)
  835. {
  836. packages = new Package[definedPackages.size()];
  837. definedPackages.values().toArray(packages);
  838. }
  839. // If we have a parent get all packages defined by our parents.
  840. Package[] parentPackages;
  841. if (parent == null)
  842. parentPackages = VMClassLoader.getPackages();
  843. else
  844. parentPackages = parent.getPackages();
  845. Package[] allPackages = new Package[parentPackages.length
  846. + packages.length];
  847. System.arraycopy(parentPackages, 0, allPackages, 0,
  848. parentPackages.length);
  849. System.arraycopy(packages, 0, allPackages, parentPackages.length,
  850. packages.length);
  851. return allPackages;
  852. }
  853. /**
  854. * Called by <code>Runtime.loadLibrary()</code> to get an absolute path
  855. * to a (system specific) library that was requested by a class loaded
  856. * by this classloader. The default implementation returns
  857. * <code>null</code>. It should be implemented by subclasses when they
  858. * have a way to find the absolute path to a library. If this method
  859. * returns null the library is searched for in the default locations
  860. * (the directories listed in the <code>java.library.path</code> system
  861. * property).
  862. *
  863. * @param name the (system specific) name of the requested library
  864. * @return the full pathname to the requested library, or null
  865. * @see Runtime#loadLibrary(String)
  866. * @since 1.2
  867. */
  868. protected String findLibrary(String name)
  869. {
  870. return null;
  871. }
  872. /**
  873. * Set the default assertion status for classes loaded by this classloader,
  874. * used unless overridden by a package or class request.
  875. *
  876. * @param enabled true to set the default to enabled
  877. * @see #setClassAssertionStatus(String, boolean)
  878. * @see #setPackageAssertionStatus(String, boolean)
  879. * @see #clearAssertionStatus()
  880. * @since 1.4
  881. */
  882. public void setDefaultAssertionStatus(boolean enabled)
  883. {
  884. defaultAssertionStatus = enabled;
  885. }
  886. /**
  887. * Set the default assertion status for packages, used unless overridden
  888. * by a class request. This default also covers subpackages, unless they
  889. * are also specified. The unnamed package should use null for the name.
  890. *
  891. * @param name the package (and subpackages) to affect
  892. * @param enabled true to set the default to enabled
  893. * @see #setDefaultAssertionStatus(boolean)
  894. * @see #setClassAssertionStatus(String, boolean)
  895. * @see #clearAssertionStatus()
  896. * @since 1.4
  897. */
  898. public synchronized void setPackageAssertionStatus(String name,
  899. boolean enabled)
  900. {
  901. if (packageAssertionStatus == null)
  902. packageAssertionStatus
  903. = new HashMap<String, Boolean>(StaticData.systemPackageAssertionStatus);
  904. packageAssertionStatus.put(name, Boolean.valueOf(enabled));
  905. }
  906. /**
  907. * Set the default assertion status for a class. This only affects the
  908. * status of top-level classes, any other string is harmless.
  909. *
  910. * @param name the class to affect
  911. * @param enabled true to set the default to enabled
  912. * @throws NullPointerException if name is null
  913. * @see #setDefaultAssertionStatus(boolean)
  914. * @see #setPackageAssertionStatus(String, boolean)
  915. * @see #clearAssertionStatus()
  916. * @since 1.4
  917. */
  918. public synchronized void setClassAssertionStatus(String name,
  919. boolean enabled)
  920. {
  921. if (classAssertionStatus == null)
  922. classAssertionStatus
  923. = new HashMap<String, Boolean>(StaticData.systemClassAssertionStatus);
  924. // The toString() hack catches null, as required.
  925. classAssertionStatus.put(name.toString(), Boolean.valueOf(enabled));
  926. }
  927. /**
  928. * Resets the default assertion status of this classloader, its packages
  929. * and classes, all to false. This allows overriding defaults inherited
  930. * from the command line.
  931. *
  932. * @see #setDefaultAssertionStatus(boolean)
  933. * @see #setClassAssertionStatus(String, boolean)
  934. * @see #setPackageAssertionStatus(String, boolean)
  935. * @since 1.4
  936. */
  937. public synchronized void clearAssertionStatus()
  938. {
  939. defaultAssertionStatus = false;
  940. packageAssertionStatus = null;
  941. classAssertionStatus = null;
  942. }
  943. /**
  944. * Return true if this loader is either the specified class loader
  945. * or an ancestor thereof.
  946. * @param loader the class loader to check
  947. */
  948. final boolean isAncestorOf(ClassLoader loader)
  949. {
  950. while (loader != null)
  951. {
  952. if (this == loader)
  953. return true;
  954. loader = loader.parent;
  955. }
  956. return false;
  957. }
  958. private static URL[] getExtClassLoaderUrls()
  959. {
  960. String classpath = SystemProperties.getProperty("java.ext.dirs", "");
  961. StringTokenizer tok = new StringTokenizer(classpath, File.pathSeparator);
  962. ArrayList list = new ArrayList();
  963. while (tok.hasMoreTokens())
  964. {
  965. try
  966. {
  967. File f = new File(tok.nextToken());
  968. File[] files = f.listFiles();
  969. if (files != null)
  970. for (int i = 0; i < files.length; i++)
  971. list.add(files[i].toURL());
  972. }
  973. catch(Exception x)
  974. {
  975. }
  976. }
  977. URL[] urls = new URL[list.size()];
  978. list.toArray(urls);
  979. return urls;
  980. }
  981. private static void addFileURL(ArrayList list, String file)
  982. {
  983. try
  984. {
  985. list.add(new File(file).toURL());
  986. }
  987. catch(java.net.MalformedURLException x)
  988. {
  989. }
  990. }
  991. private static URL[] getSystemClassLoaderUrls()
  992. {
  993. String classpath = SystemProperties.getProperty("java.class.path", ".");
  994. StringTokenizer tok = new StringTokenizer(classpath, File.pathSeparator, true);
  995. ArrayList list = new ArrayList();
  996. while (tok.hasMoreTokens())
  997. {
  998. String s = tok.nextToken();
  999. if (s.equals(File.pathSeparator))
  1000. addFileURL(list, ".");
  1001. else
  1002. {
  1003. addFileURL(list, s);
  1004. if (tok.hasMoreTokens())
  1005. {
  1006. // Skip the separator.
  1007. tok.nextToken();
  1008. // If the classpath ended with a separator,
  1009. // append the current directory.
  1010. if (!tok.hasMoreTokens())
  1011. addFileURL(list, ".");
  1012. }
  1013. }
  1014. }
  1015. URL[] urls = new URL[list.size()];
  1016. list.toArray(urls);
  1017. return urls;
  1018. }
  1019. static ClassLoader defaultGetSystemClassLoader()
  1020. {
  1021. return createAuxiliarySystemClassLoader(
  1022. createSystemClassLoader(getSystemClassLoaderUrls(),
  1023. createExtClassLoader(getExtClassLoaderUrls(), null)));
  1024. }
  1025. static ClassLoader createExtClassLoader(URL[] urls, ClassLoader parent)
  1026. {
  1027. if (urls.length > 0)
  1028. return new URLClassLoader(urls, parent);
  1029. else
  1030. return parent;
  1031. }
  1032. static ClassLoader createSystemClassLoader(URL[] urls, ClassLoader parent)
  1033. {
  1034. return
  1035. new URLClassLoader(urls, parent)
  1036. {
  1037. protected synchronized Class loadClass(String name,
  1038. boolean resolve)
  1039. throws ClassNotFoundException
  1040. {
  1041. SecurityManager sm = SecurityManager.current;
  1042. if (sm != null)
  1043. {
  1044. int lastDot = name.lastIndexOf('.');
  1045. if (lastDot != -1)
  1046. sm.checkPackageAccess(name.substring(0, lastDot));
  1047. }
  1048. return super.loadClass(name, resolve);
  1049. }
  1050. };
  1051. }
  1052. static ClassLoader createAuxiliarySystemClassLoader(ClassLoader parent)
  1053. {
  1054. String loader = SystemProperties.getProperty("java.system.class.loader", null);
  1055. if (loader == null)
  1056. {
  1057. return parent;
  1058. }
  1059. try
  1060. {
  1061. Constructor c = Class.forName(loader, false, parent)
  1062. .getConstructor(new Class[] { ClassLoader.class });
  1063. return (ClassLoader)c.newInstance(new Object[] { parent });
  1064. }
  1065. catch (Exception e)
  1066. {
  1067. System.err.println("Requested system classloader " + loader + " failed.");
  1068. throw (Error)
  1069. new Error("Requested system classloader " + loader + " failed.")
  1070. .initCause(e);
  1071. }
  1072. }
  1073. /**
  1074. * Before doing anything "dangerous" please call this method to make sure
  1075. * this class loader instance was properly constructed (and not obtained
  1076. * by exploiting the finalizer attack)
  1077. * @see #initialized
  1078. */
  1079. private void checkInitialized()
  1080. {
  1081. if (! initialized)
  1082. throw new SecurityException("attempt to use uninitialized class loader");
  1083. }
  1084. }