OSDN Git Service

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