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