1 /* 2 * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. Oracle designates this 8 * particular file as subject to the "Classpath" exception as provided 9 * by Oracle in the LICENSE file that accompanied this code. 10 * 11 * This code is distributed in the hope that it will be useful, but WITHOUT 12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14 * version 2 for more details (a copy is included in the LICENSE file that 15 * accompanied this code). 16 * 17 * You should have received a copy of the GNU General Public License version 18 * 2 along with this work; if not, write to the Free Software Foundation, 19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 20 * 21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 22 * or visit www.oracle.com if you need additional information or have any 23 * questions. 24 */ 25 package java.lang; 26 27 import java.io.InputStream; 28 import java.io.IOException; 29 import java.io.File; 30 import java.lang.reflect.Constructor; 31 import java.lang.reflect.InvocationTargetException; 32 import java.net.MalformedURLException; 33 import java.net.URL; 34 import java.security.AccessController; 35 import java.security.AccessControlContext; 36 import java.security.CodeSource; 37 import java.security.Policy; 38 import java.security.PrivilegedAction; 39 import java.security.PrivilegedActionException; 40 import java.security.PrivilegedExceptionAction; 41 import java.security.ProtectionDomain; 42 import java.security.cert.Certificate; 43 import java.util.Collections; 44 import java.util.Enumeration; 45 import java.util.HashMap; 46 import java.util.HashSet; 47 import java.util.Set; 48 import java.util.Stack; 49 import java.util.Map; 50 import java.util.Vector; 51 import java.util.Hashtable; 52 import java.util.WeakHashMap; 53 import java.util.concurrent.ConcurrentHashMap; 54 import sun.misc.ClassFileTransformer; 55 import sun.misc.CompoundEnumeration; 56 import sun.misc.Resource; 57 import sun.misc.URLClassPath; 58 import sun.misc.VM; 59 import sun.reflect.Reflection; 60 import sun.security.util.SecurityConstants; 61 62 /** 63 * A class loader is an object that is responsible for loading classes. The 64 * class <tt>ClassLoader</tt> is an abstract class. Given the <a 65 * href="#name">binary name</a> of a class, a class loader should attempt to 66 * locate or generate data that constitutes a definition for the class. A 67 * typical strategy is to transform the name into a file name and then read a 68 * "class file" of that name from a file system. 69 * 70 * <p> Every {@link Class <tt>Class</tt>} object contains a {@link 71 * Class#getClassLoader() reference} to the <tt>ClassLoader</tt> that defined 72 * it. 73 * 74 * <p> <tt>Class</tt> objects for array classes are not created by class 75 * loaders, but are created automatically as required by the Java runtime. 76 * The class loader for an array class, as returned by {@link 77 * Class#getClassLoader()} is the same as the class loader for its element 78 * type; if the element type is a primitive type, then the array class has no 79 * class loader. 80 * 81 * <p> Applications implement subclasses of <tt>ClassLoader</tt> in order to 82 * extend the manner in which the Java virtual machine dynamically loads 83 * classes. 84 * 85 * <p> Class loaders may typically be used by security managers to indicate 86 * security domains. 87 * 88 * <p> The <tt>ClassLoader</tt> class uses a delegation model to search for 89 * classes and resources. Each instance of <tt>ClassLoader</tt> has an 90 * associated parent class loader. When requested to find a class or 91 * resource, a <tt>ClassLoader</tt> instance will delegate the search for the 92 * class or resource to its parent class loader before attempting to find the 93 * class or resource itself. The virtual machine's built-in class loader, 94 * called the "bootstrap class loader", does not itself have a parent but may 95 * serve as the parent of a <tt>ClassLoader</tt> instance. 96 * 97 * <p> Class loaders that support concurrent loading of classes are known as 98 * <em>parallel capable</em> class loaders and are required to register 99 * themselves at their class initialization time by invoking the 100 * {@link 101 * #registerAsParallelCapable <tt>ClassLoader.registerAsParallelCapable</tt>} 102 * method. Note that the <tt>ClassLoader</tt> class is registered as parallel 103 * capable by default. However, its subclasses still need to register themselves 104 * if they are parallel capable. <br> 105 * In environments in which the delegation model is not strictly 106 * hierarchical, class loaders need to be parallel capable, otherwise class 107 * loading can lead to deadlocks because the loader lock is held for the 108 * duration of the class loading process (see {@link #loadClass 109 * <tt>loadClass</tt>} methods). 110 * 111 * <p>Regular parallel capable class loaders may still need to use some form 112 * of synchronization to control concurrent load attempts of a given class. 113 * The {@link #getClassLoadingLock getClassLoadingLock} method is used to 114 * provide that object for use by {@link #loadClass loadClass}. A class loader 115 * can support fully concurrent loading of any class, in which case no 116 * synchronization need be used. Such parallel capable class loaders are 117 * required to register themselves at their class initialization time by 118 * invoking the 119 * {@link #registerAsFullyConcurrent registerAsFullyConcurrent} method. 120 * Note that the <tt>ClassLoader</tt> class is registered as fully 121 * concurrent by default. However, its subclasses still need to register 122 * themselves if they capable of fully concurrent class loading. 123 * 124 * <p> Normally, the Java virtual machine loads classes from the local file 125 * system in a platform-dependent manner. For example, on UNIX systems, the 126 * virtual machine loads classes from the directory defined by the 127 * <tt>CLASSPATH</tt> environment variable. 128 * 129 * <p> However, some classes may not originate from a file; they may originate 130 * from other sources, such as the network, or they could be constructed by an 131 * application. The method {@link #defineClass(String, byte[], int, int) 132 * <tt>defineClass</tt>} converts an array of bytes into an instance of class 133 * <tt>Class</tt>. Instances of this newly defined class can be created using 134 * {@link Class#newInstance <tt>Class.newInstance</tt>}. 135 * 136 * <p> The methods and constructors of objects created by a class loader may 137 * reference other classes. To determine the class(es) referred to, the Java 138 * virtual machine invokes the {@link #loadClass <tt>loadClass</tt>} method of 139 * the class loader that originally created the class. 140 * 141 * <p> For example, an application could create a network class loader to 142 * download class files from a server. Sample code might look like: 143 * 144 * <blockquote><pre> 145 * ClassLoader loader = new NetworkClassLoader(host, port); 146 * Object main = loader.loadClass("Main", true).newInstance(); 147 * . . . 148 * </pre></blockquote> 149 * 150 * <p> The network class loader subclass must define the methods {@link 151 * #findClass <tt>findClass</tt>} and <tt>loadClassData</tt> to load a class 152 * from the network. Once it has downloaded the bytes that make up the class, 153 * it should use the method {@link #defineClass <tt>defineClass</tt>} to 154 * create a class instance. A sample implementation is: 155 * 156 * <blockquote><pre> 157 * class NetworkClassLoader extends ClassLoader { 158 * String host; 159 * int port; 160 * 161 * public Class findClass(String name) { 162 * byte[] b = loadClassData(name); 163 * return defineClass(name, b, 0, b.length); 164 * } 165 * 166 * private byte[] loadClassData(String name) { 167 * // load the class data from the connection 168 * . . . 169 * } 170 * } 171 * </pre></blockquote> 172 * 173 * <h4> <a name="name">Binary names</a> </h4> 174 * 175 * <p> Any class name provided as a {@link String} parameter to methods in 176 * <tt>ClassLoader</tt> must be a binary name as defined by 177 * <cite>The Java™ Language Specification</cite>. 178 * 179 * <p> Examples of valid class names include: 180 * <blockquote><pre> 181 * "java.lang.String" 182 * "javax.swing.JSpinner$DefaultEditor" 183 * "java.security.KeyStore$Builder$FileBuilder$1" 184 * "java.net.URLClassLoader$3$1" 185 * </pre></blockquote> 186 * 187 * @see #resolveClass(Class) 188 * @since 1.0 189 */ 190 public abstract class ClassLoader { 191 192 private static native void registerNatives(); 193 static { 194 registerNatives(); 195 } 196 197 // The parent class loader for delegation 198 // Note: VM hardcoded the offset of this field, thus all new fields 199 // must be added *after* it. 200 private final ClassLoader parent; 201 202 /** 203 * Encapsulates the set of parallel capable loader types. 204 */ 205 private static class ParallelLoaders { 206 private ParallelLoaders() {} 207 208 // the set of parallel capable loader types 209 // - loader in the map -> parallel capable 210 // - loader maps to TRUE -> fully concurrent 211 private static final WeakHashMap<Class<? extends ClassLoader>, 212 Boolean> loaderTypes = 213 new WeakHashMap<>(); 214 215 static { 216 synchronized (loaderTypes) { loaderTypes.put(ClassLoader.class, Boolean.TRUE); } 217 } 218 219 /** 220 * Registers the given class loader type as parallel capable. 221 * Returns {@code true} is successfully registered; {@code false} if 222 * loader's super class is not registered. 223 */ 224 static boolean register(Class<? extends ClassLoader> c, 225 boolean fullyConcurrent) { 226 synchronized (loaderTypes) { 227 if (loaderTypes.containsKey(c.getSuperclass())) { 228 // register the class loader as parallel capable 229 // if and only if all of its super classes are. 230 // Note: given current classloading sequence, if 231 // the immediate super class is parallel capable, 232 // all the super classes higher up must be too. 233 loaderTypes.put(c, fullyConcurrent); 234 System.out.println("Registered: " + c.getName() + " as " + 235 (fullyConcurrent ? "fully concurrent " : " parallel capable") + " classloader"); 236 return true; 237 } else { 238 return false; 239 } 240 } 241 } 242 243 /** 244 * Returns the value of the given loader in the parallel 245 * loader map, else null. 246 */ 247 static Boolean getRegistration(Class<? extends ClassLoader> c) { 248 synchronized(loaderTypes) { 249 return loaderTypes.get(c); 250 } 251 } 252 } 253 254 // Maps class name to the corresponding lock object when the current 255 // class loader is parallel capable. 256 // Note: VM also uses this field to decide if the current class loader 257 // is parallel capable and the appropriate lock object for class loading. 258 private final ConcurrentHashMap<String, Object> parallelLockMap; 259 260 // Indicates this parallel capable loader supports fully concurrent loading 261 // Note: the VM uses this field to decide if the current class loader 262 // allows parallel class definition 263 private final boolean isFullyConcurrent; 264 265 // Indicate if this loader is parallel capable 266 private boolean isParallelCapable() { 267 return parallelLockMap != null || isFullyConcurrent; 268 } 269 270 // Hashtable that maps packages to certs 271 private final Map <String, Certificate[]> package2certs; 272 273 // Shared among all packages with unsigned classes 274 private static final Certificate[] nocerts = new Certificate[0]; 275 276 // The classes loaded by this class loader. The only purpose of this table 277 // is to keep the classes from being GC'ed until the loader is GC'ed. 278 private final Vector<Class<?>> classes = new Vector<>(); 279 280 // The "default" domain. Set as the default ProtectionDomain on newly 281 // created classes. 282 private final ProtectionDomain defaultDomain = 283 new ProtectionDomain(new CodeSource(null, (Certificate[]) null), 284 null, this, null); 285 286 // The initiating protection domains for all classes loaded by this loader 287 private final Set<ProtectionDomain> domains; 288 289 // Invoked by the VM to record every loaded class with this loader. 290 void addClass(Class<?> c) { 291 classes.addElement(c); 292 } 293 294 // The packages defined in this class loader. Each package name is mapped 295 // to its corresponding Package object. 296 // @GuardedBy("itself") 297 private final HashMap<String, Package> packages = new HashMap<>(); 298 299 private static Void checkCreateClassLoader() { 300 SecurityManager security = System.getSecurityManager(); 301 if (security != null) { 302 security.checkCreateClassLoader(); 303 } 304 return null; 305 } 306 307 private ClassLoader(Void unused, ClassLoader parent) { 308 this.parent = parent; 309 Boolean reg = ParallelLoaders.getRegistration(this.getClass()); 310 if (reg != null) { 311 isFullyConcurrent = reg; 312 if (isFullyConcurrent) 313 parallelLockMap = null; 314 else 315 parallelLockMap = new ConcurrentHashMap<>(); 316 package2certs = new ConcurrentHashMap<>(); 317 domains = 318 Collections.synchronizedSet(new HashSet<ProtectionDomain>()); 319 assertionLock = new Object(); 320 } else { 321 // no finer-grained lock; lock on the classloader instance 322 isFullyConcurrent = false; 323 parallelLockMap = null; 324 package2certs = new Hashtable<>(); 325 domains = new HashSet<>(); 326 assertionLock = this; 327 } 328 } 329 330 /** 331 * Creates a new class loader using the specified parent class loader for 332 * delegation. 333 * 334 * <p> If there is a security manager, its {@link 335 * SecurityManager#checkCreateClassLoader() 336 * <tt>checkCreateClassLoader</tt>} method is invoked. This may result in 337 * a security exception. </p> 338 * 339 * @param parent 340 * The parent class loader 341 * 342 * @throws SecurityException 343 * If a security manager exists and its 344 * <tt>checkCreateClassLoader</tt> method doesn't allow creation 345 * of a new class loader. 346 * 347 * @since 1.2 348 */ 349 protected ClassLoader(ClassLoader parent) { 350 this(checkCreateClassLoader(), parent); 351 } 352 353 /** 354 * Creates a new class loader using the <tt>ClassLoader</tt> returned by 355 * the method {@link #getSystemClassLoader() 356 * <tt>getSystemClassLoader()</tt>} as the parent class loader. 357 * 358 * <p> If there is a security manager, its {@link 359 * SecurityManager#checkCreateClassLoader() 360 * <tt>checkCreateClassLoader</tt>} method is invoked. This may result in 361 * a security exception. </p> 362 * 363 * @throws SecurityException 364 * If a security manager exists and its 365 * <tt>checkCreateClassLoader</tt> method doesn't allow creation 366 * of a new class loader. 367 */ 368 protected ClassLoader() { 369 this(checkCreateClassLoader(), getSystemClassLoader()); 370 } 371 372 // -- Class -- 373 374 /** 375 * Loads the class with the specified <a href="#name">binary name</a>. 376 * This method searches for classes in the same manner as the {@link 377 * #loadClass(String, boolean)} method. It is invoked by the Java virtual 378 * machine to resolve class references. Invoking this method is equivalent 379 * to invoking {@link #loadClass(String, boolean) <tt>loadClass(name, 380 * false)</tt>}. </p> 381 * 382 * @param name 383 * The <a href="#name">binary name</a> of the class 384 * 385 * @return The resulting <tt>Class</tt> object 386 * 387 * @throws ClassNotFoundException 388 * If the class was not found 389 */ 390 public Class<?> loadClass(String name) throws ClassNotFoundException { 391 return loadClass(name, false); 392 } 393 394 /** 395 * Loads the class with the specified <a href="#name">binary name</a>. The 396 * default implementation of this method searches for classes in the 397 * following order: 398 * 399 * <p><ol> 400 * 401 * <li><p> Invoke {@link #findLoadedClass(String)} to check if the class 402 * has already been loaded. </p></li> 403 * 404 * <li><p> Invoke the {@link #loadClass(String) <tt>loadClass</tt>} method 405 * on the parent class loader. If the parent is <tt>null</tt> the class 406 * loader built-in to the virtual machine is used, instead. </p></li> 407 * 408 * <li><p> Invoke the {@link #findClass(String)} method to find the 409 * class. </p></li> 410 * 411 * </ol> 412 * 413 * <p> If the class was found using the above steps, and the 414 * <tt>resolve</tt> flag is true, this method will then invoke the {@link 415 * #resolveClass(Class)} method on the resulting <tt>Class</tt> object. 416 * 417 * <p> Subclasses of <tt>ClassLoader</tt> are encouraged to override {@link 418 * #findClass(String)}, rather than this method. </p> 419 * 420 * <p> Unless overridden, if this loader is not fully concurrent then 421 * this method synchronizes on the result 422 * of the {@link #getClassLoadingLock <tt>getClassLoadingLock</tt>} method 423 * during the entire class loading process. For a fully concurrent loader 424 * no synchronization occurs. 425 * 426 * @param name 427 * The <a href="#name">binary name</a> of the class 428 * 429 * @param resolve 430 * If <tt>true</tt> then resolve the class 431 * 432 * @return The resulting <tt>Class</tt> object 433 * 434 * @throws ClassNotFoundException 435 * If the class could not be found 436 */ 437 protected Class<?> loadClass(String name, boolean resolve) 438 throws ClassNotFoundException 439 { 440 Class<?> c = null; 441 if (!isFullyConcurrent) { 442 synchronized (getClassLoadingLock(name)) { 443 c = do_loadClass(name); 444 if (resolve) { 445 resolveClass(c); 446 } 447 } 448 } 449 else { 450 c = do_loadClass(name); 451 if (resolve) { 452 resolveClass(c); 453 } 454 } 455 return c; 456 } 457 458 459 private Class<?> do_loadClass(String name) 460 throws ClassNotFoundException 461 { 462 // First, check if the class has already been loaded 463 Class<?> c = findLoadedClass(name); 464 if (c == null) { 465 long t0 = System.nanoTime(); 466 try { 467 if (parent != null) { 468 c = parent.loadClass(name, false); 469 } else { 470 c = findBootstrapClassOrNull(name); 471 } 472 } catch (ClassNotFoundException e) { 473 // ClassNotFoundException thrown if class not found 474 // from the non-null parent class loader 475 } 476 477 if (c == null) { 478 // If still not found, then invoke findClass in order 479 // to find the class. 480 long t1 = System.nanoTime(); 481 c = findClass(name); 482 483 // this is the defining class loader; record the stats 484 sun.misc.PerfCounter.getParentDelegationTime().addTime(t1 - t0); 485 sun.misc.PerfCounter.getFindClassTime().addElapsedTimeFrom(t1); 486 sun.misc.PerfCounter.getFindClasses().increment(); 487 } 488 } 489 return c; 490 } 491 492 /** 493 * Returns the lock object for class loading operations. 494 * For backward compatibility, the default implementation of this method 495 * behaves as follows. If this ClassLoader object is registered as 496 * parallel capable, the method returns a dedicated object associated 497 * with the specified class name. Otherwise, the method returns this 498 * ClassLoader object. </p> 499 * 500 * @param className 501 * The name of the to-be-loaded class 502 * 503 * @return the lock for class loading operations 504 * 505 * @throws NullPointerException 506 * If registered as parallel capable and <tt>className</tt> is null 507 * 508 * @see #loadClass(String, boolean) 509 * 510 * @since 1.7 511 */ 512 protected Object getClassLoadingLock(String className) { 513 Object lock = this; 514 if (parallelLockMap != null) { 515 Object newLock = new Object(); 516 lock = parallelLockMap.putIfAbsent(className, newLock); 517 if (lock == null) { 518 lock = newLock; 519 } 520 } 521 else if (isFullyConcurrent) { 522 lock = null; // TBD: is this the best thing to return? 523 } 524 return lock; 525 } 526 527 // This method is invoked by the virtual machine to load a class. 528 private Class<?> loadClassInternal(String name) 529 throws ClassNotFoundException 530 { 531 // For backward compatibility, explicitly lock on 'this' when 532 // the current class loader is not parallel capable. 533 if (!isParallelCapable()) { 534 synchronized (this) { 535 return loadClass(name); 536 } 537 } else { 538 return loadClass(name); 539 } 540 } 541 542 // Invoked by the VM after loading class with this loader. 543 private void checkPackageAccess(Class<?> cls, ProtectionDomain pd) { 544 final SecurityManager sm = System.getSecurityManager(); 545 if (sm != null) { 546 final String name = cls.getName(); 547 final int i = name.lastIndexOf('.'); 548 if (i != -1) { 549 AccessController.doPrivileged(new PrivilegedAction<Void>() { 550 public Void run() { 551 sm.checkPackageAccess(name.substring(0, i)); 552 return null; 553 } 554 }, new AccessControlContext(new ProtectionDomain[] {pd})); 555 } 556 } 557 domains.add(pd); 558 } 559 560 /** 561 * Finds the class with the specified <a href="#name">binary name</a>. 562 * This method should be overridden by class loader implementations that 563 * follow the delegation model for loading classes, and will be invoked by 564 * the {@link #loadClass <tt>loadClass</tt>} method after checking the 565 * parent class loader for the requested class. The default implementation 566 * throws a <tt>ClassNotFoundException</tt>. </p> 567 * 568 * @param name 569 * The <a href="#name">binary name</a> of the class 570 * 571 * @return The resulting <tt>Class</tt> object 572 * 573 * @throws ClassNotFoundException 574 * If the class could not be found 575 * 576 * @since 1.2 577 */ 578 protected Class<?> findClass(String name) throws ClassNotFoundException { 579 throw new ClassNotFoundException(name); 580 } 581 582 /** 583 * Converts an array of bytes into an instance of class <tt>Class</tt>. 584 * Before the <tt>Class</tt> can be used it must be resolved. This method 585 * is deprecated in favor of the version that takes a <a 586 * href="#name">binary name</a> as its first argument, and is more secure. 587 * 588 * @param b 589 * The bytes that make up the class data. The bytes in positions 590 * <tt>off</tt> through <tt>off+len-1</tt> should have the format 591 * of a valid class file as defined by 592 * <cite>The Java™ Virtual Machine Specification</cite>. 593 * 594 * @param off 595 * The start offset in <tt>b</tt> of the class data 596 * 597 * @param len 598 * The length of the class data 599 * 600 * @return The <tt>Class</tt> object that was created from the specified 601 * class data 602 * 603 * @throws ClassFormatError 604 * If the data did not contain a valid class 605 * 606 * @throws IndexOutOfBoundsException 607 * If either <tt>off</tt> or <tt>len</tt> is negative, or if 608 * <tt>off+len</tt> is greater than <tt>b.length</tt>. 609 * 610 * @throws SecurityException 611 * If an attempt is made to add this class to a package that 612 * contains classes that were signed by a different set of 613 * certificates than this class, or if an attempt is made 614 * to define a class in a package with a fully-qualified name 615 * that starts with "{@code java.}". 616 * 617 * @see #loadClass(String, boolean) 618 * @see #resolveClass(Class) 619 * 620 * @deprecated Replaced by {@link #defineClass(String, byte[], int, int) 621 * defineClass(String, byte[], int, int)} 622 */ 623 @Deprecated 624 protected final Class<?> defineClass(byte[] b, int off, int len) 625 throws ClassFormatError 626 { 627 return defineClass(null, b, off, len, null); 628 } 629 630 /** 631 * Converts an array of bytes into an instance of class <tt>Class</tt>. 632 * Before the <tt>Class</tt> can be used it must be resolved. 633 * 634 * <p> This method assigns a default {@link java.security.ProtectionDomain 635 * <tt>ProtectionDomain</tt>} to the newly defined class. The 636 * <tt>ProtectionDomain</tt> is effectively granted the same set of 637 * permissions returned when {@link 638 * java.security.Policy#getPermissions(java.security.CodeSource) 639 * <tt>Policy.getPolicy().getPermissions(new CodeSource(null, null))</tt>} 640 * is invoked. The default domain is created on the first invocation of 641 * {@link #defineClass(String, byte[], int, int) <tt>defineClass</tt>}, 642 * and re-used on subsequent invocations. 643 * 644 * <p> To assign a specific <tt>ProtectionDomain</tt> to the class, use 645 * the {@link #defineClass(String, byte[], int, int, 646 * java.security.ProtectionDomain) <tt>defineClass</tt>} method that takes a 647 * <tt>ProtectionDomain</tt> as one of its arguments. </p> 648 * 649 * @param name 650 * The expected <a href="#name">binary name</a> of the class, or 651 * <tt>null</tt> if not known 652 * 653 * @param b 654 * The bytes that make up the class data. The bytes in positions 655 * <tt>off</tt> through <tt>off+len-1</tt> should have the format 656 * of a valid class file as defined by 657 * <cite>The Java™ Virtual Machine Specification</cite>. 658 * 659 * @param off 660 * The start offset in <tt>b</tt> of the class data 661 * 662 * @param len 663 * The length of the class data 664 * 665 * @return The <tt>Class</tt> object that was created from the specified 666 * class data. 667 * 668 * @throws ClassFormatError 669 * If the data did not contain a valid class 670 * 671 * @throws IndexOutOfBoundsException 672 * If either <tt>off</tt> or <tt>len</tt> is negative, or if 673 * <tt>off+len</tt> is greater than <tt>b.length</tt>. 674 * 675 * @throws SecurityException 676 * If an attempt is made to add this class to a package that 677 * contains classes that were signed by a different set of 678 * certificates than this class (which is unsigned), or if 679 * <tt>name</tt> begins with "<tt>java.</tt>". 680 * 681 * @see #loadClass(String, boolean) 682 * @see #resolveClass(Class) 683 * @see java.security.CodeSource 684 * @see java.security.SecureClassLoader 685 * 686 * @since 1.1 687 */ 688 protected final Class<?> defineClass(String name, byte[] b, int off, int len) 689 throws ClassFormatError 690 { 691 return defineClass(name, b, off, len, null); 692 } 693 694 /* Determine protection domain, and check that: 695 - not define java.* class, 696 - signer of this class matches signers for the rest of the classes in 697 package. 698 */ 699 private ProtectionDomain preDefineClass(String name, 700 ProtectionDomain pd) 701 { 702 if (!checkName(name)) 703 throw new NoClassDefFoundError("IllegalName: " + name); 704 705 if ((name != null) && name.startsWith("java.")) { 706 throw new SecurityException 707 ("Prohibited package name: " + 708 name.substring(0, name.lastIndexOf('.'))); 709 } 710 if (pd == null) { 711 pd = defaultDomain; 712 } 713 714 if (name != null) checkCerts(name, pd.getCodeSource()); 715 716 return pd; 717 } 718 719 private String defineClassSourceLocation(ProtectionDomain pd) 720 { 721 CodeSource cs = pd.getCodeSource(); 722 String source = null; 723 if (cs != null && cs.getLocation() != null) { 724 source = cs.getLocation().toString(); 725 } 726 return source; 727 } 728 729 private Class<?> defineTransformedClass(String name, byte[] b, int off, int len, 730 ProtectionDomain pd, 731 ClassFormatError cfe, String source) 732 throws ClassFormatError 733 { 734 // Class format error - try to transform the bytecode and 735 // define the class again 736 // 737 ClassFileTransformer[] transformers = 738 ClassFileTransformer.getTransformers(); 739 Class<?> c = null; 740 741 if (transformers != null) { 742 for (ClassFileTransformer transformer : transformers) { 743 try { 744 // Transform byte code using transformer 745 byte[] tb = transformer.transform(b, off, len); 746 c = defineClass1(name, tb, 0, tb.length, 747 pd, source); 748 break; 749 } catch (ClassFormatError cfe2) { 750 // If ClassFormatError occurs, try next transformer 751 } 752 } 753 } 754 755 // Rethrow original ClassFormatError if unable to transform 756 // bytecode to well-formed 757 // 758 if (c == null) 759 throw cfe; 760 761 return c; 762 } 763 764 private void postDefineClass(Class<?> c, ProtectionDomain pd) 765 { 766 if (pd.getCodeSource() != null) { 767 Certificate certs[] = pd.getCodeSource().getCertificates(); 768 if (certs != null) 769 setSigners(c, certs); 770 } 771 } 772 773 /** 774 * Converts an array of bytes into an instance of class <tt>Class</tt>, 775 * with an optional <tt>ProtectionDomain</tt>. If the domain is 776 * <tt>null</tt>, then a default domain will be assigned to the class as 777 * specified in the documentation for {@link #defineClass(String, byte[], 778 * int, int)}. Before the class can be used it must be resolved. 779 * 780 * <p> The first class defined in a package determines the exact set of 781 * certificates that all subsequent classes defined in that package must 782 * contain. The set of certificates for a class is obtained from the 783 * {@link java.security.CodeSource <tt>CodeSource</tt>} within the 784 * <tt>ProtectionDomain</tt> of the class. Any classes added to that 785 * package must contain the same set of certificates or a 786 * <tt>SecurityException</tt> will be thrown. Note that if 787 * <tt>name</tt> is <tt>null</tt>, this check is not performed. 788 * You should always pass in the <a href="#name">binary name</a> of the 789 * class you are defining as well as the bytes. This ensures that the 790 * class you are defining is indeed the class you think it is. 791 * 792 * <p> The specified <tt>name</tt> cannot begin with "<tt>java.</tt>", since 793 * all classes in the "<tt>java.*</tt> packages can only be defined by the 794 * bootstrap class loader. If <tt>name</tt> is not <tt>null</tt>, it 795 * must be equal to the <a href="#name">binary name</a> of the class 796 * specified by the byte array "<tt>b</tt>", otherwise a {@link 797 * <tt>NoClassDefFoundError</tt>} will be thrown. </p> 798 * 799 * @param name 800 * The expected <a href="#name">binary name</a> of the class, or 801 * <tt>null</tt> if not known 802 * 803 * @param b 804 * The bytes that make up the class data. The bytes in positions 805 * <tt>off</tt> through <tt>off+len-1</tt> should have the format 806 * of a valid class file as defined by 807 * <cite>The Java™ Virtual Machine Specification</cite>. 808 * 809 * @param off 810 * The start offset in <tt>b</tt> of the class data 811 * 812 * @param len 813 * The length of the class data 814 * 815 * @param protectionDomain 816 * The ProtectionDomain of the class 817 * 818 * @return The <tt>Class</tt> object created from the data, 819 * and optional <tt>ProtectionDomain</tt>. 820 * 821 * @throws ClassFormatError 822 * If the data did not contain a valid class 823 * 824 * @throws NoClassDefFoundError 825 * If <tt>name</tt> is not equal to the <a href="#name">binary 826 * name</a> of the class specified by <tt>b</tt> 827 * 828 * @throws IndexOutOfBoundsException 829 * If either <tt>off</tt> or <tt>len</tt> is negative, or if 830 * <tt>off+len</tt> is greater than <tt>b.length</tt>. 831 * 832 * @throws SecurityException 833 * If an attempt is made to add this class to a package that 834 * contains classes that were signed by a different set of 835 * certificates than this class, or if <tt>name</tt> begins with 836 * "<tt>java.</tt>". 837 */ 838 protected final Class<?> defineClass(String name, byte[] b, int off, int len, 839 ProtectionDomain protectionDomain) 840 throws ClassFormatError 841 { 842 protectionDomain = preDefineClass(name, protectionDomain); 843 844 Class<?> c = null; 845 String source = defineClassSourceLocation(protectionDomain); 846 847 try { 848 c = defineClass1(name, b, off, len, protectionDomain, source); 849 } catch (ClassFormatError cfe) { 850 c = defineTransformedClass(name, b, off, len, protectionDomain, cfe, 851 source); 852 } 853 854 postDefineClass(c, protectionDomain); 855 return c; 856 } 857 858 /** 859 * Converts a {@link java.nio.ByteBuffer <tt>ByteBuffer</tt>} 860 * into an instance of class <tt>Class</tt>, 861 * with an optional <tt>ProtectionDomain</tt>. If the domain is 862 * <tt>null</tt>, then a default domain will be assigned to the class as 863 * specified in the documentation for {@link #defineClass(String, byte[], 864 * int, int)}. Before the class can be used it must be resolved. 865 * 866 * <p>The rules about the first class defined in a package determining the 867 * set of certificates for the package, and the restrictions on class names 868 * are identical to those specified in the documentation for {@link 869 * #defineClass(String, byte[], int, int, ProtectionDomain)}. 870 * 871 * <p> An invocation of this method of the form 872 * <i>cl</i><tt>.defineClass(</tt><i>name</i><tt>,</tt> 873 * <i>bBuffer</i><tt>,</tt> <i>pd</i><tt>)</tt> yields exactly the same 874 * result as the statements 875 * 876 * <blockquote><tt> 877 * ...<br> 878 * byte[] temp = new byte[</tt><i>bBuffer</i><tt>.{@link 879 * java.nio.ByteBuffer#remaining remaining}()];<br> 880 * </tt><i>bBuffer</i><tt>.{@link java.nio.ByteBuffer#get(byte[]) 881 * get}(temp);<br> 882 * return {@link #defineClass(String, byte[], int, int, ProtectionDomain) 883 * </tt><i>cl</i><tt>.defineClass}(</tt><i>name</i><tt>, temp, 0, 884 * temp.length, </tt><i>pd</i><tt>);<br> 885 * </tt></blockquote> 886 * 887 * @param name 888 * The expected <a href="#name">binary name</a>. of the class, or 889 * <tt>null</tt> if not known 890 * 891 * @param b 892 * The bytes that make up the class data. The bytes from positions 893 * <tt>b.position()</tt> through <tt>b.position() + b.limit() -1 894 * </tt> should have the format of a valid class file as defined by 895 * <cite>The Java™ Virtual Machine Specification</cite>. 896 * 897 * @param protectionDomain 898 * The ProtectionDomain of the class, or <tt>null</tt>. 899 * 900 * @return The <tt>Class</tt> object created from the data, 901 * and optional <tt>ProtectionDomain</tt>. 902 * 903 * @throws ClassFormatError 904 * If the data did not contain a valid class. 905 * 906 * @throws NoClassDefFoundError 907 * If <tt>name</tt> is not equal to the <a href="#name">binary 908 * name</a> of the class specified by <tt>b</tt> 909 * 910 * @throws SecurityException 911 * If an attempt is made to add this class to a package that 912 * contains classes that were signed by a different set of 913 * certificates than this class, or if <tt>name</tt> begins with 914 * "<tt>java.</tt>". 915 * 916 * @see #defineClass(String, byte[], int, int, ProtectionDomain) 917 * 918 * @since 1.5 919 */ 920 protected final Class<?> defineClass(String name, java.nio.ByteBuffer b, 921 ProtectionDomain protectionDomain) 922 throws ClassFormatError 923 { 924 int len = b.remaining(); 925 926 // Use byte[] if not a direct ByteBufer: 927 if (!b.isDirect()) { 928 if (b.hasArray()) { 929 return defineClass(name, b.array(), 930 b.position() + b.arrayOffset(), len, 931 protectionDomain); 932 } else { 933 // no array, or read-only array 934 byte[] tb = new byte[len]; 935 b.get(tb); // get bytes out of byte buffer. 936 return defineClass(name, tb, 0, len, protectionDomain); 937 } 938 } 939 940 protectionDomain = preDefineClass(name, protectionDomain); 941 942 Class<?> c = null; 943 String source = defineClassSourceLocation(protectionDomain); 944 945 try { 946 c = defineClass2(name, b, b.position(), len, protectionDomain, 947 source); 948 } catch (ClassFormatError cfe) { 949 byte[] tb = new byte[len]; 950 b.get(tb); // get bytes out of byte buffer. 951 c = defineTransformedClass(name, tb, 0, len, protectionDomain, cfe, 952 source); 953 } 954 955 postDefineClass(c, protectionDomain); 956 return c; 957 } 958 959 private native Class<?> defineClass0(String name, byte[] b, int off, int len, 960 ProtectionDomain pd); 961 962 private native Class<?> defineClass1(String name, byte[] b, int off, int len, 963 ProtectionDomain pd, String source); 964 965 private native Class<?> defineClass2(String name, java.nio.ByteBuffer b, 966 int off, int len, ProtectionDomain pd, 967 String source); 968 969 // true if the name is null or has the potential to be a valid binary name 970 private boolean checkName(String name) { 971 if ((name == null) || (name.length() == 0)) 972 return true; 973 if ((name.indexOf('/') != -1) 974 || (!VM.allowArraySyntax() && (name.charAt(0) == '['))) 975 return false; 976 return true; 977 } 978 979 private void checkCerts(String name, CodeSource cs) { 980 int i = name.lastIndexOf('.'); 981 String pname = (i == -1) ? "" : name.substring(0, i); 982 983 Certificate[] certs = null; 984 if (cs != null) { 985 certs = cs.getCertificates(); 986 } 987 Certificate[] pcerts = null; 988 if (!isParallelCapable()) { 989 synchronized (this) { 990 pcerts = package2certs.get(pname); 991 if (pcerts == null) { 992 package2certs.put(pname, (certs == null? nocerts:certs)); 993 } 994 } 995 } else { 996 pcerts = ((ConcurrentHashMap<String, Certificate[]>)package2certs). 997 putIfAbsent(pname, (certs == null? nocerts:certs)); 998 } 999 if (pcerts != null && !compareCerts(pcerts, certs)) { 1000 throw new SecurityException("class \""+ name + 1001 "\"'s signer information does not match signer information of other classes in the same package"); 1002 } 1003 } 1004 1005 /** 1006 * check to make sure the certs for the new class (certs) are the same as 1007 * the certs for the first class inserted in the package (pcerts) 1008 */ 1009 private boolean compareCerts(Certificate[] pcerts, 1010 Certificate[] certs) 1011 { 1012 // certs can be null, indicating no certs. 1013 if ((certs == null) || (certs.length == 0)) { 1014 return pcerts.length == 0; 1015 } 1016 1017 // the length must be the same at this point 1018 if (certs.length != pcerts.length) 1019 return false; 1020 1021 // go through and make sure all the certs in one array 1022 // are in the other and vice-versa. 1023 boolean match; 1024 for (int i = 0; i < certs.length; i++) { 1025 match = false; 1026 for (int j = 0; j < pcerts.length; j++) { 1027 if (certs[i].equals(pcerts[j])) { 1028 match = true; 1029 break; 1030 } 1031 } 1032 if (!match) return false; 1033 } 1034 1035 // now do the same for pcerts 1036 for (int i = 0; i < pcerts.length; i++) { 1037 match = false; 1038 for (int j = 0; j < certs.length; j++) { 1039 if (pcerts[i].equals(certs[j])) { 1040 match = true; 1041 break; 1042 } 1043 } 1044 if (!match) return false; 1045 } 1046 1047 return true; 1048 } 1049 1050 /** 1051 * Links the specified class. This (misleadingly named) method may be 1052 * used by a class loader to link a class. If the class <tt>c</tt> has 1053 * already been linked, then this method simply returns. Otherwise, the 1054 * class is linked as described in the "Execution" chapter of 1055 * <cite>The Java™ Language Specification</cite>. 1056 * </p> 1057 * 1058 * @param c 1059 * The class to link 1060 * 1061 * @throws NullPointerException 1062 * If <tt>c</tt> is <tt>null</tt>. 1063 * 1064 * @see #defineClass(String, byte[], int, int) 1065 */ 1066 protected final void resolveClass(Class<?> c) { 1067 resolveClass0(c); 1068 } 1069 1070 private native void resolveClass0(Class<?> c); 1071 1072 /** 1073 * Finds a class with the specified <a href="#name">binary name</a>, 1074 * loading it if necessary. 1075 * 1076 * <p> This method loads the class through the system class loader (see 1077 * {@link #getSystemClassLoader()}). The <tt>Class</tt> object returned 1078 * might have more than one <tt>ClassLoader</tt> associated with it. 1079 * Subclasses of <tt>ClassLoader</tt> need not usually invoke this method, 1080 * because most class loaders need to override just {@link 1081 * #findClass(String)}. </p> 1082 * 1083 * @param name 1084 * The <a href="#name">binary name</a> of the class 1085 * 1086 * @return The <tt>Class</tt> object for the specified <tt>name</tt> 1087 * 1088 * @throws ClassNotFoundException 1089 * If the class could not be found 1090 * 1091 * @see #ClassLoader(ClassLoader) 1092 * @see #getParent() 1093 */ 1094 protected final Class<?> findSystemClass(String name) 1095 throws ClassNotFoundException 1096 { 1097 ClassLoader system = getSystemClassLoader(); 1098 if (system == null) { 1099 if (!checkName(name)) 1100 throw new ClassNotFoundException(name); 1101 Class<?> cls = findBootstrapClass(name); 1102 if (cls == null) { 1103 throw new ClassNotFoundException(name); 1104 } 1105 return cls; 1106 } 1107 return system.loadClass(name); 1108 } 1109 1110 /** 1111 * Returns a class loaded by the bootstrap class loader; 1112 * or return null if not found. 1113 */ 1114 private Class<?> findBootstrapClassOrNull(String name) 1115 { 1116 if (!checkName(name)) return null; 1117 1118 return findBootstrapClass(name); 1119 } 1120 1121 // return null if not found 1122 private native Class<?> findBootstrapClass(String name); 1123 1124 /** 1125 * Returns the class with the given <a href="#name">binary name</a> if this 1126 * loader has been recorded by the Java virtual machine as an initiating 1127 * loader of a class with that <a href="#name">binary name</a>. Otherwise 1128 * <tt>null</tt> is returned. </p> 1129 * 1130 * @param name 1131 * The <a href="#name">binary name</a> of the class 1132 * 1133 * @return The <tt>Class</tt> object, or <tt>null</tt> if the class has 1134 * not been loaded 1135 * 1136 * @since 1.1 1137 */ 1138 protected final Class<?> findLoadedClass(String name) { 1139 if (!checkName(name)) 1140 return null; 1141 return findLoadedClass0(name); 1142 } 1143 1144 private native final Class<?> findLoadedClass0(String name); 1145 1146 /** 1147 * Sets the signers of a class. This should be invoked after defining a 1148 * class. </p> 1149 * 1150 * @param c 1151 * The <tt>Class</tt> object 1152 * 1153 * @param signers 1154 * The signers for the class 1155 * 1156 * @since 1.1 1157 */ 1158 protected final void setSigners(Class<?> c, Object[] signers) { 1159 c.setSigners(signers); 1160 } 1161 1162 1163 // -- Resource -- 1164 1165 /** 1166 * Finds the resource with the given name. A resource is some data 1167 * (images, audio, text, etc) that can be accessed by class code in a way 1168 * that is independent of the location of the code. 1169 * 1170 * <p> The name of a resource is a '<tt>/</tt>'-separated path name that 1171 * identifies the resource. 1172 * 1173 * <p> This method will first search the parent class loader for the 1174 * resource; if the parent is <tt>null</tt> the path of the class loader 1175 * built-in to the virtual machine is searched. That failing, this method 1176 * will invoke {@link #findResource(String)} to find the resource. </p> 1177 * 1178 * @param name 1179 * The resource name 1180 * 1181 * @return A <tt>URL</tt> object for reading the resource, or 1182 * <tt>null</tt> if the resource could not be found or the invoker 1183 * doesn't have adequate privileges to get the resource. 1184 * 1185 * @since 1.1 1186 */ 1187 public URL getResource(String name) { 1188 URL url; 1189 if (parent != null) { 1190 url = parent.getResource(name); 1191 } else { 1192 url = getBootstrapResource(name); 1193 } 1194 if (url == null) { 1195 url = findResource(name); 1196 } 1197 return url; 1198 } 1199 1200 /** 1201 * Finds all the resources with the given name. A resource is some data 1202 * (images, audio, text, etc) that can be accessed by class code in a way 1203 * that is independent of the location of the code. 1204 * 1205 * <p>The name of a resource is a <tt>/</tt>-separated path name that 1206 * identifies the resource. 1207 * 1208 * <p> The search order is described in the documentation for {@link 1209 * #getResource(String)}. </p> 1210 * 1211 * @param name 1212 * The resource name 1213 * 1214 * @return An enumeration of {@link java.net.URL <tt>URL</tt>} objects for 1215 * the resource. If no resources could be found, the enumeration 1216 * will be empty. Resources that the class loader doesn't have 1217 * access to will not be in the enumeration. 1218 * 1219 * @throws IOException 1220 * If I/O errors occur 1221 * 1222 * @see #findResources(String) 1223 * 1224 * @since 1.2 1225 */ 1226 public Enumeration<URL> getResources(String name) throws IOException { 1227 @SuppressWarnings("unchecked") 1228 Enumeration<URL>[] tmp = (Enumeration<URL>[]) new Enumeration<?>[2]; 1229 if (parent != null) { 1230 tmp[0] = parent.getResources(name); 1231 } else { 1232 tmp[0] = getBootstrapResources(name); 1233 } 1234 tmp[1] = findResources(name); 1235 1236 return new CompoundEnumeration<>(tmp); 1237 } 1238 1239 /** 1240 * Finds the resource with the given name. Class loader implementations 1241 * should override this method to specify where to find resources. </p> 1242 * 1243 * @param name 1244 * The resource name 1245 * 1246 * @return A <tt>URL</tt> object for reading the resource, or 1247 * <tt>null</tt> if the resource could not be found 1248 * 1249 * @since 1.2 1250 */ 1251 protected URL findResource(String name) { 1252 return null; 1253 } 1254 1255 /** 1256 * Returns an enumeration of {@link java.net.URL <tt>URL</tt>} objects 1257 * representing all the resources with the given name. Class loader 1258 * implementations should override this method to specify where to load 1259 * resources from. </p> 1260 * 1261 * @param name 1262 * The resource name 1263 * 1264 * @return An enumeration of {@link java.net.URL <tt>URL</tt>} objects for 1265 * the resources 1266 * 1267 * @throws IOException 1268 * If I/O errors occur 1269 * 1270 * @since 1.2 1271 */ 1272 protected Enumeration<URL> findResources(String name) throws IOException { 1273 return java.util.Collections.emptyEnumeration(); 1274 } 1275 1276 // index 0: java.lang.ClassLoader.class 1277 // index 1: the immediate caller of index 0. 1278 // index 2: the immediate caller of index 1. 1279 private static native Class<? extends ClassLoader> getCaller(int index); 1280 1281 /** 1282 * Registers the caller as parallel capable.</p> 1283 * The registration succeeds if and only if all of the following 1284 * conditions are met: <br> 1285 * 1. no instance of the caller has been created</p> 1286 * 2. all of the super classes (except class Object) of the caller are 1287 * registered as parallel capable</p> 1288 * Note that once a class loader is registered as parallel capable, there 1289 * is no way to change it back. </p> 1290 * <p> 1291 * Class loaders that are fully concurrent parallel capable should 1292 * use {@link #registerAsFullyConcurrent} to register. </p> 1293 * 1294 * @return true if the caller is successfully registered as 1295 * parallel capable and false if otherwise. 1296 * 1297 * @since 1.7 1298 */ 1299 protected static boolean registerAsParallelCapable() { 1300 return ParallelLoaders.register(getCaller(1), false); 1301 } 1302 1303 /** 1304 * Registers the caller as a fully concurrent parallel capable 1305 * class loader.</p> 1306 * The registration succeeds if and only if all of the following 1307 * conditions are met: <br> 1308 * 1. no instance of the caller has been created</p> 1309 * 2. all of the super classes (except class Object) of the caller are 1310 * registered as parallel capable</p> 1311 * Note that once a class loader is registered as fully concurrent 1312 * parallel capable, there is no way to change it back. </p> 1313 * 1314 * @return true if the caller is successfully registered as 1315 * fully concurrent parallel capable and false if otherwise. 1316 * 1317 * @since 1.8 1318 */ 1319 protected static boolean registerAsFullyConcurrent() { 1320 return ParallelLoaders.register(getCaller(1), true); 1321 } 1322 1323 /** 1324 * Find a resource of the specified name from the search path used to load 1325 * classes. This method locates the resource through the system class 1326 * loader (see {@link #getSystemClassLoader()}). </p> 1327 * 1328 * @param name 1329 * The resource name 1330 * 1331 * @return A {@link java.net.URL <tt>URL</tt>} object for reading the 1332 * resource, or <tt>null</tt> if the resource could not be found 1333 * 1334 * @since 1.1 1335 */ 1336 public static URL getSystemResource(String name) { 1337 ClassLoader system = getSystemClassLoader(); 1338 if (system == null) { 1339 return getBootstrapResource(name); 1340 } 1341 return system.getResource(name); 1342 } 1343 1344 /** 1345 * Finds all resources of the specified name from the search path used to 1346 * load classes. The resources thus found are returned as an 1347 * {@link java.util.Enumeration <tt>Enumeration</tt>} of {@link 1348 * java.net.URL <tt>URL</tt>} objects. 1349 * 1350 * <p> The search order is described in the documentation for {@link 1351 * #getSystemResource(String)}. </p> 1352 * 1353 * @param name 1354 * The resource name 1355 * 1356 * @return An enumeration of resource {@link java.net.URL <tt>URL</tt>} 1357 * objects 1358 * 1359 * @throws IOException 1360 * If I/O errors occur 1361 1362 * @since 1.2 1363 */ 1364 public static Enumeration<URL> getSystemResources(String name) 1365 throws IOException 1366 { 1367 ClassLoader system = getSystemClassLoader(); 1368 if (system == null) { 1369 return getBootstrapResources(name); 1370 } 1371 return system.getResources(name); 1372 } 1373 1374 /** 1375 * Find resources from the VM's built-in classloader. 1376 */ 1377 private static URL getBootstrapResource(String name) { 1378 URLClassPath ucp = getBootstrapClassPath(); 1379 Resource res = ucp.getResource(name); 1380 return res != null ? res.getURL() : null; 1381 } 1382 1383 /** 1384 * Find resources from the VM's built-in classloader. 1385 */ 1386 private static Enumeration<URL> getBootstrapResources(String name) 1387 throws IOException 1388 { 1389 final Enumeration<Resource> e = 1390 getBootstrapClassPath().getResources(name); 1391 return new Enumeration<URL> () { 1392 public URL nextElement() { 1393 return e.nextElement().getURL(); 1394 } 1395 public boolean hasMoreElements() { 1396 return e.hasMoreElements(); 1397 } 1398 }; 1399 } 1400 1401 // Returns the URLClassPath that is used for finding system resources. 1402 static URLClassPath getBootstrapClassPath() { 1403 return sun.misc.Launcher.getBootstrapClassPath(); 1404 } 1405 1406 1407 /** 1408 * Returns an input stream for reading the specified resource. 1409 * 1410 * <p> The search order is described in the documentation for {@link 1411 * #getResource(String)}. </p> 1412 * 1413 * @param name 1414 * The resource name 1415 * 1416 * @return An input stream for reading the resource, or <tt>null</tt> 1417 * if the resource could not be found 1418 * 1419 * @since 1.1 1420 */ 1421 public InputStream getResourceAsStream(String name) { 1422 URL url = getResource(name); 1423 try { 1424 return url != null ? url.openStream() : null; 1425 } catch (IOException e) { 1426 return null; 1427 } 1428 } 1429 1430 /** 1431 * Open for reading, a resource of the specified name from the search path 1432 * used to load classes. This method locates the resource through the 1433 * system class loader (see {@link #getSystemClassLoader()}). </p> 1434 * 1435 * @param name 1436 * The resource name 1437 * 1438 * @return An input stream for reading the resource, or <tt>null</tt> 1439 * if the resource could not be found 1440 * 1441 * @since 1.1 1442 */ 1443 public static InputStream getSystemResourceAsStream(String name) { 1444 URL url = getSystemResource(name); 1445 try { 1446 return url != null ? url.openStream() : null; 1447 } catch (IOException e) { 1448 return null; 1449 } 1450 } 1451 1452 1453 // -- Hierarchy -- 1454 1455 /** 1456 * Returns the parent class loader for delegation. Some implementations may 1457 * use <tt>null</tt> to represent the bootstrap class loader. This method 1458 * will return <tt>null</tt> in such implementations if this class loader's 1459 * parent is the bootstrap class loader. 1460 * 1461 * <p> If a security manager is present, and the invoker's class loader is 1462 * not <tt>null</tt> and is not an ancestor of this class loader, then this 1463 * method invokes the security manager's {@link 1464 * SecurityManager#checkPermission(java.security.Permission) 1465 * <tt>checkPermission</tt>} method with a {@link 1466 * RuntimePermission#RuntimePermission(String) 1467 * <tt>RuntimePermission("getClassLoader")</tt>} permission to verify 1468 * access to the parent class loader is permitted. If not, a 1469 * <tt>SecurityException</tt> will be thrown. </p> 1470 * 1471 * @return The parent <tt>ClassLoader</tt> 1472 * 1473 * @throws SecurityException 1474 * If a security manager exists and its <tt>checkPermission</tt> 1475 * method doesn't allow access to this class loader's parent class 1476 * loader. 1477 * 1478 * @since 1.2 1479 */ 1480 public final ClassLoader getParent() { 1481 if (parent == null) 1482 return null; 1483 SecurityManager sm = System.getSecurityManager(); 1484 if (sm != null) { 1485 ClassLoader ccl = getCallerClassLoader(); 1486 if (needsClassLoaderPermissionCheck(ccl, this)) { 1487 sm.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION); 1488 } 1489 } 1490 return parent; 1491 } 1492 1493 /** 1494 * Returns the system class loader for delegation. This is the default 1495 * delegation parent for new <tt>ClassLoader</tt> instances, and is 1496 * typically the class loader used to start the application. 1497 * 1498 * <p> This method is first invoked early in the runtime's startup 1499 * sequence, at which point it creates the system class loader and sets it 1500 * as the context class loader of the invoking <tt>Thread</tt>. 1501 * 1502 * <p> The default system class loader is an implementation-dependent 1503 * instance of this class. 1504 * 1505 * <p> If the system property "<tt>java.system.class.loader</tt>" is defined 1506 * when this method is first invoked then the value of that property is 1507 * taken to be the name of a class that will be returned as the system 1508 * class loader. The class is loaded using the default system class loader 1509 * and must define a public constructor that takes a single parameter of 1510 * type <tt>ClassLoader</tt> which is used as the delegation parent. An 1511 * instance is then created using this constructor with the default system 1512 * class loader as the parameter. The resulting class loader is defined 1513 * to be the system class loader. 1514 * 1515 * <p> If a security manager is present, and the invoker's class loader is 1516 * not <tt>null</tt> and the invoker's class loader is not the same as or 1517 * an ancestor of the system class loader, then this method invokes the 1518 * security manager's {@link 1519 * SecurityManager#checkPermission(java.security.Permission) 1520 * <tt>checkPermission</tt>} method with a {@link 1521 * RuntimePermission#RuntimePermission(String) 1522 * <tt>RuntimePermission("getClassLoader")</tt>} permission to verify 1523 * access to the system class loader. If not, a 1524 * <tt>SecurityException</tt> will be thrown. </p> 1525 * 1526 * @return The system <tt>ClassLoader</tt> for delegation, or 1527 * <tt>null</tt> if none 1528 * 1529 * @throws SecurityException 1530 * If a security manager exists and its <tt>checkPermission</tt> 1531 * method doesn't allow access to the system class loader. 1532 * 1533 * @throws IllegalStateException 1534 * If invoked recursively during the construction of the class 1535 * loader specified by the "<tt>java.system.class.loader</tt>" 1536 * property. 1537 * 1538 * @throws Error 1539 * If the system property "<tt>java.system.class.loader</tt>" 1540 * is defined but the named class could not be loaded, the 1541 * provider class does not define the required constructor, or an 1542 * exception is thrown by that constructor when it is invoked. The 1543 * underlying cause of the error can be retrieved via the 1544 * {@link Throwable#getCause()} method. 1545 * 1546 * @revised 1.4 1547 */ 1548 public static ClassLoader getSystemClassLoader() { 1549 initSystemClassLoader(); 1550 if (scl == null) { 1551 return null; 1552 } 1553 SecurityManager sm = System.getSecurityManager(); 1554 if (sm != null) { 1555 ClassLoader ccl = getCallerClassLoader(); 1556 if (needsClassLoaderPermissionCheck(ccl, scl)) { 1557 sm.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION); 1558 } 1559 } 1560 return scl; 1561 } 1562 1563 private static synchronized void initSystemClassLoader() { 1564 if (!sclSet) { 1565 if (scl != null) 1566 throw new IllegalStateException("recursive invocation"); 1567 sun.misc.Launcher l = sun.misc.Launcher.getLauncher(); 1568 if (l != null) { 1569 Throwable oops = null; 1570 scl = l.getClassLoader(); 1571 try { 1572 scl = AccessController.doPrivileged( 1573 new SystemClassLoaderAction(scl)); 1574 } catch (PrivilegedActionException pae) { 1575 oops = pae.getCause(); 1576 if (oops instanceof InvocationTargetException) { 1577 oops = oops.getCause(); 1578 } 1579 } 1580 if (oops != null) { 1581 if (oops instanceof Error) { 1582 throw (Error) oops; 1583 } else { 1584 // wrap the exception 1585 throw new Error(oops); 1586 } 1587 } 1588 } 1589 sclSet = true; 1590 } 1591 } 1592 1593 // Returns true if the specified class loader can be found in this class 1594 // loader's delegation chain. 1595 boolean isAncestor(ClassLoader cl) { 1596 ClassLoader acl = this; 1597 do { 1598 acl = acl.parent; 1599 if (cl == acl) { 1600 return true; 1601 } 1602 } while (acl != null); 1603 return false; 1604 } 1605 1606 // Tests if class loader access requires "getClassLoader" permission 1607 // check. A class loader 'from' can access class loader 'to' if 1608 // class loader 'from' is same as class loader 'to' or an ancestor 1609 // of 'to'. The class loader in a system domain can access 1610 // any class loader. 1611 static boolean needsClassLoaderPermissionCheck(ClassLoader from, 1612 ClassLoader to) 1613 { 1614 if (from == to) 1615 return false; 1616 1617 if (from == null) 1618 return false; 1619 1620 return !to.isAncestor(from); 1621 } 1622 1623 // Returns the invoker's class loader, or null if none. 1624 // NOTE: This must always be invoked when there is exactly one intervening 1625 // frame from the core libraries on the stack between this method's 1626 // invocation and the desired invoker. 1627 static ClassLoader getCallerClassLoader() { 1628 // NOTE use of more generic Reflection.getCallerClass() 1629 Class<?> caller = Reflection.getCallerClass(3); 1630 // This can be null if the VM is requesting it 1631 if (caller == null) { 1632 return null; 1633 } 1634 // Circumvent security check since this is package-private 1635 return caller.getClassLoader0(); 1636 } 1637 1638 // The class loader for the system 1639 // @GuardedBy("ClassLoader.class") 1640 private static ClassLoader scl; 1641 1642 // Set to true once the system class loader has been set 1643 // @GuardedBy("ClassLoader.class") 1644 private static boolean sclSet; 1645 1646 1647 // -- Package -- 1648 1649 /** 1650 * Defines a package by name in this <tt>ClassLoader</tt>. This allows 1651 * class loaders to define the packages for their classes. Packages must 1652 * be created before the class is defined, and package names must be 1653 * unique within a class loader and cannot be redefined or changed once 1654 * created. </p> 1655 * 1656 * @param name 1657 * The package name 1658 * 1659 * @param specTitle 1660 * The specification title 1661 * 1662 * @param specVersion 1663 * The specification version 1664 * 1665 * @param specVendor 1666 * The specification vendor 1667 * 1668 * @param implTitle 1669 * The implementation title 1670 * 1671 * @param implVersion 1672 * The implementation version 1673 * 1674 * @param implVendor 1675 * The implementation vendor 1676 * 1677 * @param sealBase 1678 * If not <tt>null</tt>, then this package is sealed with 1679 * respect to the given code source {@link java.net.URL 1680 * <tt>URL</tt>} object. Otherwise, the package is not sealed. 1681 * 1682 * @return The newly defined <tt>Package</tt> object 1683 * 1684 * @throws IllegalArgumentException 1685 * If package name duplicates an existing package either in this 1686 * class loader or one of its ancestors 1687 * 1688 * @since 1.2 1689 */ 1690 protected Package definePackage(String name, String specTitle, 1691 String specVersion, String specVendor, 1692 String implTitle, String implVersion, 1693 String implVendor, URL sealBase) 1694 throws IllegalArgumentException 1695 { 1696 synchronized (packages) { 1697 Package pkg = getPackage(name); 1698 if (pkg != null) { 1699 throw new IllegalArgumentException(name); 1700 } 1701 pkg = new Package(name, specTitle, specVersion, specVendor, 1702 implTitle, implVersion, implVendor, 1703 sealBase, this); 1704 packages.put(name, pkg); 1705 return pkg; 1706 } 1707 } 1708 1709 /** 1710 * Returns a <tt>Package</tt> that has been defined by this class loader 1711 * or any of its ancestors. </p> 1712 * 1713 * @param name 1714 * The package name 1715 * 1716 * @return The <tt>Package</tt> corresponding to the given name, or 1717 * <tt>null</tt> if not found 1718 * 1719 * @since 1.2 1720 */ 1721 protected Package getPackage(String name) { 1722 Package pkg; 1723 synchronized (packages) { 1724 pkg = packages.get(name); 1725 } 1726 if (pkg == null) { 1727 if (parent != null) { 1728 pkg = parent.getPackage(name); 1729 } else { 1730 pkg = Package.getSystemPackage(name); 1731 } 1732 if (pkg != null) { 1733 synchronized (packages) { 1734 Package pkg2 = packages.get(name); 1735 if (pkg2 == null) { 1736 packages.put(name, pkg); 1737 } else { 1738 pkg = pkg2; 1739 } 1740 } 1741 } 1742 } 1743 return pkg; 1744 } 1745 1746 /** 1747 * Returns all of the <tt>Packages</tt> defined by this class loader and 1748 * its ancestors. </p> 1749 * 1750 * @return The array of <tt>Package</tt> objects defined by this 1751 * <tt>ClassLoader</tt> 1752 * 1753 * @since 1.2 1754 */ 1755 protected Package[] getPackages() { 1756 Map<String, Package> map; 1757 synchronized (packages) { 1758 map = new HashMap<>(packages); 1759 } 1760 Package[] pkgs; 1761 if (parent != null) { 1762 pkgs = parent.getPackages(); 1763 } else { 1764 pkgs = Package.getSystemPackages(); 1765 } 1766 if (pkgs != null) { 1767 for (int i = 0; i < pkgs.length; i++) { 1768 String pkgName = pkgs[i].getName(); 1769 if (map.get(pkgName) == null) { 1770 map.put(pkgName, pkgs[i]); 1771 } 1772 } 1773 } 1774 return map.values().toArray(new Package[map.size()]); 1775 } 1776 1777 1778 // -- Native library access -- 1779 1780 /** 1781 * Returns the absolute path name of a native library. The VM invokes this 1782 * method to locate the native libraries that belong to classes loaded with 1783 * this class loader. If this method returns <tt>null</tt>, the VM 1784 * searches the library along the path specified as the 1785 * "<tt>java.library.path</tt>" property. </p> 1786 * 1787 * @param libname 1788 * The library name 1789 * 1790 * @return The absolute path of the native library 1791 * 1792 * @see System#loadLibrary(String) 1793 * @see System#mapLibraryName(String) 1794 * 1795 * @since 1.2 1796 */ 1797 protected String findLibrary(String libname) { 1798 return null; 1799 } 1800 1801 /** 1802 * The inner class NativeLibrary denotes a loaded native library instance. 1803 * Every classloader contains a vector of loaded native libraries in the 1804 * private field <tt>nativeLibraries</tt>. The native libraries loaded 1805 * into the system are entered into the <tt>systemNativeLibraries</tt> 1806 * vector. 1807 * 1808 * <p> Every native library requires a particular version of JNI. This is 1809 * denoted by the private <tt>jniVersion</tt> field. This field is set by 1810 * the VM when it loads the library, and used by the VM to pass the correct 1811 * version of JNI to the native methods. </p> 1812 * 1813 * @see ClassLoader 1814 * @since 1.2 1815 */ 1816 static class NativeLibrary { 1817 // opaque handle to native library, used in native code. 1818 long handle; 1819 // the version of JNI environment the native library requires. 1820 private int jniVersion; 1821 // the class from which the library is loaded, also indicates 1822 // the loader this native library belongs. 1823 private Class<?> fromClass; 1824 // the canonicalized name of the native library. 1825 String name; 1826 1827 native void load(String name); 1828 native long find(String name); 1829 native void unload(); 1830 1831 public NativeLibrary(Class<?> fromClass, String name) { 1832 this.name = name; 1833 this.fromClass = fromClass; 1834 } 1835 1836 protected void finalize() { 1837 synchronized (loadedLibraryNames) { 1838 if (fromClass.getClassLoader() != null && handle != 0) { 1839 /* remove the native library name */ 1840 int size = loadedLibraryNames.size(); 1841 for (int i = 0; i < size; i++) { 1842 if (name.equals(loadedLibraryNames.elementAt(i))) { 1843 loadedLibraryNames.removeElementAt(i); 1844 break; 1845 } 1846 } 1847 /* unload the library. */ 1848 ClassLoader.nativeLibraryContext.push(this); 1849 try { 1850 unload(); 1851 } finally { 1852 ClassLoader.nativeLibraryContext.pop(); 1853 } 1854 } 1855 } 1856 } 1857 // Invoked in the VM to determine the context class in 1858 // JNI_Load/JNI_Unload 1859 static Class<?> getFromClass() { 1860 return ClassLoader.nativeLibraryContext.peek().fromClass; 1861 } 1862 } 1863 1864 // All native library names we've loaded. 1865 private static Vector<String> loadedLibraryNames = new Vector<>(); 1866 1867 // Native libraries belonging to system classes. 1868 private static Vector<NativeLibrary> systemNativeLibraries 1869 = new Vector<>(); 1870 1871 // Native libraries associated with the class loader. 1872 private Vector<NativeLibrary> nativeLibraries = new Vector<>(); 1873 1874 // native libraries being loaded/unloaded. 1875 private static Stack<NativeLibrary> nativeLibraryContext = new Stack<>(); 1876 1877 // The paths searched for libraries 1878 private static String usr_paths[]; 1879 private static String sys_paths[]; 1880 1881 private static String[] initializePath(String propname) { 1882 String ldpath = System.getProperty(propname, ""); 1883 String ps = File.pathSeparator; 1884 int ldlen = ldpath.length(); 1885 int i, j, n; 1886 // Count the separators in the path 1887 i = ldpath.indexOf(ps); 1888 n = 0; 1889 while (i >= 0) { 1890 n++; 1891 i = ldpath.indexOf(ps, i + 1); 1892 } 1893 1894 // allocate the array of paths - n :'s = n + 1 path elements 1895 String[] paths = new String[n + 1]; 1896 1897 // Fill the array with paths from the ldpath 1898 n = i = 0; 1899 j = ldpath.indexOf(ps); 1900 while (j >= 0) { 1901 if (j - i > 0) { 1902 paths[n++] = ldpath.substring(i, j); 1903 } else if (j - i == 0) { 1904 paths[n++] = "."; 1905 } 1906 i = j + 1; 1907 j = ldpath.indexOf(ps, i); 1908 } 1909 paths[n] = ldpath.substring(i, ldlen); 1910 return paths; 1911 } 1912 1913 // Invoked in the java.lang.Runtime class to implement load and loadLibrary. 1914 static void loadLibrary(Class<?> fromClass, String name, 1915 boolean isAbsolute) { 1916 ClassLoader loader = 1917 (fromClass == null) ? null : fromClass.getClassLoader(); 1918 if (sys_paths == null) { 1919 usr_paths = initializePath("java.library.path"); 1920 sys_paths = initializePath("sun.boot.library.path"); 1921 } 1922 if (isAbsolute) { 1923 if (loadLibrary0(fromClass, new File(name))) { 1924 return; 1925 } 1926 throw new UnsatisfiedLinkError("Can't load library: " + name); 1927 } 1928 if (loader != null) { 1929 String libfilename = loader.findLibrary(name); 1930 if (libfilename != null) { 1931 File libfile = new File(libfilename); 1932 if (!libfile.isAbsolute()) { 1933 throw new UnsatisfiedLinkError( 1934 "ClassLoader.findLibrary failed to return an absolute path: " + libfilename); 1935 } 1936 if (loadLibrary0(fromClass, libfile)) { 1937 return; 1938 } 1939 throw new UnsatisfiedLinkError("Can't load " + libfilename); 1940 } 1941 } 1942 for (int i = 0 ; i < sys_paths.length ; i++) { 1943 File libfile = new File(sys_paths[i], System.mapLibraryName(name)); 1944 if (loadLibrary0(fromClass, libfile)) { 1945 return; 1946 } 1947 libfile = ClassLoaderHelper.mapAlternativeName(libfile); 1948 if (libfile != null && loadLibrary0(fromClass, libfile)) { 1949 return; 1950 } 1951 } 1952 if (loader != null) { 1953 for (int i = 0 ; i < usr_paths.length ; i++) { 1954 File libfile = new File(usr_paths[i], 1955 System.mapLibraryName(name)); 1956 if (loadLibrary0(fromClass, libfile)) { 1957 return; 1958 } 1959 libfile = ClassLoaderHelper.mapAlternativeName(libfile); 1960 if (libfile != null && loadLibrary0(fromClass, libfile)) { 1961 return; 1962 } 1963 } 1964 } 1965 // Oops, it failed 1966 throw new UnsatisfiedLinkError("no " + name + " in java.library.path"); 1967 } 1968 1969 private static boolean loadLibrary0(Class<?> fromClass, final File file) { 1970 boolean exists = AccessController.doPrivileged( 1971 new PrivilegedAction<Object>() { 1972 public Object run() { 1973 return file.exists() ? Boolean.TRUE : null; 1974 }}) 1975 != null; 1976 if (!exists) { 1977 return false; 1978 } 1979 String name; 1980 try { 1981 name = file.getCanonicalPath(); 1982 } catch (IOException e) { 1983 return false; 1984 } 1985 ClassLoader loader = 1986 (fromClass == null) ? null : fromClass.getClassLoader(); 1987 Vector<NativeLibrary> libs = 1988 loader != null ? loader.nativeLibraries : systemNativeLibraries; 1989 synchronized (libs) { 1990 int size = libs.size(); 1991 for (int i = 0; i < size; i++) { 1992 NativeLibrary lib = libs.elementAt(i); 1993 if (name.equals(lib.name)) { 1994 return true; 1995 } 1996 } 1997 1998 synchronized (loadedLibraryNames) { 1999 if (loadedLibraryNames.contains(name)) { 2000 throw new UnsatisfiedLinkError 2001 ("Native Library " + 2002 name + 2003 " already loaded in another classloader"); 2004 } 2005 /* If the library is being loaded (must be by the same thread, 2006 * because Runtime.load and Runtime.loadLibrary are 2007 * synchronous). The reason is can occur is that the JNI_OnLoad 2008 * function can cause another loadLibrary invocation. 2009 * 2010 * Thus we can use a static stack to hold the list of libraries 2011 * we are loading. 2012 * 2013 * If there is a pending load operation for the library, we 2014 * immediately return success; otherwise, we raise 2015 * UnsatisfiedLinkError. 2016 */ 2017 int n = nativeLibraryContext.size(); 2018 for (int i = 0; i < n; i++) { 2019 NativeLibrary lib = nativeLibraryContext.elementAt(i); 2020 if (name.equals(lib.name)) { 2021 if (loader == lib.fromClass.getClassLoader()) { 2022 return true; 2023 } else { 2024 throw new UnsatisfiedLinkError 2025 ("Native Library " + 2026 name + 2027 " is being loaded in another classloader"); 2028 } 2029 } 2030 } 2031 NativeLibrary lib = new NativeLibrary(fromClass, name); 2032 nativeLibraryContext.push(lib); 2033 try { 2034 lib.load(name); 2035 } finally { 2036 nativeLibraryContext.pop(); 2037 } 2038 if (lib.handle != 0) { 2039 loadedLibraryNames.addElement(name); 2040 libs.addElement(lib); 2041 return true; 2042 } 2043 return false; 2044 } 2045 } 2046 } 2047 2048 // Invoked in the VM class linking code. 2049 static long findNative(ClassLoader loader, String name) { 2050 Vector<NativeLibrary> libs = 2051 loader != null ? loader.nativeLibraries : systemNativeLibraries; 2052 synchronized (libs) { 2053 int size = libs.size(); 2054 for (int i = 0; i < size; i++) { 2055 NativeLibrary lib = libs.elementAt(i); 2056 long entry = lib.find(name); 2057 if (entry != 0) 2058 return entry; 2059 } 2060 } 2061 return 0; 2062 } 2063 2064 2065 // -- Assertion management -- 2066 2067 final Object assertionLock; 2068 2069 // The default toggle for assertion checking. 2070 // @GuardedBy("assertionLock") 2071 private boolean defaultAssertionStatus = false; 2072 2073 // Maps String packageName to Boolean package default assertion status Note 2074 // that the default package is placed under a null map key. If this field 2075 // is null then we are delegating assertion status queries to the VM, i.e., 2076 // none of this ClassLoader's assertion status modification methods have 2077 // been invoked. 2078 // @GuardedBy("assertionLock") 2079 private Map<String, Boolean> packageAssertionStatus = null; 2080 2081 // Maps String fullyQualifiedClassName to Boolean assertionStatus If this 2082 // field is null then we are delegating assertion status queries to the VM, 2083 // i.e., none of this ClassLoader's assertion status modification methods 2084 // have been invoked. 2085 // @GuardedBy("assertionLock") 2086 Map<String, Boolean> classAssertionStatus = null; 2087 2088 /** 2089 * Sets the default assertion status for this class loader. This setting 2090 * determines whether classes loaded by this class loader and initialized 2091 * in the future will have assertions enabled or disabled by default. 2092 * This setting may be overridden on a per-package or per-class basis by 2093 * invoking {@link #setPackageAssertionStatus(String, boolean)} or {@link 2094 * #setClassAssertionStatus(String, boolean)}. </p> 2095 * 2096 * @param enabled 2097 * <tt>true</tt> if classes loaded by this class loader will 2098 * henceforth have assertions enabled by default, <tt>false</tt> 2099 * if they will have assertions disabled by default. 2100 * 2101 * @since 1.4 2102 */ 2103 public void setDefaultAssertionStatus(boolean enabled) { 2104 synchronized (assertionLock) { 2105 if (classAssertionStatus == null) 2106 initializeJavaAssertionMaps(); 2107 2108 defaultAssertionStatus = enabled; 2109 } 2110 } 2111 2112 /** 2113 * Sets the package default assertion status for the named package. The 2114 * package default assertion status determines the assertion status for 2115 * classes initialized in the future that belong to the named package or 2116 * any of its "subpackages". 2117 * 2118 * <p> A subpackage of a package named p is any package whose name begins 2119 * with "<tt>p.</tt>". For example, <tt>javax.swing.text</tt> is a 2120 * subpackage of <tt>javax.swing</tt>, and both <tt>java.util</tt> and 2121 * <tt>java.lang.reflect</tt> are subpackages of <tt>java</tt>. 2122 * 2123 * <p> In the event that multiple package defaults apply to a given class, 2124 * the package default pertaining to the most specific package takes 2125 * precedence over the others. For example, if <tt>javax.lang</tt> and 2126 * <tt>javax.lang.reflect</tt> both have package defaults associated with 2127 * them, the latter package default applies to classes in 2128 * <tt>javax.lang.reflect</tt>. 2129 * 2130 * <p> Package defaults take precedence over the class loader's default 2131 * assertion status, and may be overridden on a per-class basis by invoking 2132 * {@link #setClassAssertionStatus(String, boolean)}. </p> 2133 * 2134 * @param packageName 2135 * The name of the package whose package default assertion status 2136 * is to be set. A <tt>null</tt> value indicates the unnamed 2137 * package that is "current" 2138 * (see section 7.4.2 of 2139 * <cite>The Java™ Language Specification</cite>.) 2140 * 2141 * @param enabled 2142 * <tt>true</tt> if classes loaded by this classloader and 2143 * belonging to the named package or any of its subpackages will 2144 * have assertions enabled by default, <tt>false</tt> if they will 2145 * have assertions disabled by default. 2146 * 2147 * @since 1.4 2148 */ 2149 public void setPackageAssertionStatus(String packageName, 2150 boolean enabled) { 2151 synchronized (assertionLock) { 2152 if (packageAssertionStatus == null) 2153 initializeJavaAssertionMaps(); 2154 2155 packageAssertionStatus.put(packageName, enabled); 2156 } 2157 } 2158 2159 /** 2160 * Sets the desired assertion status for the named top-level class in this 2161 * class loader and any nested classes contained therein. This setting 2162 * takes precedence over the class loader's default assertion status, and 2163 * over any applicable per-package default. This method has no effect if 2164 * the named class has already been initialized. (Once a class is 2165 * initialized, its assertion status cannot change.) 2166 * 2167 * <p> If the named class is not a top-level class, this invocation will 2168 * have no effect on the actual assertion status of any class. </p> 2169 * 2170 * @param className 2171 * The fully qualified class name of the top-level class whose 2172 * assertion status is to be set. 2173 * 2174 * @param enabled 2175 * <tt>true</tt> if the named class is to have assertions 2176 * enabled when (and if) it is initialized, <tt>false</tt> if the 2177 * class is to have assertions disabled. 2178 * 2179 * @since 1.4 2180 */ 2181 public void setClassAssertionStatus(String className, boolean enabled) { 2182 synchronized (assertionLock) { 2183 if (classAssertionStatus == null) 2184 initializeJavaAssertionMaps(); 2185 2186 classAssertionStatus.put(className, enabled); 2187 } 2188 } 2189 2190 /** 2191 * Sets the default assertion status for this class loader to 2192 * <tt>false</tt> and discards any package defaults or class assertion 2193 * status settings associated with the class loader. This method is 2194 * provided so that class loaders can be made to ignore any command line or 2195 * persistent assertion status settings and "start with a clean slate." 2196 * </p> 2197 * 2198 * @since 1.4 2199 */ 2200 public void clearAssertionStatus() { 2201 /* 2202 * Whether or not "Java assertion maps" are initialized, set 2203 * them to empty maps, effectively ignoring any present settings. 2204 */ 2205 synchronized (assertionLock) { 2206 classAssertionStatus = new HashMap<>(); 2207 packageAssertionStatus = new HashMap<>(); 2208 defaultAssertionStatus = false; 2209 } 2210 } 2211 2212 /** 2213 * Returns the assertion status that would be assigned to the specified 2214 * class if it were to be initialized at the time this method is invoked. 2215 * If the named class has had its assertion status set, the most recent 2216 * setting will be returned; otherwise, if any package default assertion 2217 * status pertains to this class, the most recent setting for the most 2218 * specific pertinent package default assertion status is returned; 2219 * otherwise, this class loader's default assertion status is returned. 2220 * </p> 2221 * 2222 * @param className 2223 * The fully qualified class name of the class whose desired 2224 * assertion status is being queried. 2225 * 2226 * @return The desired assertion status of the specified class. 2227 * 2228 * @see #setClassAssertionStatus(String, boolean) 2229 * @see #setPackageAssertionStatus(String, boolean) 2230 * @see #setDefaultAssertionStatus(boolean) 2231 * 2232 * @since 1.4 2233 */ 2234 boolean desiredAssertionStatus(String className) { 2235 synchronized (assertionLock) { 2236 // assert classAssertionStatus != null; 2237 // assert packageAssertionStatus != null; 2238 2239 // Check for a class entry 2240 Boolean result = classAssertionStatus.get(className); 2241 if (result != null) 2242 return result.booleanValue(); 2243 2244 // Check for most specific package entry 2245 int dotIndex = className.lastIndexOf("."); 2246 if (dotIndex < 0) { // default package 2247 result = packageAssertionStatus.get(null); 2248 if (result != null) 2249 return result.booleanValue(); 2250 } 2251 while(dotIndex > 0) { 2252 className = className.substring(0, dotIndex); 2253 result = packageAssertionStatus.get(className); 2254 if (result != null) 2255 return result.booleanValue(); 2256 dotIndex = className.lastIndexOf(".", dotIndex-1); 2257 } 2258 2259 // Return the classloader default 2260 return defaultAssertionStatus; 2261 } 2262 } 2263 2264 // Set up the assertions with information provided by the VM. 2265 // Note: Should only be called inside a synchronized block 2266 private void initializeJavaAssertionMaps() { 2267 // assert Thread.holdsLock(assertionLock); 2268 2269 classAssertionStatus = new HashMap<>(); 2270 packageAssertionStatus = new HashMap<>(); 2271 AssertionStatusDirectives directives = retrieveDirectives(); 2272 2273 for(int i = 0; i < directives.classes.length; i++) 2274 classAssertionStatus.put(directives.classes[i], 2275 directives.classEnabled[i]); 2276 2277 for(int i = 0; i < directives.packages.length; i++) 2278 packageAssertionStatus.put(directives.packages[i], 2279 directives.packageEnabled[i]); 2280 2281 defaultAssertionStatus = directives.deflt; 2282 } 2283 2284 // Retrieves the assertion directives from the VM. 2285 private static native AssertionStatusDirectives retrieveDirectives(); 2286 } 2287 2288 2289 class SystemClassLoaderAction 2290 implements PrivilegedExceptionAction<ClassLoader> { 2291 private ClassLoader parent; 2292 2293 SystemClassLoaderAction(ClassLoader parent) { 2294 this.parent = parent; 2295 } 2296 2297 public ClassLoader run() throws Exception { 2298 String cls = System.getProperty("java.system.class.loader"); 2299 if (cls == null) { 2300 return parent; 2301 } 2302 2303 Constructor<?> ctor = Class.forName(cls, true, parent) 2304 .getDeclaredConstructor(new Class<?>[] { ClassLoader.class }); 2305 ClassLoader sys = (ClassLoader) ctor.newInstance( 2306 new Object[] { parent }); 2307 Thread.currentThread().setContextClassLoader(sys); 2308 return sys; 2309 } 2310 }