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