ClassLoader.java 40.6 KB
Newer Older
1
/* ClassLoader.java -- responsible for loading classes into the VM
2
   Copyright (C) 1998, 1999, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008 Free Software Foundation, Inc.
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17

This file is part of GNU Classpath.

GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.

GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
General Public License for more details.

You should have received a copy of the GNU General Public License
along with GNU Classpath; see the file COPYING.  If not, write to the
Kelley Cook committed
18 19
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA.
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36

Linking this library statically or dynamically with other modules is
making a combined work based on this library.  Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.

As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module.  An independent module is a module which is not derived from
or based on this library.  If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so.  If you do not wish to do so, delete this
exception statement from your version. */
Tom Tromey committed
37 38 39


package java.lang;
Anthony Green committed
40

41
import gnu.classpath.SystemProperties;
42
import gnu.classpath.VMStackWalker;
43 44 45
import gnu.java.util.DoubleEnumeration;
import gnu.java.util.EmptyEnumeration;

46
import java.io.IOException;
47
import java.io.InputStream;
48
import java.lang.ref.WeakReference;
Anthony Green committed
49
import java.net.URL;
50
import java.nio.ByteBuffer;
51
import java.security.CodeSource;
52
import java.security.PermissionCollection;
53 54
import java.security.Policy;
import java.security.ProtectionDomain;
55 56 57
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
Tom Tromey committed
58

59 60 61
import java.util.concurrent.ConcurrentHashMap;
import java.lang.annotation.Annotation;

Tom Tromey committed
62
/**
63 64 65 66 67 68
 * The ClassLoader is a way of customizing the way Java gets its classes
 * and loads them into memory.  The verifier and other standard Java things
 * still run, but the ClassLoader is allowed great flexibility in determining
 * where to get the classfiles and when to load and resolve them. For that
 * matter, a custom ClassLoader can perform on-the-fly code generation or
 * modification!
Anthony Green committed
69
 *
70
 * <p>Every classloader has a parent classloader that is consulted before
71
 * the 'child' classloader when classes or resources should be loaded.
72
 * This is done to make sure that classes can be loaded from an hierarchy of
73
 * multiple classloaders and classloaders do not accidentially redefine
74
 * already loaded classes by classloaders higher in the hierarchy.
75
 *
76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
 * <p>The grandparent of all classloaders is the bootstrap classloader, which
 * loads all the standard system classes as implemented by GNU Classpath. The
 * other special classloader is the system classloader (also called
 * application classloader) that loads all classes from the CLASSPATH
 * (<code>java.class.path</code> system property). The system classloader
 * is responsible for finding the application classes from the classpath,
 * and delegates all requests for the standard library classes to its parent
 * the bootstrap classloader. Most programs will load all their classes
 * through the system classloaders.
 *
 * <p>The bootstrap classloader in GNU Classpath is implemented as a couple of
 * static (native) methods on the package private class
 * <code>java.lang.VMClassLoader</code>, the system classloader is an
 * instance of <code>gnu.java.lang.SystemClassLoader</code>
 * (which is a subclass of <code>java.net.URLClassLoader</code>).
 *
 * <p>Users of a <code>ClassLoader</code> will normally just use the methods
 * <ul>
 *  <li> <code>loadClass()</code> to load a class.</li>
 *  <li> <code>getResource()</code> or <code>getResourceAsStream()</code>
 *       to access a resource.</li>
 *  <li> <code>getResources()</code> to get an Enumeration of URLs to all
 *       the resources provided by the classloader and its parents with the
 *       same name.</li>
 * </ul>
 *
 * <p>Subclasses should implement the methods
 * <ul>
 *  <li> <code>findClass()</code> which is called by <code>loadClass()</code>
 *       when the parent classloader cannot provide a named class.</li>
 *  <li> <code>findResource()</code> which is called by
 *       <code>getResource()</code> when the parent classloader cannot provide
 *       a named resource.</li>
 *  <li> <code>findResources()</code> which is called by
 *       <code>getResource()</code> to combine all the resources with the
 *       same name from the classloader and its parents.</li>
 *  <li> <code>findLibrary()</code> which is called by
 *       <code>Runtime.loadLibrary()</code> when a class defined by the
 *       classloader wants to load a native library.</li>
 * </ul>
 *
 * @author John Keiser
 * @author Mark Wielaard
119
 * @author Eric Blake (ebb9@email.byu.edu)
120 121
 * @see Class
 * @since 1.0
Tom Tromey committed
122
 */
123 124
public abstract class ClassLoader
{
125
  /**
126 127 128 129 130
   * All classes loaded by this classloader. VM's may choose to implement
   * this cache natively; but it is here available for use if necessary. It
   * is not private in order to allow native code (and trusted subclasses)
   * access to this field.
   */
131
  final HashMap loadedClasses = new HashMap();
132 133

  /**
134 135 136 137 138 139 140 141 142
   * Loading constraints registered with this classloader.  This maps
   * a class name to a weak reference to a class.  When the reference
   * is non-null, it means that a reference to the name must resolve
   * to the indicated class.
   */
  final HashMap<String, WeakReference<Class>> loadingConstraints
    = new HashMap<String, WeakReference<Class>>();

  /**
143 144 145
   * All packages defined by this classloader. It is not private in order to
   * allow native code (and trusted subclasses) access to this field.
   */
146
  final HashMap definedPackages = new HashMap();
147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173

  /**
   * The classloader that is consulted before this classloader.
   * If null then the parent is the bootstrap classloader.
   */
  private final ClassLoader parent;

  /**
   * This is true if this classloader was successfully initialized.
   * This flag is needed to avoid a class loader attack: even if the
   * security manager rejects an attempt to create a class loader, the
   * malicious class could have a finalize method which proceeds to
   * define classes.
   */
  private final boolean initialized;

  /**
   * System/Application classloader: defaults to an instance of
   * gnu.java.lang.SystemClassLoader, unless the first invocation of
   * getSystemClassLoader loads another class loader because of the
   * java.system.class.loader property. The initialization of this field
   * is somewhat circular - getSystemClassLoader() checks whether this
   * field is null in order to bypass a security check.
   */
  static final ClassLoader systemClassLoader =
    VMClassLoader.getSystemClassLoader();

174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252
  /**
   * This cache maps from a Class to its associated annotations.  It's
   * declared here so that when this class loader becomes unreachable,
   * so will the corresponding cache.
   */

  private final ConcurrentHashMap<AnnotationsKey,Object[]> 
    declaredAnnotations 
      = new ConcurrentHashMap<AnnotationsKey,Object[]>();
  
  static final class AnnotationsKey
  {
    final int /* jv_attr_type */ member_type;
    final int member_index;
    final int /* jv_attr_kind */ kind_req;
    final Class declaringClass;
    final int hashCode;

    public AnnotationsKey (Class declaringClass,
			   int member_type,
			   int member_index,
			   int kind_req)
    {
      this.member_type = member_type;
      this.member_index = member_index;
      this.kind_req = kind_req;
      this.declaringClass = declaringClass;
      hashCode = (member_type ^ member_index ^ kind_req
		  ^ declaringClass.hashCode());
    }

    public boolean equals(Object obj)
    {
      AnnotationsKey other = (AnnotationsKey)obj;
      return (this.member_type == other.member_type
	      && this.member_index == other.member_index
	      && this.kind_req == other.kind_req
	      && this.declaringClass == other.declaringClass);
    }

    public int hashCode()
    {
      return hashCode;
    }

    public static final Annotation[] NIL = new Annotation[0];
  }
  
  final Object[] getDeclaredAnnotations(Class declaringClass,
					int member_type,
					int member_index,
					int kind_req)
  {
    Object[] result 
      = declaredAnnotations.get (new AnnotationsKey
				 (declaringClass,
				  member_type,
				  member_index,
				  kind_req));
    if (result != AnnotationsKey.NIL && result != null)
      return (Object[])result.clone();
    return null;
  }

  final Object[] putDeclaredAnnotations(Class declaringClass,
					int member_type,
					int member_index,
					int kind_req,
					Object[] annotations)
  {
    declaredAnnotations.put 
      (new AnnotationsKey
       (declaringClass,	member_type,
	member_index, kind_req), 
       annotations == null ? AnnotationsKey.NIL : annotations);

    return annotations == null ? null : (Object[])annotations.clone();
  }

253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285
  static
  {
    // Find out if we have to install a default security manager. Note
    // that this is done here because we potentially need the system
    // class loader to load the security manager and note also that we
    // don't need the security manager until the system class loader
    // is created.  If the runtime chooses to use a class loader that
    // doesn't have the system class loader as its parent, it is
    // responsible for setting up a security manager before doing so.
    String secman = SystemProperties.getProperty("java.security.manager");
    if (secman != null && SecurityManager.current == null)
    {
      if (secman.equals("") || secman.equals("default"))
      {
	SecurityManager.current = new SecurityManager();
      }
      else
      {
	try
	{
	  Class cl = Class.forName(secman, false, systemClassLoader);
	  SecurityManager.current = (SecurityManager) cl.newInstance();
	}
	catch (Exception x)
	{
	  throw (InternalError)
	    new InternalError("Unable to create SecurityManager")
	        .initCause(x);
	}
      }
    }
  }

286 287 288 289 290 291 292 293 294 295 296 297 298
  /**
   * The default protection domain, used when defining a class with a null
   * paramter for the domain.
   */
  static final ProtectionDomain defaultProtectionDomain;
  static
  {
    CodeSource cs = new CodeSource(null, null);
    PermissionCollection perm = Policy.getPolicy().getPermissions(cs);
    defaultProtectionDomain = new ProtectionDomain(cs, perm);
  }

  /**
299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338
   * The desired assertion status of classes loaded by this loader, if not
   * overridden by package or class instructions.
   */
  // Package visible for use by Class.
  boolean defaultAssertionStatus = VMClassLoader.defaultAssertionStatus();

  /**
   * The command-line state of the package assertion status overrides. This
   * map is never modified, so it does not need to be synchronized.
   */
  // Package visible for use by Class.
  static final Map systemPackageAssertionStatus
    = VMClassLoader.packageAssertionStatus();

  /**
   * The map of package assertion status overrides, or null if no package
   * overrides have been specified yet. The values of the map should be
   * Boolean.TRUE or Boolean.FALSE, and the unnamed package is represented
   * by the null key. This map must be synchronized on this instance.
   */
  // Package visible for use by Class.
  Map packageAssertionStatus;

  /**
   * The command-line state of the class assertion status overrides. This
   * map is never modified, so it does not need to be synchronized.
   */
  // Package visible for use by Class.
  static final Map systemClassAssertionStatus
    = VMClassLoader.classAssertionStatus();

  /**
   * The map of class assertion status overrides, or null if no class
   * overrides have been specified yet. The values of the map should be
   * Boolean.TRUE or Boolean.FALSE. This map must be synchronized on this
   * instance.
   */
  // Package visible for use by Class.
  Map classAssertionStatus;

339
  /**
340 341
   * Create a new ClassLoader with as parent the system classloader. There
   * may be a security check for <code>checkCreateClassLoader</code>.
342 343 344
   *
   * @throws SecurityException if the security check fails
   */
345
  protected ClassLoader() throws SecurityException
346
  {
347
    this(systemClassLoader);
348
  }
349

350
  /**
351 352 353 354 355 356 357
   * Create a new ClassLoader with the specified parent. The parent will
   * be consulted when a class or resource is requested through
   * <code>loadClass()</code> or <code>getResource()</code>. Only when the
   * parent classloader cannot provide the requested class or resource the
   * <code>findClass()</code> or <code>findResource()</code> method
   * of this classloader will be called. There may be a security check for
   * <code>checkCreateClassLoader</code>.
358
   *
359 360
   * @param parent the classloader's parent, or null for the bootstrap
   *        classloader
361 362 363
   * @throws SecurityException if the security check fails
   * @since 1.2
   */
364
  protected ClassLoader(ClassLoader parent)
365
  {
366 367 368 369 370 371
    // May we create a new classloader?
    SecurityManager sm = System.getSecurityManager();
    if (sm != null)
      sm.checkCreateClassLoader();
    this.parent = parent;
    this.initialized = true;
372
  }
Tom Tromey committed
373

Anthony Green committed
374
  /**
375 376 377 378
   * Load a class using this ClassLoader or its parent, without resolving
   * it. Calls <code>loadClass(name, false)</code>.
   *
   * <p>Subclasses should not override this method but should override
379
   * <code>findClass()</code> which is called by this method.</p>
380 381 382 383
   *
   * @param name the name of the class relative to this ClassLoader
   * @return the loaded class
   * @throws ClassNotFoundException if the class cannot be found
384
   */
385
  public Class<?> loadClass(String name) throws ClassNotFoundException
386
  {
387
    return loadClass(name, false);
388 389
  }

Andrew Haley committed
390 391 392
  private native Class loadClassFromSig(String name)
    throws ClassNotFoundException;

393
  /**
394 395 396 397 398
   * Load a class using this ClassLoader or its parent, possibly resolving
   * it as well using <code>resolveClass()</code>. It first tries to find
   * out if the class has already been loaded through this classloader by
   * calling <code>findLoadedClass()</code>. Then it calls
   * <code>loadClass()</code> on the parent classloader (or when there is
399
   * no parent it uses the VM bootclassloader). If the class is still
400 401 402 403 404 405
   * not loaded it tries to create a new class by calling
   * <code>findClass()</code>. Finally when <code>resolve</code> is
   * <code>true</code> it also calls <code>resolveClass()</code> on the
   * newly loaded class.
   *
   * <p>Subclasses should not override this method but should override
406
   * <code>findClass()</code> which is called by this method.</p>
407 408 409 410 411
   *
   * @param name the fully qualified name of the class to load
   * @param resolve whether or not to resolve the class
   * @return the loaded class
   * @throws ClassNotFoundException if the class cannot be found
Anthony Green committed
412
   */
413
  protected synchronized Class<?> loadClass(String name, boolean resolve)
414
    throws ClassNotFoundException
415
  {
416 417 418 419 420 421 422 423
    SecurityManager sm = SecurityManager.current;
    if (sm != null)
      {
	int lastDot = name.lastIndexOf('.');
	if (lastDot != -1)
	  sm.checkPackageAccess(name.substring(0, lastDot));
      }

Andrew Haley committed
424 425
    // Arrays are handled specially.
    Class c;
426
    if (name.length() > 0 && name.charAt(0) == '[')
Andrew Haley committed
427 428
      c = loadClassFromSig(name);
    else
429
      {
Andrew Haley committed
430 431 432
	// Have we already loaded this class?
	c = findLoadedClass(name);
	if (c == null)
433
	  {
Andrew Haley committed
434 435
	    // Can the class be loaded by a parent?
	    try
436
	      {
Andrew Haley committed
437 438 439 440 441 442 443 444 445 446
		if (parent == null)
		  {
		    c = VMClassLoader.loadClass(name, resolve);
		    if (c != null)
		      return c;
		  }
		else
		  {
		    return parent.loadClass(name, resolve);
		  }
447
	      }
Andrew Haley committed
448
	    catch (ClassNotFoundException e)
449 450
	      {
	      }
Andrew Haley committed
451 452
	    // Still not found, we have to do it ourself.
	    c = findClass(name);
453
	  }
454
      }
455 456
    if (resolve)
      resolveClass(c);
457 458 459
    return c;
  }

460 461 462 463 464
  /**
   * Called for every class name that is needed but has not yet been
   * defined by this classloader or one of its parents. It is called by
   * <code>loadClass()</code> after both <code>findLoadedClass()</code> and
   * <code>parent.loadClass()</code> couldn't provide the requested class.
465
   *
466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482
   * <p>The default implementation throws a
   * <code>ClassNotFoundException</code>. Subclasses should override this
   * method. An implementation of this method in a subclass should get the
   * class bytes of the class (if it can find them), if the package of the
   * requested class doesn't exist it should define the package and finally
   * it should call define the actual class. It does not have to resolve the
   * class. It should look something like the following:<br>
   *
   * <pre>
   * // Get the bytes that describe the requested class
   * byte[] classBytes = classLoaderSpecificWayToFindClassBytes(name);
   * // Get the package name
   * int lastDot = name.lastIndexOf('.');
   * if (lastDot != -1)
   *   {
   *     String packageName = name.substring(0, lastDot);
   *     // Look if the package already exists
483
   *     if (getPackage(packageName) == null)
484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499
   *       {
   *         // define the package
   *         definePackage(packageName, ...);
   *       }
   *   }
   * // Define and return the class
   *  return defineClass(name, classBytes, 0, classBytes.length);
   * </pre>
   *
   * <p><code>loadClass()</code> makes sure that the <code>Class</code>
   * returned by <code>findClass()</code> will later be returned by
   * <code>findLoadedClass()</code> when the same class name is requested.
   *
   * @param name class name to find (including the package name)
   * @return the requested Class
   * @throws ClassNotFoundException when the class can not be found
500
   * @since 1.2
501
   */
502
  protected Class<?> findClass(String name) throws ClassNotFoundException
503
  {
504
    throw new ClassNotFoundException(name);
505 506
  }

507 508 509 510 511 512 513 514 515 516 517
  /**
   * Helper to define a class using a string of bytes. This version is not
   * secure.
   *
   * @param data the data representing the classfile, in classfile format
   * @param offset the offset into the data where the classfile starts
   * @param len the length of the classfile data in the array
   * @return the class that was defined
   * @throws ClassFormatError if data is not in proper classfile format
   * @throws IndexOutOfBoundsException if offset or len is negative, or
   *         offset + len exceeds data
518 519
   * @deprecated use {@link #defineClass(String, byte[], int, int)} instead
   */
520
  protected final Class<?> defineClass(byte[] data, int offset, int len)
521
    throws ClassFormatError
Anthony Green committed
522
  {
523
    return defineClass(null, data, offset, len);
Anthony Green committed
524
  }
Tom Tromey committed
525

526 527 528 529 530 531
  /**
   * Helper to define a class using a string of bytes without a
   * ProtectionDomain. Subclasses should call this method from their
   * <code>findClass()</code> implementation. The name should use '.'
   * separators, and discard the trailing ".class".  The default protection
   * domain has the permissions of
532
   * <code>Policy.getPolicy().getPermissions(new CodeSource(null, null))</code>.
533 534 535 536 537 538 539 540 541 542 543 544
   *
   * @param name the name to give the class, or null if unknown
   * @param data the data representing the classfile, in classfile format
   * @param offset the offset into the data where the classfile starts
   * @param len the length of the classfile data in the array
   * @return the class that was defined
   * @throws ClassFormatError if data is not in proper classfile format
   * @throws IndexOutOfBoundsException if offset or len is negative, or
   *         offset + len exceeds data
   * @throws SecurityException if name starts with "java."
   * @since 1.1
   */
545 546
  protected final Class<?> defineClass(String name, byte[] data, int offset,
				       int len) throws ClassFormatError
547
  {
548
    return defineClass(name, data, offset, len, null);
Anthony Green committed
549 550
  }

551 552 553 554
  /**
   * Helper to define a class using a string of bytes. Subclasses should call
   * this method from their <code>findClass()</code> implementation. If the
   * domain is null, the default of
555
   * <code>Policy.getPolicy().getPermissions(new CodeSource(null, null))</code>
556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573
   * is used. Once a class has been defined in a package, all further classes
   * in that package must have the same set of certificates or a
   * SecurityException is thrown.
   *
   * @param name the name to give the class.  null if unknown
   * @param data the data representing the classfile, in classfile format
   * @param offset the offset into the data where the classfile starts
   * @param len the length of the classfile data in the array
   * @param domain the ProtectionDomain to give to the class, null for the
   *        default protection domain
   * @return the class that was defined
   * @throws ClassFormatError if data is not in proper classfile format
   * @throws IndexOutOfBoundsException if offset or len is negative, or
   *         offset + len exceeds data
   * @throws SecurityException if name starts with "java.", or if certificates
   *         do not match up
   * @since 1.2
   */
574 575 576
  protected final synchronized Class<?> defineClass(String name, byte[] data,
						    int offset, int len,
						    ProtectionDomain domain)
577
    throws ClassFormatError
578
  {
579
    checkInitialized();
580 581
    if (domain == null)
      domain = defaultProtectionDomain;
582
    
583
    Class retval = VMClassLoader.defineClass(this, name, data,
584
					     offset, len, domain);
585 586
    loadedClasses.put(retval.getName(), retval);
    return retval;
587 588
  }

589
  /**
590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618
   * Helper to define a class using the contents of a byte buffer. If
   * the domain is null, the default of
   * <code>Policy.getPolicy().getPermissions(new CodeSource(null,
   * null))</code> is used. Once a class has been defined in a
   * package, all further classes in that package must have the same
   * set of certificates or a SecurityException is thrown.
   *
   * @param name the name to give the class.  null if unknown
   * @param buf a byte buffer containing bytes that form a class.
   * @param domain the ProtectionDomain to give to the class, null for the
   *        default protection domain
   * @return the class that was defined
   * @throws ClassFormatError if data is not in proper classfile format
   * @throws NoClassDefFoundError if the supplied name is not the same as
   *                              the one specified by the byte buffer.
   * @throws SecurityException if name starts with "java.", or if certificates
   *         do not match up
   * @since 1.5
   */
  protected final Class<?> defineClass(String name, ByteBuffer buf,
				       ProtectionDomain domain)
    throws ClassFormatError
  {
    byte[] data = new byte[buf.remaining()];
    buf.get(data);
    return defineClass(name, data, 0, data.length, domain);
  }

  /**
619 620 621 622 623 624 625
   * Links the class, if that has not already been done. Linking basically
   * resolves all references to other classes made by this class.
   *
   * @param c the class to resolve
   * @throws NullPointerException if c is null
   * @throws LinkageError if linking fails
   */
626
  protected final void resolveClass(Class<?> c)
Anthony Green committed
627
  {
628
    checkInitialized();
629
    VMClassLoader.resolveClass(c);
Anthony Green committed
630 631
  }

632
  /**
633 634 635
   * Helper to find a Class using the system classloader, possibly loading it.
   * A subclass usually does not need to call this, if it correctly
   * overrides <code>findClass(String)</code>.
636
   *
637 638 639
   * @param name the name of the class to find
   * @return the found class
   * @throws ClassNotFoundException if the class cannot be found
640
   */
641
  protected final Class<?> findSystemClass(String name)
642
    throws ClassNotFoundException
643
  {
644
    checkInitialized();
645
    return Class.forName(name, false, systemClassLoader);
646 647 648
  }

  /**
649 650 651 652
   * Returns the parent of this classloader. If the parent of this
   * classloader is the bootstrap classloader then this method returns
   * <code>null</code>. A security check may be performed on
   * <code>RuntimePermission("getClassLoader")</code>.
653
   *
654
   * @return the parent <code>ClassLoader</code>
655
   * @throws SecurityException if the security check fails
656 657
   * @since 1.2
   */
658
  public final ClassLoader getParent()
659
  {
660 661 662
    // Check if we may return the parent classloader.
    SecurityManager sm = System.getSecurityManager();
    if (sm != null)
663
      {
664
	ClassLoader cl = VMStackWalker.getCallingClassLoader();
665 666
	if (cl != null && ! cl.isAncestorOf(this))
          sm.checkPermission(new RuntimePermission("getClassLoader"));
667
      }
668
    return parent;
669 670 671
  }

  /**
672 673
   * Helper to set the signers of a class. This should be called after
   * defining the class.
674
   *
675 676 677
   * @param c the Class to set signers of
   * @param signers the signers to set
   * @since 1.1
678
   */
679
  protected final void setSigners(Class<?> c, Object[] signers)
680
  {
681
    checkInitialized();
682
    c.setSigners(signers);
683
  }
Anthony Green committed
684

685
  /**
686
   * Helper to find an already-loaded class in this ClassLoader.
687
   *
688 689 690
   * @param name the name of the class to find
   * @return the found Class, or null if it is not found
   * @since 1.1
691
   */
692
  protected final synchronized Class<?> findLoadedClass(String name)
693
  {
694
    checkInitialized();
695 696 697
    // NOTE: If the VM is keeping its own cache, it may make sense to have
    // this method be native.
    return (Class) loadedClasses.get(name);
698 699
  }

700 701 702 703 704 705 706
  /**
   * Get the URL to a resource using this classloader or one of its parents.
   * First tries to get the resource by calling <code>getResource()</code>
   * on the parent classloader. If the parent classloader returns null then
   * it tries finding the resource by calling <code>findResource()</code> on
   * this classloader. The resource name should be separated by '/' for path
   * elements.
Anthony Green committed
707
   *
708 709 710 711 712
   * <p>Subclasses should not override this method but should override
   * <code>findResource()</code> which is called by this method.
   *
   * @param name the name of the resource relative to this classloader
   * @return the URL to the resource or null when not found
Anthony Green committed
713
   */
714
  public URL getResource(String name)
715
  {
716 717 718 719 720 721 722 723 724 725
    URL result;

    if (parent == null)
      result = VMClassLoader.getResource(name);
    else
      result = parent.getResource(name);

    if (result == null)
      result = findResource(name);
    return result;
726
  }
Anthony Green committed
727

728
  /**
729 730 731 732 733 734
   * Returns an Enumeration of all resources with a given name that can
   * be found by this classloader and its parents. Certain classloaders
   * (such as the URLClassLoader when given multiple jar files) can have
   * multiple resources with the same name that come from multiple locations.
   * It can also occur that a parent classloader offers a resource with a
   * certain name and the child classloader also offers a resource with that
735
   * same name. <code>getResource()</code> only offers the first resource (of the
736 737
   * parent) with a given name. This method lists all resources with the
   * same name. The name should use '/' as path separators.
738
   *
739 740
   * <p>The Enumeration is created by first calling <code>getResources()</code>
   * on the parent classloader and then calling <code>findResources()</code>
741
   * on this classloader.</p>
742 743 744 745 746
   *
   * @param name the resource name
   * @return an enumaration of all resources found
   * @throws IOException if I/O errors occur in the process
   * @since 1.2
747
   * @specnote this was <code>final</code> prior to 1.5
748
   */
749
  public Enumeration<URL> getResources(String name) throws IOException
750
  {
751
    Enumeration<URL> parentResources;
752 753 754 755
    if (parent == null)
      parentResources = VMClassLoader.getResources(name);
    else
      parentResources = parent.getResources(name);
756
    return new DoubleEnumeration<URL>(parentResources, findResources(name));
Anthony Green committed
757 758
  }

759
  /**
760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775
   * Called whenever all locations of a named resource are needed.
   * It is called by <code>getResources()</code> after it has called
   * <code>parent.getResources()</code>. The results are combined by
   * the <code>getResources()</code> method.
   *
   * <p>The default implementation always returns an empty Enumeration.
   * Subclasses should override it when they can provide an Enumeration of
   * URLs (possibly just one element) to the named resource.
   * The first URL of the Enumeration should be the same as the one
   * returned by <code>findResource</code>.
   *
   * @param name the name of the resource to be found
   * @return a possibly empty Enumeration of URLs to the named resource
   * @throws IOException if I/O errors occur in the process
   * @since 1.2
   */
776
  protected Enumeration<URL> findResources(String name) throws IOException
777
  {
778
    return new EmptyEnumeration<URL>();
779
  }
780 781

  /**
782 783 784 785
   * Called whenever a resource is needed that could not be provided by
   * one of the parents of this classloader. It is called by
   * <code>getResource()</code> after <code>parent.getResource()</code>
   * couldn't provide the requested resource.
786
   *
787 788 789 790 791 792 793
   * <p>The default implementation always returns null. Subclasses should
   * override this method when they can provide a way to return a URL
   * to a named resource.
   *
   * @param name the name of the resource to be found
   * @return a URL to the named resource or null when not found
   * @since 1.2
794
   */
795 796 797
  protected URL findResource(String name)
  {
    return null;
Anthony Green committed
798
  }
Tom Tromey committed
799

800 801 802 803 804 805 806
  /**
   * Get the URL to a resource using the system classloader.
   *
   * @param name the name of the resource relative to the system classloader
   * @return the URL to the resource
   * @since 1.1
   */
807 808 809
  public static final URL getSystemResource(String name)
  {
    return systemClassLoader.getResource(name);
Anthony Green committed
810 811 812
  }

  /**
813 814 815 816 817 818 819 820 821 822
   * Get an Enumeration of URLs to resources with a given name using the
   * the system classloader. The enumeration firsts lists the resources with
   * the given name that can be found by the bootstrap classloader followed
   * by the resources with the given name that can be found on the classpath.
   *
   * @param name the name of the resource relative to the system classloader
   * @return an Enumeration of URLs to the resources
   * @throws IOException if I/O errors occur in the process
   * @since 1.2
   */
823 824
  public static Enumeration<URL> getSystemResources(String name)
    throws IOException
825
  {
826
    return systemClassLoader.getResources(name);
827 828 829
  }

  /**
830 831 832 833 834 835 836 837 838 839 840
   * Get a resource as stream using this classloader or one of its parents.
   * First calls <code>getResource()</code> and if that returns a URL to
   * the resource then it calls and returns the InputStream given by
   * <code>URL.openStream()</code>.
   *
   * <p>Subclasses should not override this method but should override
   * <code>findResource()</code> which is called by this method.
   *
   * @param name the name of the resource relative to this classloader
   * @return an InputStream to the resource, or null
   * @since 1.1
Anthony Green committed
841
   */
842
  public InputStream getResourceAsStream(String name)
Anthony Green committed
843
  {
844 845
    try
      {
846 847
        URL url = getResource(name);
        if (url == null)
848
          return null;
849
        return url.openStream();
850
      }
851
    catch (IOException e)
852
      {
853
        return null;
854
      }
Anthony Green committed
855
  }
856

Anthony Green committed
857
  /**
858 859 860 861 862
   * Get a resource using the system classloader.
   *
   * @param name the name of the resource relative to the system classloader
   * @return an input stream for the resource, or null
   * @since 1.1
Anthony Green committed
863
   */
864
  public static final InputStream getSystemResourceAsStream(String name)
865
  {
866 867 868 869 870 871 872 873 874 875 876
    try
      {
        URL url = getSystemResource(name);
        if (url == null)
          return null;
        return url.openStream();
      }
    catch (IOException e)
      {
        return null;
      }
877 878
  }

879
  /**
880
   * Returns the system classloader. The system classloader (also called
881
   * the application classloader) is the classloader that is used to
882 883 884 885 886
   * load the application classes on the classpath (given by the system
   * property <code>java.class.path</code>. This is set as the context
   * class loader for a thread. The system property
   * <code>java.system.class.loader</code>, if defined, is taken to be the
   * name of the class to use as the system class loader, which must have
887 888 889
   * a public constructor which takes a ClassLoader as a parent. The parent
   * class loader passed in the constructor is the default system class
   * loader.
890
   *
891 892 893
   * <p>Note that this is different from the bootstrap classloader that
   * actually loads all the real "system" classes (the bootstrap classloader
   * is the parent of the returned system classloader).
894
   *
895 896 897 898 899 900 901 902
   * <p>A security check will be performed for
   * <code>RuntimePermission("getClassLoader")</code> if the calling class
   * is not a parent of the system class loader.
   *
   * @return the system class loader
   * @throws SecurityException if the security check fails
   * @throws IllegalStateException if this is called recursively
   * @throws Error if <code>java.system.class.loader</code> fails to load
903 904
   * @since 1.2
   */
905
  public static ClassLoader getSystemClassLoader()
906
  {
907 908 909 910
    // Check if we may return the system classloader
    SecurityManager sm = System.getSecurityManager();
    if (sm != null)
      {
911
	ClassLoader cl = VMStackWalker.getCallingClassLoader();
912 913 914 915 916
	if (cl != null && cl != systemClassLoader)
	  sm.checkPermission(new RuntimePermission("getClassLoader"));
      }

    return systemClassLoader;
Anthony Green committed
917 918
  }

919
  /**
920 921 922 923 924 925 926
   * Defines a new package and creates a Package object. The package should
   * be defined before any class in the package is defined with
   * <code>defineClass()</code>. The package should not yet be defined
   * before in this classloader or in one of its parents (which means that
   * <code>getPackage()</code> should return <code>null</code>). All
   * parameters except the <code>name</code> of the package may be
   * <code>null</code>.
927
   *
928 929 930 931
   * <p>Subclasses should call this method from their <code>findClass()</code>
   * implementation before calling <code>defineClass()</code> on a Class
   * in a not yet defined Package (which can be checked by calling
   * <code>getPackage()</code>).
932
   *
933 934 935 936 937 938 939 940 941 942 943 944
   * @param name the name of the Package
   * @param specTitle the name of the specification
   * @param specVendor the name of the specification designer
   * @param specVersion the version of this specification
   * @param implTitle the name of the implementation
   * @param implVendor the vendor that wrote this implementation
   * @param implVersion the version of this implementation
   * @param sealed if sealed the origin of the package classes
   * @return the Package object for the specified package
   * @throws IllegalArgumentException if the package name is null or it
   *         was already defined by this classloader or one of its parents
   * @see Package
945 946
   * @since 1.2
   */
947 948 949 950 951 952 953 954 955
  protected Package definePackage(String name, String specTitle,
                                  String specVendor, String specVersion,
                                  String implTitle, String implVendor,
                                  String implVersion, URL sealed)
  {
    if (getPackage(name) != null)
      throw new IllegalArgumentException("Package " + name
                                         + " already defined");
    Package p = new Package(name, specTitle, specVendor, specVersion,
956
                            implTitle, implVendor, implVersion, sealed, this);
957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973
    synchronized (definedPackages)
      {
        definedPackages.put(name, p);
      }
    return p;
  }

  /**
   * Returns the Package object for the requested package name. It returns
   * null when the package is not defined by this classloader or one of its
   * parents.
   *
   * @param name the package name to find
   * @return the package, if defined
   * @since 1.2
   */
  protected Package getPackage(String name)
974
  {
975 976 977
    Package p;
    if (parent == null)
      p = VMClassLoader.getPackage(name);
978
    else
979 980 981 982 983 984 985 986 987 988
      p = parent.getPackage(name);

    if (p == null)
      {
	synchronized (definedPackages)
	  {
	    p = (Package) definedPackages.get(name);
	  }
      }
    return p;
989 990
  }

991
  /**
992
   * Returns all Package objects defined by this classloader and its parents.
993
   *
994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031
   * @return an array of all defined packages
   * @since 1.2
   */
  protected Package[] getPackages()
  {
    // Get all our packages.
    Package[] packages;
    synchronized(definedPackages)
      {
        packages = new Package[definedPackages.size()];
        definedPackages.values().toArray(packages);
      }

    // If we have a parent get all packages defined by our parents.
    Package[] parentPackages;
    if (parent == null)
      parentPackages = VMClassLoader.getPackages();
    else
      parentPackages = parent.getPackages();

    Package[] allPackages = new Package[parentPackages.length
					+ packages.length];
    System.arraycopy(parentPackages, 0, allPackages, 0,
                     parentPackages.length);
    System.arraycopy(packages, 0, allPackages, parentPackages.length,
                     packages.length);
    return allPackages;
  }

  /**
   * Called by <code>Runtime.loadLibrary()</code> to get an absolute path
   * to a (system specific) library that was requested by a class loaded
   * by this classloader. The default implementation returns
   * <code>null</code>. It should be implemented by subclasses when they
   * have a way to find the absolute path to a library. If this method
   * returns null the library is searched for in the default locations
   * (the directories listed in the <code>java.library.path</code> system
   * property).
1032
   *
1033 1034
   * @param name the (system specific) name of the requested library
   * @return the full pathname to the requested library, or null
1035
   * @see Runtime#loadLibrary(String)
1036 1037
   * @since 1.2
   */
1038
  protected String findLibrary(String name)
1039
  {
1040
    return null;
1041
  }
1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056

  /**
   * Set the default assertion status for classes loaded by this classloader,
   * used unless overridden by a package or class request.
   *
   * @param enabled true to set the default to enabled
   * @see #setClassAssertionStatus(String, boolean)
   * @see #setPackageAssertionStatus(String, boolean)
   * @see #clearAssertionStatus()
   * @since 1.4
   */
  public void setDefaultAssertionStatus(boolean enabled)
  {
    defaultAssertionStatus = enabled;
  }
1057
  
1058 1059 1060 1061 1062 1063 1064
  /**
   * Set the default assertion status for packages, used unless overridden
   * by a class request. This default also covers subpackages, unless they
   * are also specified. The unnamed package should use null for the name.
   *
   * @param name the package (and subpackages) to affect
   * @param enabled true to set the default to enabled
1065
   * @see #setDefaultAssertionStatus(boolean)
1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085
   * @see #setClassAssertionStatus(String, boolean)
   * @see #clearAssertionStatus()
   * @since 1.4
   */
  public synchronized void setPackageAssertionStatus(String name,
                                                     boolean enabled)
  {
    if (packageAssertionStatus == null)
      packageAssertionStatus
        = new HashMap(systemPackageAssertionStatus);
    packageAssertionStatus.put(name, Boolean.valueOf(enabled));
  }
  
  /**
   * Set the default assertion status for a class. This only affects the
   * status of top-level classes, any other string is harmless.
   *
   * @param name the class to affect
   * @param enabled true to set the default to enabled
   * @throws NullPointerException if name is null
1086
   * @see #setDefaultAssertionStatus(boolean)
1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115
   * @see #setPackageAssertionStatus(String, boolean)
   * @see #clearAssertionStatus()
   * @since 1.4
   */
  public synchronized void setClassAssertionStatus(String name,
                                                   boolean enabled)
  {
    if (classAssertionStatus == null)
      classAssertionStatus = new HashMap(systemClassAssertionStatus);
    // The toString() hack catches null, as required.
    classAssertionStatus.put(name.toString(), Boolean.valueOf(enabled));
  }
  
  /**
   * Resets the default assertion status of this classloader, its packages
   * and classes, all to false. This allows overriding defaults inherited
   * from the command line.
   *
   * @see #setDefaultAssertionStatus(boolean)
   * @see #setClassAssertionStatus(String, boolean)
   * @see #setPackageAssertionStatus(String, boolean)
   * @since 1.4
   */
  public synchronized void clearAssertionStatus()
  {
    defaultAssertionStatus = false;
    packageAssertionStatus = new HashMap();
    classAssertionStatus = new HashMap();
  }
Tom Tromey committed
1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131

  /**
   * Return true if this loader is either the specified class loader
   * or an ancestor thereof.
   * @param loader the class loader to check
   */
  final boolean isAncestorOf(ClassLoader loader)
  {
    while (loader != null)
      {
	if (this == loader)
	  return true;
	loader = loader.parent;
      }
    return false;
  }
1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143

  /**
   * Before doing anything "dangerous" please call this method to make sure
   * this class loader instance was properly constructed (and not obtained
   * by exploiting the finalizer attack)
   * @see #initialized
   */
  private void checkInitialized()
  {
    if (! initialized)
      throw new SecurityException("attempt to use uninitialized class loader");
  }
Tom Tromey committed
1144
}