Source for java.lang.ClassLoader

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