ClassLoader.java 41 KB

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