1 /* 2 * Copyright (c) 2013, 2015, Oracle and/or its affiliates. All rights reserved. 3 * Copyright (c) 2019, Azul Systems, Inc. All rights reserved. 4 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 5 * 6 * This code is free software; you can redistribute it and/or modify it 7 * under the terms of the GNU General Public License version 2 only, as 8 * published by the Free Software Foundation. Oracle designates this 9 * particular file as subject to the "Classpath" exception as provided 10 * by Oracle in the LICENSE file that accompanied this code. 11 * 12 * This code is distributed in the hope that it will be useful, but WITHOUT 13 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 14 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 15 * version 2 for more details (a copy is included in the LICENSE file that 16 * accompanied this code). 17 * 18 * You should have received a copy of the GNU General Public License version 19 * 2 along with this work; if not, write to the Free Software Foundation, 20 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 21 * 22 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 23 * or visit www.oracle.com if you need additional information or have any 24 * questions. 25 */ 26 package java.lang; 27 28 import java.io.InputStream; 29 import java.io.IOException; 30 import java.io.File; 31 import java.lang.reflect.Constructor; 32 import java.lang.reflect.InvocationTargetException; 33 import java.net.MalformedURLException; 34 import java.net.URL; 35 import java.security.AccessController; 36 import java.security.AccessControlContext; 37 import java.security.CodeSource; 38 import java.security.Policy; 39 import java.security.PrivilegedAction; 40 import java.security.PrivilegedActionException; 41 import java.security.PrivilegedExceptionAction; 42 import java.security.ProtectionDomain; 43 import java.security.cert.Certificate; 44 import java.util.Collections; 45 import java.util.Enumeration; 46 import java.util.HashMap; 47 import java.util.HashSet; 48 import java.util.Set; 49 import java.util.Stack; 50 import java.util.Map; 51 import java.util.Vector; 52 import java.util.Hashtable; 53 import java.util.WeakHashMap; 54 import java.util.concurrent.ConcurrentHashMap; 55 import sun.misc.CompoundEnumeration; 56 import sun.misc.Resource; 57 import sun.misc.URLClassPath; 58 import sun.misc.VM; 59 import sun.reflect.CallerSensitive; 60 import sun.reflect.Reflection; 61 import sun.reflect.misc.ReflectUtil; 62 import sun.security.util.SecurityConstants; 63 64 /** 65 * A class loader is an object that is responsible for loading classes. The 66 * class <tt>ClassLoader</tt> is an abstract class. Given the <a 67 * href="#name">binary name</a> of a class, a class loader should attempt to 68 * locate or generate data that constitutes a definition for the class. A 69 * typical strategy is to transform the name into a file name and then read a 70 * "class file" of that name from a file system. 71 * 72 * <p> Every {@link Class <tt>Class</tt>} object contains a {@link 73 * Class#getClassLoader() reference} to the <tt>ClassLoader</tt> that defined 74 * it. 75 * 76 * <p> <tt>Class</tt> objects for array classes are not created by class 77 * loaders, but are created automatically as required by the Java runtime. 78 * The class loader for an array class, as returned by {@link 79 * Class#getClassLoader()} is the same as the class loader for its element 80 * type; if the element type is a primitive type, then the array class has no 81 * class loader. 82 * 83 * <p> Applications implement subclasses of <tt>ClassLoader</tt> in order to 84 * extend the manner in which the Java virtual machine dynamically loads 85 * classes. 86 * 87 * <p> Class loaders may typically be used by security managers to indicate 88 * security domains. 89 * 90 * <p> The <tt>ClassLoader</tt> class uses a delegation model to search for 91 * classes and resources. Each instance of <tt>ClassLoader</tt> has an 92 * associated parent class loader. When requested to find a class or 93 * resource, a <tt>ClassLoader</tt> instance will delegate the search for the 94 * class or resource to its parent class loader before attempting to find the 95 * class or resource itself. The virtual machine's built-in class loader, 96 * called the "bootstrap class loader", does not itself have a parent but may 97 * serve as the parent of a <tt>ClassLoader</tt> instance. 98 * 99 * <p> Class loaders that support concurrent loading of classes are known as 100 * <em>parallel capable</em> class loaders and are required to register 101 * themselves at their class initialization time by invoking the 102 * {@link 103 * #registerAsParallelCapable <tt>ClassLoader.registerAsParallelCapable</tt>} 104 * method. Note that the <tt>ClassLoader</tt> class is registered as parallel 105 * capable by default. However, its subclasses still need to register themselves 106 * if they are parallel capable. <br> 107 * In environments in which the delegation model is not strictly 108 * hierarchical, class loaders need to be parallel capable, otherwise class 109 * loading can lead to deadlocks because the loader lock is held for the 110 * duration of the class loading process (see {@link #loadClass 111 * <tt>loadClass</tt>} methods). 112 * 113 * <p> Normally, the Java virtual machine loads classes from the local file 114 * system in a platform-dependent manner. For example, on UNIX systems, the 115 * virtual machine loads classes from the directory defined by the 116 * <tt>CLASSPATH</tt> environment variable. 117 * 118 * <p> However, some classes may not originate from a file; they may originate 119 * from other sources, such as the network, or they could be constructed by an 120 * application. The method {@link #defineClass(String, byte[], int, int) 121 * <tt>defineClass</tt>} converts an array of bytes into an instance of class 122 * <tt>Class</tt>. Instances of this newly defined class can be created using 123 * {@link Class#newInstance <tt>Class.newInstance</tt>}. 124 * 125 * <p> The methods and constructors of objects created by a class loader may 126 * reference other classes. To determine the class(es) referred to, the Java 127 * virtual machine invokes the {@link #loadClass <tt>loadClass</tt>} method of 128 * the class loader that originally created the class. 129 * 130 * <p> For example, an application could create a network class loader to 131 * download class files from a server. Sample code might look like: 132 * 133 * <blockquote><pre> 134 * ClassLoader loader = new NetworkClassLoader(host, port); 135 * Object main = loader.loadClass("Main", true).newInstance(); 136 * . . . 137 * </pre></blockquote> 138 * 139 * <p> The network class loader subclass must define the methods {@link 140 * #findClass <tt>findClass</tt>} and <tt>loadClassData</tt> to load a class 141 * from the network. Once it has downloaded the bytes that make up the class, 142 * it should use the method {@link #defineClass <tt>defineClass</tt>} to 143 * create a class instance. A sample implementation is: 144 * 145 * <blockquote><pre> 146 * class NetworkClassLoader extends ClassLoader { 147 * String host; 148 * int port; 149 * 150 * public Class findClass(String name) { 151 * byte[] b = loadClassData(name); 152 * return defineClass(name, b, 0, b.length); 153 * } 154 * 155 * private byte[] loadClassData(String name) { 156 * // load the class data from the connection 157 * . . . 158 * } 159 * } 160 * </pre></blockquote> 161 * 162 * <h3> <a name="name">Binary names</a> </h3> 163 * 164 * <p> Any class name provided as a {@link String} parameter to methods in 165 * <tt>ClassLoader</tt> must be a binary name as defined by 166 * <cite>The Java™ Language Specification</cite>. 167 * 168 * <p> Examples of valid class names include: 169 * <blockquote><pre> 170 * "java.lang.String" 171 * "javax.swing.JSpinner$DefaultEditor" 172 * "java.security.KeyStore$Builder$FileBuilder$1" 173 * "java.net.URLClassLoader$3$1" 174 * </pre></blockquote> 175 * 176 * @see #resolveClass(Class) 177 * @since 1.0 178 */ 179 public abstract class ClassLoader { 180 181 private static native void registerNatives(); 182 static { 183 registerNatives(); 184 } 185 186 // The parent class loader for delegation 187 // Note: VM hardcoded the offset of this field, thus all new fields 188 // must be added *after* it. 189 private final ClassLoader parent; 190 191 /** 192 * Encapsulates the set of parallel capable loader types. 193 */ 194 private static class ParallelLoaders { 195 private ParallelLoaders() {} 196 197 // the set of parallel capable loader types 198 private static final Set<Class<? extends ClassLoader>> loaderTypes = 199 Collections.newSetFromMap( 200 new WeakHashMap<Class<? extends ClassLoader>, Boolean>()); 201 static { 202 synchronized (loaderTypes) { loaderTypes.add(ClassLoader.class); } 203 } 204 205 /** 206 * Registers the given class loader type as parallel capabale. 207 * Returns {@code true} is successfully registered; {@code false} if 208 * loader's super class is not registered. 209 */ 210 static boolean register(Class<? extends ClassLoader> c) { 211 synchronized (loaderTypes) { 212 if (loaderTypes.contains(c.getSuperclass())) { 213 // register the class loader as parallel capable 214 // if and only if all of its super classes are. 215 // Note: given current classloading sequence, if 216 // the immediate super class is parallel capable, 217 // all the super classes higher up must be too. 218 loaderTypes.add(c); 219 return true; 220 } else { 221 return false; 222 } 223 } 224 } 225 226 /** 227 * Returns {@code true} if the given class loader type is 228 * registered as parallel capable. 229 */ 230 static boolean isRegistered(Class<? extends ClassLoader> c) { 231 synchronized (loaderTypes) { 232 return loaderTypes.contains(c); 233 } 234 } 235 } 236 237 // Maps class name to the corresponding lock object when the current 238 // class loader is parallel capable. 239 // Note: VM also uses this field to decide if the current class loader 240 // is parallel capable and the appropriate lock object for class loading. 241 private final ConcurrentHashMap<String, Object> parallelLockMap; 242 243 // Hashtable that maps packages to certs 244 private final Map <String, Certificate[]> package2certs; 245 246 // Shared among all packages with unsigned classes 247 private static final Certificate[] nocerts = new Certificate[0]; 248 249 // The classes loaded by this class loader. The only purpose of this table 250 // is to keep the classes from being GC'ed until the loader is GC'ed. 251 private final Vector<Class<?>> classes = new Vector<>(); 252 253 // The "default" domain. Set as the default ProtectionDomain on newly 254 // created classes. 255 private final ProtectionDomain defaultDomain = 256 new ProtectionDomain(new CodeSource(null, (Certificate[]) null), 257 null, this, null); 258 259 // Invoked by the VM to record every loaded class with this loader. 260 void addClass(Class<?> c) { 261 classes.addElement(c); 262 } 263 264 // The packages defined in this class loader. Each package name is mapped 265 // to its corresponding Package object. 266 // @GuardedBy("itself") 267 private final HashMap<String, Package> packages = new HashMap<>(); 268 269 private static Void checkCreateClassLoader() { 270 SecurityManager security = System.getSecurityManager(); 271 if (security != null) { 272 security.checkCreateClassLoader(); 273 } 274 return null; 275 } 276 277 private ClassLoader(Void unused, ClassLoader parent) { 278 this.parent = parent; 279 if (ParallelLoaders.isRegistered(this.getClass())) { 280 parallelLockMap = new ConcurrentHashMap<>(); 281 package2certs = new ConcurrentHashMap<>(); 282 assertionLock = new Object(); 283 } else { 284 // no finer-grained lock; lock on the classloader instance 285 parallelLockMap = null; 286 package2certs = new Hashtable<>(); 287 assertionLock = this; 288 } 289 } 290 291 /** 292 * Creates a new class loader using the specified parent class loader for 293 * delegation. 294 * 295 * <p> If there is a security manager, its {@link 296 * SecurityManager#checkCreateClassLoader() 297 * <tt>checkCreateClassLoader</tt>} method is invoked. This may result in 298 * a security exception. </p> 299 * 300 * @param parent 301 * The parent class loader 302 * 303 * @throws SecurityException 304 * If a security manager exists and its 305 * <tt>checkCreateClassLoader</tt> method doesn't allow creation 306 * of a new class loader. 307 * 308 * @since 1.2 309 */ 310 protected ClassLoader(ClassLoader parent) { 311 this(checkCreateClassLoader(), parent); 312 } 313 314 /** 315 * Creates a new class loader using the <tt>ClassLoader</tt> returned by 316 * the method {@link #getSystemClassLoader() 317 * <tt>getSystemClassLoader()</tt>} as the parent class loader. 318 * 319 * <p> If there is a security manager, its {@link 320 * SecurityManager#checkCreateClassLoader() 321 * <tt>checkCreateClassLoader</tt>} method is invoked. This may result in 322 * a security exception. </p> 323 * 324 * @throws SecurityException 325 * If a security manager exists and its 326 * <tt>checkCreateClassLoader</tt> method doesn't allow creation 327 * of a new class loader. 328 */ 329 protected ClassLoader() { 330 this(checkCreateClassLoader(), getSystemClassLoader()); 331 } 332 333 // -- Class -- 334 335 /** 336 * Loads the class with the specified <a href="#name">binary name</a>. 337 * This method searches for classes in the same manner as the {@link 338 * #loadClass(String, boolean)} method. It is invoked by the Java virtual 339 * machine to resolve class references. Invoking this method is equivalent 340 * to invoking {@link #loadClass(String, boolean) <tt>loadClass(name, 341 * false)</tt>}. 342 * 343 * @param name 344 * The <a href="#name">binary name</a> of the class 345 * 346 * @return The resulting <tt>Class</tt> object 347 * 348 * @throws ClassNotFoundException 349 * If the class was not found 350 */ 351 public Class<?> loadClass(String name) throws ClassNotFoundException { 352 return loadClass(name, false); 353 } 354 355 /** 356 * Loads the class with the specified <a href="#name">binary name</a>. The 357 * default implementation of this method searches for classes in the 358 * following order: 359 * 360 * <ol> 361 * 362 * <li><p> Invoke {@link #findLoadedClass(String)} to check if the class 363 * has already been loaded. </p></li> 364 * 365 * <li><p> Invoke the {@link #loadClass(String) <tt>loadClass</tt>} method 366 * on the parent class loader. If the parent is <tt>null</tt> the class 367 * loader built-in to the virtual machine is used, instead. </p></li> 368 * 369 * <li><p> Invoke the {@link #findClass(String)} method to find the 370 * class. </p></li> 371 * 372 * </ol> 373 * 374 * <p> If the class was found using the above steps, and the 375 * <tt>resolve</tt> flag is true, this method will then invoke the {@link 376 * #resolveClass(Class)} method on the resulting <tt>Class</tt> object. 377 * 378 * <p> Subclasses of <tt>ClassLoader</tt> are encouraged to override {@link 379 * #findClass(String)}, rather than this method. </p> 380 * 381 * <p> Unless overridden, this method synchronizes on the result of 382 * {@link #getClassLoadingLock <tt>getClassLoadingLock</tt>} method 383 * during the entire class loading process. 384 * 385 * @param name 386 * The <a href="#name">binary name</a> of the class 387 * 388 * @param resolve 389 * If <tt>true</tt> then resolve the class 390 * 391 * @return The resulting <tt>Class</tt> object 392 * 393 * @throws ClassNotFoundException 394 * If the class could not be found 395 */ 396 protected Class<?> loadClass(String name, boolean resolve) 397 throws ClassNotFoundException 398 { 399 synchronized (getClassLoadingLock(name)) { 400 // First, check if the class has already been loaded 401 Class<?> c = findLoadedClass(name); 402 if (c == null) { 403 long t0 = System.nanoTime(); 404 try { 405 if (parent != null) { 406 c = parent.loadClass(name, false); 407 } else { 408 c = findBootstrapClassOrNull(name); 409 } 410 } catch (ClassNotFoundException e) { 411 // ClassNotFoundException thrown if class not found 412 // from the non-null parent class loader 413 } 414 415 if (c == null) { 416 // If still not found, then invoke findClass in order 417 // to find the class. 418 long t1 = System.nanoTime(); 419 c = findClass(name); 420 421 // this is the defining class loader; record the stats 422 sun.misc.PerfCounter.getParentDelegationTime().addTime(t1 - t0); 423 sun.misc.PerfCounter.getFindClassTime().addElapsedTimeFrom(t1); 424 sun.misc.PerfCounter.getFindClasses().increment(); 425 } 426 } 427 if (resolve) { 428 resolveClass(c); 429 } 430 return c; 431 } 432 } 433 434 /** 435 * Returns the lock object for class loading operations. 436 * For backward compatibility, the default implementation of this method 437 * behaves as follows. If this ClassLoader object is registered as 438 * parallel capable, the method returns a dedicated object associated 439 * with the specified class name. Otherwise, the method returns this 440 * ClassLoader object. 441 * 442 * @param className 443 * The name of the to-be-loaded class 444 * 445 * @return the lock for class loading operations 446 * 447 * @throws NullPointerException 448 * If registered as parallel capable and <tt>className</tt> is null 449 * 450 * @see #loadClass(String, boolean) 451 * 452 * @since 1.7 453 */ 454 protected Object getClassLoadingLock(String className) { 455 Object lock = this; 456 if (parallelLockMap != null) { 457 Object newLock = new Object(); 458 lock = parallelLockMap.putIfAbsent(className, newLock); 459 if (lock == null) { 460 lock = newLock; 461 } 462 } 463 return lock; 464 } 465 466 // This method is invoked by the virtual machine to load a class. 467 private Class<?> loadClassInternal(String name) 468 throws ClassNotFoundException 469 { 470 // For backward compatibility, explicitly lock on 'this' when 471 // the current class loader is not parallel capable. 472 if (parallelLockMap == null) { 473 synchronized (this) { 474 return loadClass(name); 475 } 476 } else { 477 return loadClass(name); 478 } 479 } 480 481 // Invoked by the VM after loading class with this loader. 482 private void checkPackageAccess(Class<?> cls, ProtectionDomain pd) { 483 final SecurityManager sm = System.getSecurityManager(); 484 if (sm != null) { 485 if (ReflectUtil.isNonPublicProxyClass(cls)) { 486 for (Class<?> intf: cls.getInterfaces()) { 487 checkPackageAccess(intf, pd); 488 } 489 return; 490 } 491 492 final String name = cls.getName(); 493 final int i = name.lastIndexOf('.'); 494 if (i != -1) { 495 AccessController.doPrivileged(new PrivilegedAction<Void>() { 496 public Void run() { 497 sm.checkPackageAccess(name.substring(0, i)); 498 return null; 499 } 500 }, new AccessControlContext(new ProtectionDomain[] {pd})); 501 } 502 } 503 } 504 505 /** 506 * Finds the class with the specified <a href="#name">binary name</a>. 507 * This method should be overridden by class loader implementations that 508 * follow the delegation model for loading classes, and will be invoked by 509 * the {@link #loadClass <tt>loadClass</tt>} method after checking the 510 * parent class loader for the requested class. The default implementation 511 * throws a <tt>ClassNotFoundException</tt>. 512 * 513 * @param name 514 * The <a href="#name">binary name</a> of the class 515 * 516 * @return The resulting <tt>Class</tt> object 517 * 518 * @throws ClassNotFoundException 519 * If the class could not be found 520 * 521 * @since 1.2 522 */ 523 protected Class<?> findClass(String name) throws ClassNotFoundException { 524 throw new ClassNotFoundException(name); 525 } 526 527 /** 528 * Converts an array of bytes into an instance of class <tt>Class</tt>. 529 * Before the <tt>Class</tt> can be used it must be resolved. This method 530 * is deprecated in favor of the version that takes a <a 531 * href="#name">binary name</a> as its first argument, and is more secure. 532 * 533 * @param b 534 * The bytes that make up the class data. The bytes in positions 535 * <tt>off</tt> through <tt>off+len-1</tt> should have the format 536 * of a valid class file as defined by 537 * <cite>The Java™ Virtual Machine Specification</cite>. 538 * 539 * @param off 540 * The start offset in <tt>b</tt> of the class data 541 * 542 * @param len 543 * The length of the class data 544 * 545 * @return The <tt>Class</tt> object that was created from the specified 546 * class data 547 * 548 * @throws ClassFormatError 549 * If the data did not contain a valid class 550 * 551 * @throws IndexOutOfBoundsException 552 * If either <tt>off</tt> or <tt>len</tt> is negative, or if 553 * <tt>off+len</tt> is greater than <tt>b.length</tt>. 554 * 555 * @throws SecurityException 556 * If an attempt is made to add this class to a package that 557 * contains classes that were signed by a different set of 558 * certificates than this class, or if an attempt is made 559 * to define a class in a package with a fully-qualified name 560 * that starts with "{@code java.}". 561 * 562 * @see #loadClass(String, boolean) 563 * @see #resolveClass(Class) 564 * 565 * @deprecated Replaced by {@link #defineClass(String, byte[], int, int) 566 * defineClass(String, byte[], int, int)} 567 */ 568 @Deprecated 569 protected final Class<?> defineClass(byte[] b, int off, int len) 570 throws ClassFormatError 571 { 572 return defineClass(null, b, off, len, null); 573 } 574 575 /** 576 * Converts an array of bytes into an instance of class <tt>Class</tt>. 577 * Before the <tt>Class</tt> can be used it must be resolved. 578 * 579 * <p> This method assigns a default {@link java.security.ProtectionDomain 580 * <tt>ProtectionDomain</tt>} to the newly defined class. The 581 * <tt>ProtectionDomain</tt> is effectively granted the same set of 582 * permissions returned when {@link 583 * java.security.Policy#getPermissions(java.security.CodeSource) 584 * <tt>Policy.getPolicy().getPermissions(new CodeSource(null, null))</tt>} 585 * is invoked. The default domain is created on the first invocation of 586 * {@link #defineClass(String, byte[], int, int) <tt>defineClass</tt>}, 587 * and re-used on subsequent invocations. 588 * 589 * <p> To assign a specific <tt>ProtectionDomain</tt> to the class, use 590 * the {@link #defineClass(String, byte[], int, int, 591 * java.security.ProtectionDomain) <tt>defineClass</tt>} method that takes a 592 * <tt>ProtectionDomain</tt> as one of its arguments. </p> 593 * 594 * @param name 595 * The expected <a href="#name">binary name</a> of the class, or 596 * <tt>null</tt> if not known 597 * 598 * @param b 599 * The bytes that make up the class data. The bytes in positions 600 * <tt>off</tt> through <tt>off+len-1</tt> should have the format 601 * of a valid class file as defined by 602 * <cite>The Java™ Virtual Machine Specification</cite>. 603 * 604 * @param off 605 * The start offset in <tt>b</tt> of the class data 606 * 607 * @param len 608 * The length of the class data 609 * 610 * @return The <tt>Class</tt> object that was created from the specified 611 * class data. 612 * 613 * @throws ClassFormatError 614 * If the data did not contain a valid class 615 * 616 * @throws IndexOutOfBoundsException 617 * If either <tt>off</tt> or <tt>len</tt> is negative, or if 618 * <tt>off+len</tt> is greater than <tt>b.length</tt>. 619 * 620 * @throws SecurityException 621 * If an attempt is made to add this class to a package that 622 * contains classes that were signed by a different set of 623 * certificates than this class (which is unsigned), or if 624 * <tt>name</tt> begins with "<tt>java.</tt>". 625 * 626 * @see #loadClass(String, boolean) 627 * @see #resolveClass(Class) 628 * @see java.security.CodeSource 629 * @see java.security.SecureClassLoader 630 * 631 * @since 1.1 632 */ 633 protected final Class<?> defineClass(String name, byte[] b, int off, int len) 634 throws ClassFormatError 635 { 636 return defineClass(name, b, off, len, null); 637 } 638 639 /* Determine protection domain, and check that: 640 - not define java.* class, 641 - signer of this class matches signers for the rest of the classes in 642 package. 643 */ 644 private ProtectionDomain preDefineClass(String name, 645 ProtectionDomain pd) 646 { 647 if (!checkName(name)) 648 throw new NoClassDefFoundError("IllegalName: " + name); 649 650 // Note: Checking logic in java.lang.invoke.MemberName.checkForTypeAlias 651 // relies on the fact that spoofing is impossible if a class has a name 652 // of the form "java.*" 653 if ((name != null) && name.startsWith("java.")) { 654 throw new SecurityException 655 ("Prohibited package name: " + 656 name.substring(0, name.lastIndexOf('.'))); 657 } 658 if (pd == null) { 659 pd = defaultDomain; 660 } 661 662 if (name != null) checkCerts(name, pd.getCodeSource()); 663 664 return pd; 665 } 666 667 private String defineClassSourceLocation(ProtectionDomain pd) 668 { 669 CodeSource cs = pd.getCodeSource(); 670 String source = null; 671 if (cs != null && cs.getLocation() != null) { 672 source = cs.getLocation().toString(); 673 } 674 return source; 675 } 676 677 private void postDefineClass(Class<?> c, ProtectionDomain pd) 678 { 679 if (pd.getCodeSource() != null) { 680 Certificate certs[] = pd.getCodeSource().getCertificates(); 681 if (certs != null) 682 setSigners(c, certs); 683 } 684 } 685 686 /** 687 * Converts an array of bytes into an instance of class <tt>Class</tt>, 688 * with an optional <tt>ProtectionDomain</tt>. If the domain is 689 * <tt>null</tt>, then a default domain will be assigned to the class as 690 * specified in the documentation for {@link #defineClass(String, byte[], 691 * int, int)}. Before the class can be used it must be resolved. 692 * 693 * <p> The first class defined in a package determines the exact set of 694 * certificates that all subsequent classes defined in that package must 695 * contain. The set of certificates for a class is obtained from the 696 * {@link java.security.CodeSource <tt>CodeSource</tt>} within the 697 * <tt>ProtectionDomain</tt> of the class. Any classes added to that 698 * package must contain the same set of certificates or a 699 * <tt>SecurityException</tt> will be thrown. Note that if 700 * <tt>name</tt> is <tt>null</tt>, this check is not performed. 701 * You should always pass in the <a href="#name">binary name</a> of the 702 * class you are defining as well as the bytes. This ensures that the 703 * class you are defining is indeed the class you think it is. 704 * 705 * <p> The specified <tt>name</tt> cannot begin with "<tt>java.</tt>", since 706 * all classes in the "<tt>java.*</tt> packages can only be defined by the 707 * bootstrap class loader. If <tt>name</tt> is not <tt>null</tt>, it 708 * must be equal to the <a href="#name">binary name</a> of the class 709 * specified by the byte array "<tt>b</tt>", otherwise a {@link 710 * NoClassDefFoundError <tt>NoClassDefFoundError</tt>} will be thrown. </p> 711 * 712 * @param name 713 * The expected <a href="#name">binary name</a> of the class, or 714 * <tt>null</tt> if not known 715 * 716 * @param b 717 * The bytes that make up the class data. The bytes in positions 718 * <tt>off</tt> through <tt>off+len-1</tt> should have the format 719 * of a valid class file as defined by 720 * <cite>The Java™ Virtual Machine Specification</cite>. 721 * 722 * @param off 723 * The start offset in <tt>b</tt> of the class data 724 * 725 * @param len 726 * The length of the class data 727 * 728 * @param protectionDomain 729 * The ProtectionDomain of the class 730 * 731 * @return The <tt>Class</tt> object created from the data, 732 * and optional <tt>ProtectionDomain</tt>. 733 * 734 * @throws ClassFormatError 735 * If the data did not contain a valid class 736 * 737 * @throws NoClassDefFoundError 738 * If <tt>name</tt> is not equal to the <a href="#name">binary 739 * name</a> of the class specified by <tt>b</tt> 740 * 741 * @throws IndexOutOfBoundsException 742 * If either <tt>off</tt> or <tt>len</tt> is negative, or if 743 * <tt>off+len</tt> is greater than <tt>b.length</tt>. 744 * 745 * @throws SecurityException 746 * If an attempt is made to add this class to a package that 747 * contains classes that were signed by a different set of 748 * certificates than this class, or if <tt>name</tt> begins with 749 * "<tt>java.</tt>". 750 */ 751 protected final Class<?> defineClass(String name, byte[] b, int off, int len, 752 ProtectionDomain protectionDomain) 753 throws ClassFormatError 754 { 755 protectionDomain = preDefineClass(name, protectionDomain); 756 String source = defineClassSourceLocation(protectionDomain); 757 Class<?> c = defineClass1(name, b, off, len, protectionDomain, source); 758 postDefineClass(c, protectionDomain); 759 return c; 760 } 761 762 /** 763 * Converts a {@link java.nio.ByteBuffer <tt>ByteBuffer</tt>} 764 * into an instance of class <tt>Class</tt>, 765 * with an optional <tt>ProtectionDomain</tt>. If the domain is 766 * <tt>null</tt>, then a default domain will be assigned to the class as 767 * specified in the documentation for {@link #defineClass(String, byte[], 768 * int, int)}. Before the class can be used it must be resolved. 769 * 770 * <p>The rules about the first class defined in a package determining the 771 * set of certificates for the package, and the restrictions on class names 772 * are identical to those specified in the documentation for {@link 773 * #defineClass(String, byte[], int, int, ProtectionDomain)}. 774 * 775 * <p> An invocation of this method of the form 776 * <i>cl</i><tt>.defineClass(</tt><i>name</i><tt>,</tt> 777 * <i>bBuffer</i><tt>,</tt> <i>pd</i><tt>)</tt> yields exactly the same 778 * result as the statements 779 * 780 *<p> <tt> 781 * ...<br> 782 * byte[] temp = new byte[bBuffer.{@link 783 * java.nio.ByteBuffer#remaining remaining}()];<br> 784 * bBuffer.{@link java.nio.ByteBuffer#get(byte[]) 785 * get}(temp);<br> 786 * return {@link #defineClass(String, byte[], int, int, ProtectionDomain) 787 * cl.defineClass}(name, temp, 0, 788 * temp.length, pd);<br> 789 * </tt></p> 790 * 791 * @param name 792 * The expected <a href="#name">binary name</a>. of the class, or 793 * <tt>null</tt> if not known 794 * 795 * @param b 796 * The bytes that make up the class data. The bytes from positions 797 * <tt>b.position()</tt> through <tt>b.position() + b.limit() -1 798 * </tt> should have the format of a valid class file as defined by 799 * <cite>The Java™ Virtual Machine Specification</cite>. 800 * 801 * @param protectionDomain 802 * The ProtectionDomain of the class, or <tt>null</tt>. 803 * 804 * @return The <tt>Class</tt> object created from the data, 805 * and optional <tt>ProtectionDomain</tt>. 806 * 807 * @throws ClassFormatError 808 * If the data did not contain a valid class. 809 * 810 * @throws NoClassDefFoundError 811 * If <tt>name</tt> is not equal to the <a href="#name">binary 812 * name</a> of the class specified by <tt>b</tt> 813 * 814 * @throws SecurityException 815 * If an attempt is made to add this class to a package that 816 * contains classes that were signed by a different set of 817 * certificates than this class, or if <tt>name</tt> begins with 818 * "<tt>java.</tt>". 819 * 820 * @see #defineClass(String, byte[], int, int, ProtectionDomain) 821 * 822 * @since 1.5 823 */ 824 protected final Class<?> defineClass(String name, java.nio.ByteBuffer b, 825 ProtectionDomain protectionDomain) 826 throws ClassFormatError 827 { 828 int len = b.remaining(); 829 830 // Use byte[] if not a direct ByteBufer: 831 if (!b.isDirect()) { 832 if (b.hasArray()) { 833 return defineClass(name, b.array(), 834 b.position() + b.arrayOffset(), len, 835 protectionDomain); 836 } else { 837 // no array, or read-only array 838 byte[] tb = new byte[len]; 839 b.get(tb); // get bytes out of byte buffer. 840 return defineClass(name, tb, 0, len, protectionDomain); 841 } 842 } 843 844 protectionDomain = preDefineClass(name, protectionDomain); 845 String source = defineClassSourceLocation(protectionDomain); 846 Class<?> c = defineClass2(name, b, b.position(), len, protectionDomain, source); 847 postDefineClass(c, protectionDomain); 848 return c; 849 } 850 851 private native Class<?> defineClass0(String name, byte[] b, int off, int len, 852 ProtectionDomain pd); 853 854 private native Class<?> defineClass1(String name, byte[] b, int off, int len, 855 ProtectionDomain pd, String source); 856 857 private native Class<?> defineClass2(String name, java.nio.ByteBuffer b, 858 int off, int len, ProtectionDomain pd, 859 String source); 860 861 // true if the name is null or has the potential to be a valid binary name 862 private boolean checkName(String name) { 863 if ((name == null) || (name.length() == 0)) 864 return true; 865 if ((name.indexOf('/') != -1) 866 || (!VM.allowArraySyntax() && (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 (int i = 0; i < certs.length; i++) { 917 match = false; 918 for (int j = 0; j < pcerts.length; j++) { 919 if (certs[i].equals(pcerts[j])) { 920 match = true; 921 break; 922 } 923 } 924 if (!match) return false; 925 } 926 927 // now do the same for pcerts 928 for (int i = 0; i < pcerts.length; i++) { 929 match = false; 930 for (int j = 0; j < certs.length; j++) { 931 if (pcerts[i].equals(certs[j])) { 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 resolveClass0(c); 959 } 960 961 private native void resolveClass0(Class<?> c); 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 native final 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<URL> () { 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 /* 1472 * Initialize default paths for native libraries search. 1473 * Must be done early as JDK may load libraries during bootstrap. 1474 * 1475 * @see java.lang.System#initPhase1 1476 */ 1477 static void initLibraryPaths() { 1478 usr_paths = initializePath("java.library.path"); 1479 sys_paths = initializePath("sun.boot.library.path"); 1480 } 1481 1482 // Returns true if the specified class loader can be found in this class 1483 // loader's delegation chain. 1484 boolean isAncestor(ClassLoader cl) { 1485 ClassLoader acl = this; 1486 do { 1487 acl = acl.parent; 1488 if (cl == acl) { 1489 return true; 1490 } 1491 } while (acl != null); 1492 return false; 1493 } 1494 1495 // Tests if class loader access requires "getClassLoader" permission 1496 // check. A class loader 'from' can access class loader 'to' if 1497 // class loader 'from' is same as class loader 'to' or an ancestor 1498 // of 'to'. The class loader in a system domain can access 1499 // any class loader. 1500 private static boolean needsClassLoaderPermissionCheck(ClassLoader from, 1501 ClassLoader to) 1502 { 1503 if (from == to) 1504 return false; 1505 1506 if (from == null) 1507 return false; 1508 1509 return !to.isAncestor(from); 1510 } 1511 1512 // Returns the class's class loader, or null if none. 1513 static ClassLoader getClassLoader(Class<?> caller) { 1514 // This can be null if the VM is requesting it 1515 if (caller == null) { 1516 return null; 1517 } 1518 // Circumvent security check since this is package-private 1519 return caller.getClassLoader0(); 1520 } 1521 1522 /* 1523 * Checks RuntimePermission("getClassLoader") permission 1524 * if caller's class loader is not null and caller's class loader 1525 * is not the same as or an ancestor of the given cl argument. 1526 */ 1527 static void checkClassLoaderPermission(ClassLoader cl, Class<?> caller) { 1528 SecurityManager sm = System.getSecurityManager(); 1529 if (sm != null) { 1530 // caller can be null if the VM is requesting it 1531 ClassLoader ccl = getClassLoader(caller); 1532 if (needsClassLoaderPermissionCheck(ccl, cl)) { 1533 sm.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION); 1534 } 1535 } 1536 } 1537 1538 // The class loader for the system 1539 // @GuardedBy("ClassLoader.class") 1540 private static ClassLoader scl; 1541 1542 // Set to true once the system class loader has been set 1543 // @GuardedBy("ClassLoader.class") 1544 private static boolean sclSet; 1545 1546 1547 // -- Package -- 1548 1549 /** 1550 * Defines a package by name in this <tt>ClassLoader</tt>. This allows 1551 * class loaders to define the packages for their classes. Packages must 1552 * be created before the class is defined, and package names must be 1553 * unique within a class loader and cannot be redefined or changed once 1554 * created. 1555 * 1556 * @param name 1557 * The package name 1558 * 1559 * @param specTitle 1560 * The specification title 1561 * 1562 * @param specVersion 1563 * The specification version 1564 * 1565 * @param specVendor 1566 * The specification vendor 1567 * 1568 * @param implTitle 1569 * The implementation title 1570 * 1571 * @param implVersion 1572 * The implementation version 1573 * 1574 * @param implVendor 1575 * The implementation vendor 1576 * 1577 * @param sealBase 1578 * If not <tt>null</tt>, then this package is sealed with 1579 * respect to the given code source {@link java.net.URL 1580 * <tt>URL</tt>} object. Otherwise, the package is not sealed. 1581 * 1582 * @return The newly defined <tt>Package</tt> object 1583 * 1584 * @throws IllegalArgumentException 1585 * If package name duplicates an existing package either in this 1586 * class loader or one of its ancestors 1587 * 1588 * @since 1.2 1589 */ 1590 protected Package definePackage(String name, String specTitle, 1591 String specVersion, String specVendor, 1592 String implTitle, String implVersion, 1593 String implVendor, URL sealBase) 1594 throws IllegalArgumentException 1595 { 1596 synchronized (packages) { 1597 Package pkg = getPackage(name); 1598 if (pkg != null) { 1599 throw new IllegalArgumentException(name); 1600 } 1601 pkg = new Package(name, specTitle, specVersion, specVendor, 1602 implTitle, implVersion, implVendor, 1603 sealBase, this); 1604 packages.put(name, pkg); 1605 return pkg; 1606 } 1607 } 1608 1609 /** 1610 * Returns a <tt>Package</tt> that has been defined by this class loader 1611 * or any of its ancestors. 1612 * 1613 * @param name 1614 * The package name 1615 * 1616 * @return The <tt>Package</tt> corresponding to the given name, or 1617 * <tt>null</tt> if not found 1618 * 1619 * @since 1.2 1620 */ 1621 protected Package getPackage(String name) { 1622 Package pkg; 1623 synchronized (packages) { 1624 pkg = packages.get(name); 1625 } 1626 if (pkg == null) { 1627 if (parent != null) { 1628 pkg = parent.getPackage(name); 1629 } else { 1630 pkg = Package.getSystemPackage(name); 1631 } 1632 if (pkg != null) { 1633 synchronized (packages) { 1634 Package pkg2 = packages.get(name); 1635 if (pkg2 == null) { 1636 packages.put(name, pkg); 1637 } else { 1638 pkg = pkg2; 1639 } 1640 } 1641 } 1642 } 1643 return pkg; 1644 } 1645 1646 /** 1647 * Returns all of the <tt>Packages</tt> defined by this class loader and 1648 * its ancestors. 1649 * 1650 * @return The array of <tt>Package</tt> objects defined by this 1651 * <tt>ClassLoader</tt> 1652 * 1653 * @since 1.2 1654 */ 1655 protected Package[] getPackages() { 1656 Map<String, Package> map; 1657 synchronized (packages) { 1658 map = new HashMap<>(packages); 1659 } 1660 Package[] pkgs; 1661 if (parent != null) { 1662 pkgs = parent.getPackages(); 1663 } else { 1664 pkgs = Package.getSystemPackages(); 1665 } 1666 if (pkgs != null) { 1667 for (int i = 0; i < pkgs.length; i++) { 1668 String pkgName = pkgs[i].getName(); 1669 if (map.get(pkgName) == null) { 1670 map.put(pkgName, pkgs[i]); 1671 } 1672 } 1673 } 1674 return map.values().toArray(new Package[map.size()]); 1675 } 1676 1677 1678 // -- Native library access -- 1679 1680 /** 1681 * Returns the absolute path name of a native library. The VM invokes this 1682 * method to locate the native libraries that belong to classes loaded with 1683 * this class loader. If this method returns <tt>null</tt>, the VM 1684 * searches the library along the path specified as the 1685 * "<tt>java.library.path</tt>" property. 1686 * 1687 * @param libname 1688 * The library name 1689 * 1690 * @return The absolute path of the native library 1691 * 1692 * @see System#loadLibrary(String) 1693 * @see System#mapLibraryName(String) 1694 * 1695 * @since 1.2 1696 */ 1697 protected String findLibrary(String libname) { 1698 return null; 1699 } 1700 1701 /** 1702 * The inner class NativeLibrary denotes a loaded native library instance. 1703 * Every classloader contains a vector of loaded native libraries in the 1704 * private field <tt>nativeLibraries</tt>. The native libraries loaded 1705 * into the system are entered into the <tt>systemNativeLibraries</tt> 1706 * vector. 1707 * 1708 * <p> Every native library requires a particular version of JNI. This is 1709 * denoted by the private <tt>jniVersion</tt> field. This field is set by 1710 * the VM when it loads the library, and used by the VM to pass the correct 1711 * version of JNI to the native methods. </p> 1712 * 1713 * @see ClassLoader 1714 * @since 1.2 1715 */ 1716 static class NativeLibrary { 1717 // opaque handle to native library, used in native code. 1718 long handle; 1719 // the version of JNI environment the native library requires. 1720 private int jniVersion; 1721 // the class from which the library is loaded, also indicates 1722 // the loader this native library belongs. 1723 private final Class<?> fromClass; 1724 // the canonicalized name of the native library. 1725 // or static library name 1726 String name; 1727 // Indicates if the native library is linked into the VM 1728 boolean isBuiltin; 1729 // Indicates if the native library is loaded 1730 boolean loaded; 1731 native void load(String name, boolean isBuiltin); 1732 1733 native long find(String name); 1734 native void unload(String name, boolean isBuiltin); 1735 1736 public NativeLibrary(Class<?> fromClass, String name, boolean isBuiltin) { 1737 this.name = name; 1738 this.fromClass = fromClass; 1739 this.isBuiltin = isBuiltin; 1740 } 1741 1742 protected void finalize() { 1743 synchronized (loadedLibraryNames) { 1744 if (fromClass.getClassLoader() != null && loaded) { 1745 /* remove the native library name */ 1746 int size = loadedLibraryNames.size(); 1747 for (int i = 0; i < size; i++) { 1748 if (name.equals(loadedLibraryNames.elementAt(i))) { 1749 loadedLibraryNames.removeElementAt(i); 1750 break; 1751 } 1752 } 1753 /* unload the library. */ 1754 ClassLoader.nativeLibraryContext.push(this); 1755 try { 1756 unload(name, isBuiltin); 1757 } finally { 1758 ClassLoader.nativeLibraryContext.pop(); 1759 } 1760 } 1761 } 1762 } 1763 // Invoked in the VM to determine the context class in 1764 // JNI_Load/JNI_Unload 1765 static Class<?> getFromClass() { 1766 return ClassLoader.nativeLibraryContext.peek().fromClass; 1767 } 1768 } 1769 1770 // All native library names we've loaded. 1771 private static Vector<String> loadedLibraryNames = new Vector<>(); 1772 1773 // Native libraries belonging to system classes. 1774 private static Vector<NativeLibrary> systemNativeLibraries 1775 = new Vector<>(); 1776 1777 // Native libraries associated with the class loader. 1778 private Vector<NativeLibrary> nativeLibraries = new Vector<>(); 1779 1780 // native libraries being loaded/unloaded. 1781 private static Stack<NativeLibrary> nativeLibraryContext = new Stack<>(); 1782 1783 // The paths searched for libraries 1784 private static String usr_paths[]; 1785 private static String sys_paths[]; 1786 1787 private static String[] initializePath(String propname) { 1788 String ldpath = System.getProperty(propname, ""); 1789 String ps = File.pathSeparator; 1790 int ldlen = ldpath.length(); 1791 int i, j, n; 1792 // Count the separators in the path 1793 i = ldpath.indexOf(ps); 1794 n = 0; 1795 while (i >= 0) { 1796 n++; 1797 i = ldpath.indexOf(ps, i + 1); 1798 } 1799 1800 // allocate the array of paths - n :'s = n + 1 path elements 1801 String[] paths = new String[n + 1]; 1802 1803 // Fill the array with paths from the ldpath 1804 n = i = 0; 1805 j = ldpath.indexOf(ps); 1806 while (j >= 0) { 1807 if (j - i > 0) { 1808 paths[n++] = ldpath.substring(i, j); 1809 } else if (j - i == 0) { 1810 paths[n++] = "."; 1811 } 1812 i = j + 1; 1813 j = ldpath.indexOf(ps, i); 1814 } 1815 paths[n] = ldpath.substring(i, ldlen); 1816 return paths; 1817 } 1818 1819 // Invoked in the java.lang.Runtime class to implement load and loadLibrary. 1820 static void loadLibrary(Class<?> fromClass, String name, 1821 boolean isAbsolute) { 1822 ClassLoader loader = 1823 (fromClass == null) ? null : fromClass.getClassLoader(); 1824 assert sys_paths != null : "should be initialized at this point"; 1825 assert usr_paths != null : "should be initialized at this point"; 1826 1827 if (isAbsolute) { 1828 if (loadLibrary0(fromClass, new File(name))) { 1829 return; 1830 } 1831 throw new UnsatisfiedLinkError("Can't load library: " + name); 1832 } 1833 if (loader != null) { 1834 String libfilename = loader.findLibrary(name); 1835 if (libfilename != null) { 1836 File libfile = new File(libfilename); 1837 if (!libfile.isAbsolute()) { 1838 throw new UnsatisfiedLinkError( 1839 "ClassLoader.findLibrary failed to return an absolute path: " + libfilename); 1840 } 1841 if (loadLibrary0(fromClass, libfile)) { 1842 return; 1843 } 1844 throw new UnsatisfiedLinkError("Can't load " + libfilename); 1845 } 1846 } 1847 for (int i = 0 ; i < sys_paths.length ; i++) { 1848 File libfile = new File(sys_paths[i], System.mapLibraryName(name)); 1849 if (loadLibrary0(fromClass, libfile)) { 1850 return; 1851 } 1852 libfile = ClassLoaderHelper.mapAlternativeName(libfile); 1853 if (libfile != null && loadLibrary0(fromClass, libfile)) { 1854 return; 1855 } 1856 } 1857 if (loader != null) { 1858 for (int i = 0 ; i < usr_paths.length ; i++) { 1859 File libfile = new File(usr_paths[i], 1860 System.mapLibraryName(name)); 1861 if (loadLibrary0(fromClass, libfile)) { 1862 return; 1863 } 1864 libfile = ClassLoaderHelper.mapAlternativeName(libfile); 1865 if (libfile != null && loadLibrary0(fromClass, libfile)) { 1866 return; 1867 } 1868 } 1869 } 1870 // Oops, it failed 1871 throw new UnsatisfiedLinkError("no " + name + " in java.library.path"); 1872 } 1873 1874 private static native String findBuiltinLib(String name); 1875 1876 private static boolean loadLibrary0(Class<?> fromClass, final File file) { 1877 // Check to see if we're attempting to access a static library 1878 String name = findBuiltinLib(file.getName()); 1879 boolean isBuiltin = (name != null); 1880 if (!isBuiltin) { 1881 boolean exists = AccessController.doPrivileged( 1882 new PrivilegedAction<Object>() { 1883 public Object run() { 1884 return file.exists() ? Boolean.TRUE : null; 1885 }}) 1886 != null; 1887 if (!exists) { 1888 return false; 1889 } 1890 try { 1891 name = file.getCanonicalPath(); 1892 } catch (IOException e) { 1893 return false; 1894 } 1895 } 1896 ClassLoader loader = 1897 (fromClass == null) ? null : fromClass.getClassLoader(); 1898 Vector<NativeLibrary> libs = 1899 loader != null ? loader.nativeLibraries : systemNativeLibraries; 1900 synchronized (libs) { 1901 int size = libs.size(); 1902 for (int i = 0; i < size; i++) { 1903 NativeLibrary lib = libs.elementAt(i); 1904 if (name.equals(lib.name)) { 1905 return true; 1906 } 1907 } 1908 1909 synchronized (loadedLibraryNames) { 1910 if (loadedLibraryNames.contains(name)) { 1911 throw new UnsatisfiedLinkError 1912 ("Native Library " + 1913 name + 1914 " already loaded in another classloader"); 1915 } 1916 /* 1917 * When a library is being loaded, JNI_OnLoad function can cause 1918 * another loadLibrary invocation that should succeed. 1919 * 1920 * We use a static stack to hold the list of libraries we are 1921 * loading because this can happen only when called by the 1922 * same thread because Runtime.load and Runtime.loadLibrary 1923 * are synchronous. 1924 * 1925 * If there is a pending load operation for the library, we 1926 * immediately return success; otherwise, we raise 1927 * UnsatisfiedLinkError. 1928 */ 1929 int n = nativeLibraryContext.size(); 1930 for (int i = 0; i < n; i++) { 1931 NativeLibrary lib = nativeLibraryContext.elementAt(i); 1932 if (name.equals(lib.name)) { 1933 if (loader == lib.fromClass.getClassLoader()) { 1934 return true; 1935 } else { 1936 throw new UnsatisfiedLinkError 1937 ("Native Library " + 1938 name + 1939 " is being loaded in another classloader"); 1940 } 1941 } 1942 } 1943 NativeLibrary lib = new NativeLibrary(fromClass, name, isBuiltin); 1944 nativeLibraryContext.push(lib); 1945 try { 1946 lib.load(name, isBuiltin); 1947 } finally { 1948 nativeLibraryContext.pop(); 1949 } 1950 if (lib.loaded) { 1951 loadedLibraryNames.addElement(name); 1952 libs.addElement(lib); 1953 return true; 1954 } 1955 return false; 1956 } 1957 } 1958 } 1959 1960 // Invoked in the VM class linking code. 1961 static long findNative(ClassLoader loader, String name) { 1962 Vector<NativeLibrary> libs = 1963 loader != null ? loader.nativeLibraries : systemNativeLibraries; 1964 synchronized (libs) { 1965 int size = libs.size(); 1966 for (int i = 0; i < size; i++) { 1967 NativeLibrary lib = libs.elementAt(i); 1968 long entry = lib.find(name); 1969 if (entry != 0) 1970 return entry; 1971 } 1972 } 1973 return 0; 1974 } 1975 1976 1977 // -- Assertion management -- 1978 1979 final Object assertionLock; 1980 1981 // The default toggle for assertion checking. 1982 // @GuardedBy("assertionLock") 1983 private boolean defaultAssertionStatus = false; 1984 1985 // Maps String packageName to Boolean package default assertion status Note 1986 // that the default package is placed under a null map key. If this field 1987 // is null then we are delegating assertion status queries to the VM, i.e., 1988 // none of this ClassLoader's assertion status modification methods have 1989 // been invoked. 1990 // @GuardedBy("assertionLock") 1991 private Map<String, Boolean> packageAssertionStatus = null; 1992 1993 // Maps String fullyQualifiedClassName to Boolean assertionStatus If this 1994 // field is null then we are delegating assertion status queries to the VM, 1995 // i.e., none of this ClassLoader's assertion status modification methods 1996 // have been invoked. 1997 // @GuardedBy("assertionLock") 1998 Map<String, Boolean> classAssertionStatus = null; 1999 2000 /** 2001 * Sets the default assertion status for this class loader. This setting 2002 * determines whether classes loaded by this class loader and initialized 2003 * in the future will have assertions enabled or disabled by default. 2004 * This setting may be overridden on a per-package or per-class basis by 2005 * invoking {@link #setPackageAssertionStatus(String, boolean)} or {@link 2006 * #setClassAssertionStatus(String, boolean)}. 2007 * 2008 * @param enabled 2009 * <tt>true</tt> if classes loaded by this class loader will 2010 * henceforth have assertions enabled by default, <tt>false</tt> 2011 * if they will have assertions disabled by default. 2012 * 2013 * @since 1.4 2014 */ 2015 public void setDefaultAssertionStatus(boolean enabled) { 2016 synchronized (assertionLock) { 2017 if (classAssertionStatus == null) 2018 initializeJavaAssertionMaps(); 2019 2020 defaultAssertionStatus = enabled; 2021 } 2022 } 2023 2024 /** 2025 * Sets the package default assertion status for the named package. The 2026 * package default assertion status determines the assertion status for 2027 * classes initialized in the future that belong to the named package or 2028 * any of its "subpackages". 2029 * 2030 * <p> A subpackage of a package named p is any package whose name begins 2031 * with "<tt>p.</tt>". For example, <tt>javax.swing.text</tt> is a 2032 * subpackage of <tt>javax.swing</tt>, and both <tt>java.util</tt> and 2033 * <tt>java.lang.reflect</tt> are subpackages of <tt>java</tt>. 2034 * 2035 * <p> In the event that multiple package defaults apply to a given class, 2036 * the package default pertaining to the most specific package takes 2037 * precedence over the others. For example, if <tt>javax.lang</tt> and 2038 * <tt>javax.lang.reflect</tt> both have package defaults associated with 2039 * them, the latter package default applies to classes in 2040 * <tt>javax.lang.reflect</tt>. 2041 * 2042 * <p> Package defaults take precedence over the class loader's default 2043 * assertion status, and may be overridden on a per-class basis by invoking 2044 * {@link #setClassAssertionStatus(String, boolean)}. </p> 2045 * 2046 * @param packageName 2047 * The name of the package whose package default assertion status 2048 * is to be set. A <tt>null</tt> value indicates the unnamed 2049 * package that is "current" 2050 * (see section 7.4.2 of 2051 * <cite>The Java™ Language Specification</cite>.) 2052 * 2053 * @param enabled 2054 * <tt>true</tt> if classes loaded by this classloader and 2055 * belonging to the named package or any of its subpackages will 2056 * have assertions enabled by default, <tt>false</tt> if they will 2057 * have assertions disabled by default. 2058 * 2059 * @since 1.4 2060 */ 2061 public void setPackageAssertionStatus(String packageName, 2062 boolean enabled) { 2063 synchronized (assertionLock) { 2064 if (packageAssertionStatus == null) 2065 initializeJavaAssertionMaps(); 2066 2067 packageAssertionStatus.put(packageName, enabled); 2068 } 2069 } 2070 2071 /** 2072 * Sets the desired assertion status for the named top-level class in this 2073 * class loader and any nested classes contained therein. This setting 2074 * takes precedence over the class loader's default assertion status, and 2075 * over any applicable per-package default. This method has no effect if 2076 * the named class has already been initialized. (Once a class is 2077 * initialized, its assertion status cannot change.) 2078 * 2079 * <p> If the named class is not a top-level class, this invocation will 2080 * have no effect on the actual assertion status of any class. </p> 2081 * 2082 * @param className 2083 * The fully qualified class name of the top-level class whose 2084 * assertion status is to be set. 2085 * 2086 * @param enabled 2087 * <tt>true</tt> if the named class is to have assertions 2088 * enabled when (and if) it is initialized, <tt>false</tt> if the 2089 * class is to have assertions disabled. 2090 * 2091 * @since 1.4 2092 */ 2093 public void setClassAssertionStatus(String className, boolean enabled) { 2094 synchronized (assertionLock) { 2095 if (classAssertionStatus == null) 2096 initializeJavaAssertionMaps(); 2097 2098 classAssertionStatus.put(className, enabled); 2099 } 2100 } 2101 2102 /** 2103 * Sets the default assertion status for this class loader to 2104 * <tt>false</tt> and discards any package defaults or class assertion 2105 * status settings associated with the class loader. This method is 2106 * provided so that class loaders can be made to ignore any command line or 2107 * persistent assertion status settings and "start with a clean slate." 2108 * 2109 * @since 1.4 2110 */ 2111 public void clearAssertionStatus() { 2112 /* 2113 * Whether or not "Java assertion maps" are initialized, set 2114 * them to empty maps, effectively ignoring any present settings. 2115 */ 2116 synchronized (assertionLock) { 2117 classAssertionStatus = new HashMap<>(); 2118 packageAssertionStatus = new HashMap<>(); 2119 defaultAssertionStatus = false; 2120 } 2121 } 2122 2123 /** 2124 * Returns the assertion status that would be assigned to the specified 2125 * class if it were to be initialized at the time this method is invoked. 2126 * If the named class has had its assertion status set, the most recent 2127 * setting will be returned; otherwise, if any package default assertion 2128 * status pertains to this class, the most recent setting for the most 2129 * specific pertinent package default assertion status is returned; 2130 * otherwise, this class loader's default assertion status is returned. 2131 * </p> 2132 * 2133 * @param className 2134 * The fully qualified class name of the class whose desired 2135 * assertion status is being queried. 2136 * 2137 * @return The desired assertion status of the specified class. 2138 * 2139 * @see #setClassAssertionStatus(String, boolean) 2140 * @see #setPackageAssertionStatus(String, boolean) 2141 * @see #setDefaultAssertionStatus(boolean) 2142 * 2143 * @since 1.4 2144 */ 2145 boolean desiredAssertionStatus(String className) { 2146 synchronized (assertionLock) { 2147 // assert classAssertionStatus != null; 2148 // assert packageAssertionStatus != null; 2149 2150 // Check for a class entry 2151 Boolean result = classAssertionStatus.get(className); 2152 if (result != null) 2153 return result.booleanValue(); 2154 2155 // Check for most specific package entry 2156 int dotIndex = className.lastIndexOf("."); 2157 if (dotIndex < 0) { // default package 2158 result = packageAssertionStatus.get(null); 2159 if (result != null) 2160 return result.booleanValue(); 2161 } 2162 while(dotIndex > 0) { 2163 className = className.substring(0, dotIndex); 2164 result = packageAssertionStatus.get(className); 2165 if (result != null) 2166 return result.booleanValue(); 2167 dotIndex = className.lastIndexOf(".", dotIndex-1); 2168 } 2169 2170 // Return the classloader default 2171 return defaultAssertionStatus; 2172 } 2173 } 2174 2175 // Set up the assertions with information provided by the VM. 2176 // Note: Should only be called inside a synchronized block 2177 private void initializeJavaAssertionMaps() { 2178 // assert Thread.holdsLock(assertionLock); 2179 2180 classAssertionStatus = new HashMap<>(); 2181 packageAssertionStatus = new HashMap<>(); 2182 AssertionStatusDirectives directives = retrieveDirectives(); 2183 2184 for(int i = 0; i < directives.classes.length; i++) 2185 classAssertionStatus.put(directives.classes[i], 2186 directives.classEnabled[i]); 2187 2188 for(int i = 0; i < directives.packages.length; i++) 2189 packageAssertionStatus.put(directives.packages[i], 2190 directives.packageEnabled[i]); 2191 2192 defaultAssertionStatus = directives.deflt; 2193 } 2194 2195 // Retrieves the assertion directives from the VM. 2196 private static native AssertionStatusDirectives retrieveDirectives(); 2197 } 2198 2199 2200 class SystemClassLoaderAction 2201 implements PrivilegedExceptionAction<ClassLoader> { 2202 private ClassLoader parent; 2203 2204 SystemClassLoaderAction(ClassLoader parent) { 2205 this.parent = parent; 2206 } 2207 2208 public ClassLoader run() throws Exception { 2209 String cls = System.getProperty("java.system.class.loader"); 2210 if (cls == null) { 2211 return parent; 2212 } 2213 2214 Constructor<?> ctor = Class.forName(cls, true, parent) 2215 .getDeclaredConstructor(new Class<?>[] { ClassLoader.class }); 2216 ClassLoader sys = (ClassLoader) ctor.newInstance( 2217 new Object[] { parent }); 2218 Thread.currentThread().setContextClassLoader(sys); 2219 return sys; 2220 } 2221 }