1/* 2 * Copyright (c) 2013, 2017, 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 26package java.lang; 27 28import java.io.InputStream; 29import java.io.IOException; 30import java.io.UncheckedIOException; 31import java.io.File; 32import java.lang.reflect.Constructor; 33import java.lang.reflect.Field; 34import java.net.URL; 35import java.security.AccessController; 36import java.security.AccessControlContext; 37import java.security.CodeSource; 38import java.security.PrivilegedAction; 39import java.security.ProtectionDomain; 40import java.security.cert.Certificate; 41import java.util.Collections; 42import java.util.Enumeration; 43import java.util.HashMap; 44import java.util.Hashtable; 45import java.util.Map; 46import java.util.NoSuchElementException; 47import java.util.Objects; 48import java.util.Set; 49import java.util.Spliterator; 50import java.util.Spliterators; 51import java.util.Stack; 52import java.util.Vector; 53import java.util.WeakHashMap; 54import java.util.concurrent.ConcurrentHashMap; 55import java.util.function.Supplier; 56import java.util.stream.Stream; 57import java.util.stream.StreamSupport; 58 59import jdk.internal.perf.PerfCounter; 60import jdk.internal.loader.BootLoader; 61import jdk.internal.loader.ClassLoaders; 62import jdk.internal.misc.SharedSecrets; 63import jdk.internal.misc.Unsafe; 64import jdk.internal.misc.VM; 65import jdk.internal.reflect.CallerSensitive; 66import jdk.internal.reflect.Reflection; 67import sun.reflect.misc.ReflectUtil; 68import sun.security.util.SecurityConstants; 69 70/** 71 * A class loader is an object that is responsible for loading classes. The 72 * class {@code ClassLoader} is an abstract class. Given the <a 73 * href="#name">binary name</a> of a class, a class loader should attempt to 74 * locate or generate data that constitutes a definition for the class. A 75 * typical strategy is to transform the name into a file name and then read a 76 * "class file" of that name from a file system. 77 * 78 * <p> Every {@link java.lang.Class Class} object contains a {@link 79 * Class#getClassLoader() reference} to the {@code ClassLoader} that defined 80 * it. 81 * 82 * <p> {@code Class} objects for array classes are not created by class 83 * loaders, but are created automatically as required by the Java runtime. 84 * The class loader for an array class, as returned by {@link 85 * Class#getClassLoader()} is the same as the class loader for its element 86 * type; if the element type is a primitive type, then the array class has no 87 * class loader. 88 * 89 * <p> Applications implement subclasses of {@code ClassLoader} in order to 90 * extend the manner in which the Java virtual machine dynamically loads 91 * classes. 92 * 93 * <p> Class loaders may typically be used by security managers to indicate 94 * security domains. 95 * 96 * <p> In addition to loading classes, a class loader is also responsible for 97 * locating resources. A resource is some data (a "{@code .class}" file, 98 * configuration data, or an image for example) that is identified with an 99 * abstract '/'-separated path name. Resources are typically packaged with an 100 * application or library so that they can be located by code in the 101 * application or library. In some cases, the resources are included so that 102 * they can be located by other libraries. 103 * 104 * <p> The {@code ClassLoader} class uses a delegation model to search for 105 * classes and resources. Each instance of {@code ClassLoader} has an 106 * associated parent class loader. When requested to find a class or 107 * resource, a {@code ClassLoader} instance will usually delegate the search 108 * for the class or resource to its parent class loader before attempting to 109 * find the class or resource itself. 110 * 111 * <p> Class loaders that support concurrent loading of classes are known as 112 * <em>{@linkplain #isRegisteredAsParallelCapable() parallel capable}</em> class 113 * loaders and are required to register themselves at their class initialization 114 * time by invoking the {@link 115 * #registerAsParallelCapable ClassLoader.registerAsParallelCapable} 116 * method. Note that the {@code ClassLoader} class is registered as parallel 117 * capable by default. However, its subclasses still need to register themselves 118 * if they are parallel capable. 119 * In environments in which the delegation model is not strictly 120 * hierarchical, class loaders need to be parallel capable, otherwise class 121 * loading can lead to deadlocks because the loader lock is held for the 122 * duration of the class loading process (see {@link #loadClass 123 * loadClass} methods). 124 * 125 * <h3> <a id="builtinLoaders">Run-time Built-in Class Loaders</a></h3> 126 * 127 * The Java run-time has the following built-in class loaders: 128 * 129 * <ul> 130 * <li><p>Bootstrap class loader. 131 * It is the virtual machine's built-in class loader, typically represented 132 * as {@code null}, and does not have a parent.</li> 133 * <li><p>{@linkplain #getPlatformClassLoader() Platform class loader}. 134 * All <em>platform classes</em> are visible to the platform class loader 135 * that can be used as the parent of a {@code ClassLoader} instance. 136 * Platform classes include Java SE platform APIs, their implementation 137 * classes and JDK-specific run-time classes that are defined by the 138 * platform class loader or its ancestors. 139 * <p> To allow for upgrading/overriding of modules defined to the platform 140 * class loader, and where upgraded modules read modules defined to class 141 * loaders other than the platform class loader and its ancestors, then 142 * the platform class loader may have to delegate to other class loaders, 143 * the application class loader for example. 144 * In other words, classes in named modules defined to class loaders 145 * other than the platform class loader and its ancestors may be visible 146 * to the platform class loader. </li> 147 * <li><p>{@linkplain #getSystemClassLoader() System class loader}. 148 * It is also known as <em>application class loader</em> and is distinct 149 * from the platform class loader. 150 * The system class loader is typically used to define classes on the 151 * application class path, module path, and JDK-specific tools. 152 * The platform class loader is a parent or an ancestor of the system class 153 * loader that all platform classes are visible to it.</li> 154 * </ul> 155 * 156 * <p> Normally, the Java virtual machine loads classes from the local file 157 * system in a platform-dependent manner. 158 * However, some classes may not originate from a file; they may originate 159 * from other sources, such as the network, or they could be constructed by an 160 * application. The method {@link #defineClass(String, byte[], int, int) 161 * defineClass} converts an array of bytes into an instance of class 162 * {@code Class}. Instances of this newly defined class can be created using 163 * {@link Class#newInstance Class.newInstance}. 164 * 165 * <p> The methods and constructors of objects created by a class loader may 166 * reference other classes. To determine the class(es) referred to, the Java 167 * virtual machine invokes the {@link #loadClass loadClass} method of 168 * the class loader that originally created the class. 169 * 170 * <p> For example, an application could create a network class loader to 171 * download class files from a server. Sample code might look like: 172 * 173 * <blockquote><pre> 174 * ClassLoader loader = new NetworkClassLoader(host, port); 175 * Object main = loader.loadClass("Main", true).newInstance(); 176 * . . . 177 * </pre></blockquote> 178 * 179 * <p> The network class loader subclass must define the methods {@link 180 * #findClass findClass} and {@code loadClassData} to load a class 181 * from the network. Once it has downloaded the bytes that make up the class, 182 * it should use the method {@link #defineClass defineClass} to 183 * create a class instance. A sample implementation is: 184 * 185 * <blockquote><pre> 186 * class NetworkClassLoader extends ClassLoader { 187 * String host; 188 * int port; 189 * 190 * public Class findClass(String name) { 191 * byte[] b = loadClassData(name); 192 * return defineClass(name, b, 0, b.length); 193 * } 194 * 195 * private byte[] loadClassData(String name) { 196 * // load the class data from the connection 197 * . . . 198 * } 199 * } 200 * </pre></blockquote> 201 * 202 * <h3> <a id="name">Binary names</a> </h3> 203 * 204 * <p> Any class name provided as a {@code String} parameter to methods in 205 * {@code ClassLoader} must be a binary name as defined by 206 * <cite>The Java™ Language Specification</cite>. 207 * 208 * <p> Examples of valid class names include: 209 * <blockquote><pre> 210 * "java.lang.String" 211 * "javax.swing.JSpinner$DefaultEditor" 212 * "java.security.KeyStore$Builder$FileBuilder$1" 213 * "java.net.URLClassLoader$3$1" 214 * </pre></blockquote> 215 * 216 * <p> Any package name provided as a {@code String} parameter to methods in 217 * {@code ClassLoader} must be either the empty string (denoting an unnamed package) 218 * or a fully qualified name as defined by 219 * <cite>The Java™ Language Specification</cite>. 220 * 221 * @jls 6.7 Fully Qualified Names 222 * @jls 13.1 The Form of a Binary 223 * @see #resolveClass(Class) 224 * @since 1.0 225 * @revised 9 226 * @spec JPMS 227 */ 228public abstract class ClassLoader { 229 230 private static native void registerNatives(); 231 static { 232 registerNatives(); 233 } 234 235 // The parent class loader for delegation 236 // Note: VM hardcoded the offset of this field, thus all new fields 237 // must be added *after* it. 238 private final ClassLoader parent; 239 240 // class loader name 241 private final String name; 242 243 // the unnamed module for this ClassLoader 244 private final Module unnamedModule; 245 246 /** 247 * Encapsulates the set of parallel capable loader types. 248 */ 249 private static class ParallelLoaders { 250 private ParallelLoaders() {} 251 252 // the set of parallel capable loader types 253 private static final Set<Class<? extends ClassLoader>> loaderTypes = 254 Collections.newSetFromMap(new WeakHashMap<>()); 255 static { 256 synchronized (loaderTypes) { loaderTypes.add(ClassLoader.class); } 257 } 258 259 /** 260 * Registers the given class loader type as parallel capable. 261 * Returns {@code true} is successfully registered; {@code false} if 262 * loader's super class is not registered. 263 */ 264 static boolean register(Class<? extends ClassLoader> c) { 265 synchronized (loaderTypes) { 266 if (loaderTypes.contains(c.getSuperclass())) { 267 // register the class loader as parallel capable 268 // if and only if all of its super classes are. 269 // Note: given current classloading sequence, if 270 // the immediate super class is parallel capable, 271 // all the super classes higher up must be too. 272 loaderTypes.add(c); 273 return true; 274 } else { 275 return false; 276 } 277 } 278 } 279 280 /** 281 * Returns {@code true} if the given class loader type is 282 * registered as parallel capable. 283 */ 284 static boolean isRegistered(Class<? extends ClassLoader> c) { 285 synchronized (loaderTypes) { 286 return loaderTypes.contains(c); 287 } 288 } 289 } 290 291 // Maps class name to the corresponding lock object when the current 292 // class loader is parallel capable. 293 // Note: VM also uses this field to decide if the current class loader 294 // is parallel capable and the appropriate lock object for class loading. 295 private final ConcurrentHashMap<String, Object> parallelLockMap; 296 297 // Maps packages to certs 298 private final Map <String, Certificate[]> package2certs; 299 300 // Shared among all packages with unsigned classes 301 private static final Certificate[] nocerts = new Certificate[0]; 302 303 // The classes loaded by this class loader. The only purpose of this table 304 // is to keep the classes from being GC'ed until the loader is GC'ed. 305 private final Vector<Class<?>> classes = new Vector<>(); 306 307 // The "default" domain. Set as the default ProtectionDomain on newly 308 // created classes. 309 private final ProtectionDomain defaultDomain = 310 new ProtectionDomain(new CodeSource(null, (Certificate[]) null), 311 null, this, null); 312 313 // Invoked by the VM to record every loaded class with this loader. 314 void addClass(Class<?> c) { 315 classes.addElement(c); 316 } 317 318 // The packages defined in this class loader. Each package name is 319 // mapped to its corresponding NamedPackage object. 320 // 321 // The value is a Package object if ClassLoader::definePackage, 322 // Class::getPackage, ClassLoader::getDefinePackage(s) or 323 // Package::getPackage(s) method is called to define it. 324 // Otherwise, the value is a NamedPackage object. 325 private final ConcurrentHashMap<String, NamedPackage> packages 326 = new ConcurrentHashMap<>(); 327 328 /* 329 * Returns a named package for the given module. 330 */ 331 private NamedPackage getNamedPackage(String pn, Module m) { 332 NamedPackage p = packages.get(pn); 333 if (p == null) { 334 p = new NamedPackage(pn, m); 335 336 NamedPackage value = packages.putIfAbsent(pn, p); 337 if (value != null) { 338 // Package object already be defined for the named package 339 p = value; 340 // if definePackage is called by this class loader to define 341 // a package in a named module, this will return Package 342 // object of the same name. Package object may contain 343 // unexpected information but it does not impact the runtime. 344 // this assertion may be helpful for troubleshooting 345 assert value.module() == m; 346 } 347 } 348 return p; 349 } 350 351 private static Void checkCreateClassLoader() { 352 return checkCreateClassLoader(null); 353 } 354 355 private static Void checkCreateClassLoader(String name) { 356 if (name != null && name.isEmpty()) { 357 throw new IllegalArgumentException("name must be non-empty or null"); 358 } 359 360 SecurityManager security = System.getSecurityManager(); 361 if (security != null) { 362 security.checkCreateClassLoader(); 363 } 364 return null; 365 } 366 367 private ClassLoader(Void unused, String name, ClassLoader parent) { 368 this.name = name; 369 this.parent = parent; 370 this.unnamedModule = new Module(this); 371 if (ParallelLoaders.isRegistered(this.getClass())) { 372 parallelLockMap = new ConcurrentHashMap<>(); 373 package2certs = new ConcurrentHashMap<>(); 374 assertionLock = new Object(); 375 } else { 376 // no finer-grained lock; lock on the classloader instance 377 parallelLockMap = null; 378 package2certs = new Hashtable<>(); 379 assertionLock = this; 380 } 381 } 382 383 /** 384 * Creates a new class loader of the specified name and using the 385 * specified parent class loader for delegation. 386 * 387 * @apiNote If the parent is specified as {@code null} (for the 388 * bootstrap class loader) then there is no guarantee that all platform 389 * classes are visible. 390 * 391 * @param name class loader name; or {@code null} if not named 392 * @param parent the parent class loader 393 * 394 * @throws IllegalArgumentException if the given name is empty. 395 * 396 * @throws SecurityException 397 * If a security manager exists and its 398 * {@link SecurityManager#checkCreateClassLoader()} 399 * method doesn't allow creation of a new class loader. 400 * 401 * @since 9 402 * @spec JPMS 403 */ 404 protected ClassLoader(String name, ClassLoader parent) { 405 this(checkCreateClassLoader(name), name, parent); 406 } 407 408 /** 409 * Creates a new class loader using the specified parent class loader for 410 * delegation. 411 * 412 * <p> If there is a security manager, its {@link 413 * SecurityManager#checkCreateClassLoader() checkCreateClassLoader} method 414 * is invoked. This may result in a security exception. </p> 415 * 416 * @apiNote If the parent is specified as {@code null} (for the 417 * bootstrap class loader) then there is no guarantee that all platform 418 * classes are visible. 419 * 420 * @param parent 421 * The parent class loader 422 * 423 * @throws SecurityException 424 * If a security manager exists and its 425 * {@code checkCreateClassLoader} method doesn't allow creation 426 * of a new class loader. 427 * 428 * @since 1.2 429 */ 430 protected ClassLoader(ClassLoader parent) { 431 this(checkCreateClassLoader(), null, parent); 432 } 433 434 /** 435 * Creates a new class loader using the {@code ClassLoader} returned by 436 * the method {@link #getSystemClassLoader() 437 * getSystemClassLoader()} as the parent class loader. 438 * 439 * <p> If there is a security manager, its {@link 440 * SecurityManager#checkCreateClassLoader() 441 * checkCreateClassLoader} method is invoked. This may result in 442 * a security exception. </p> 443 * 444 * @throws SecurityException 445 * If a security manager exists and its 446 * {@code checkCreateClassLoader} method doesn't allow creation 447 * of a new class loader. 448 */ 449 protected ClassLoader() { 450 this(checkCreateClassLoader(), null, getSystemClassLoader()); 451 } 452 453 /** 454 * Returns the name of this class loader or {@code null} if 455 * this class loader is not named. 456 * 457 * @apiNote This method is non-final for compatibility. If this 458 * method is overridden, this method must return the same name 459 * as specified when this class loader was instantiated. 460 * 461 * @return name of this class loader; or {@code null} if 462 * this class loader is not named. 463 * 464 * @since 9 465 * @spec JPMS 466 */ 467 public String getName() { 468 return name; 469 } 470 471 // package-private used by StackTraceElement to avoid 472 // calling the overrideable getName method 473 final String name() { 474 return name; 475 } 476 477 // -- Class -- 478 479 /** 480 * Loads the class with the specified <a href="#name">binary name</a>. 481 * This method searches for classes in the same manner as the {@link 482 * #loadClass(String, boolean)} method. It is invoked by the Java virtual 483 * machine to resolve class references. Invoking this method is equivalent 484 * to invoking {@link #loadClass(String, boolean) loadClass(name, 485 * false)}. 486 * 487 * @param name 488 * The <a href="#name">binary name</a> of the class 489 * 490 * @return The resulting {@code Class} object 491 * 492 * @throws ClassNotFoundException 493 * If the class was not found 494 */ 495 public Class<?> loadClass(String name) throws ClassNotFoundException { 496 return loadClass(name, false); 497 } 498 499 /** 500 * Loads the class with the specified <a href="#name">binary name</a>. The 501 * default implementation of this method searches for classes in the 502 * following order: 503 * 504 * <ol> 505 * 506 * <li><p> Invoke {@link #findLoadedClass(String)} to check if the class 507 * has already been loaded. </p></li> 508 * 509 * <li><p> Invoke the {@link #loadClass(String) loadClass} method 510 * on the parent class loader. If the parent is {@code null} the class 511 * loader built into the virtual machine is used, instead. </p></li> 512 * 513 * <li><p> Invoke the {@link #findClass(String)} method to find the 514 * class. </p></li> 515 * 516 * </ol> 517 * 518 * <p> If the class was found using the above steps, and the 519 * {@code resolve} flag is true, this method will then invoke the {@link 520 * #resolveClass(Class)} method on the resulting {@code Class} object. 521 * 522 * <p> Subclasses of {@code ClassLoader} are encouraged to override {@link 523 * #findClass(String)}, rather than this method. </p> 524 * 525 * <p> Unless overridden, this method synchronizes on the result of 526 * {@link #getClassLoadingLock getClassLoadingLock} method 527 * during the entire class loading process. 528 * 529 * @param name 530 * The <a href="#name">binary name</a> of the class 531 * 532 * @param resolve 533 * If {@code true} then resolve the class 534 * 535 * @return The resulting {@code Class} object 536 * 537 * @throws ClassNotFoundException 538 * If the class could not be found 539 */ 540 protected Class<?> loadClass(String name, boolean resolve) 541 throws ClassNotFoundException 542 { 543 synchronized (getClassLoadingLock(name)) { 544 // First, check if the class has already been loaded 545 Class<?> c = findLoadedClass(name); 546 if (c == null) { 547 long t0 = System.nanoTime(); 548 try { 549 if (parent != null) { 550 c = parent.loadClass(name, false); 551 } else { 552 c = findBootstrapClassOrNull(name); 553 } 554 } catch (ClassNotFoundException e) { 555 // ClassNotFoundException thrown if class not found 556 // from the non-null parent class loader 557 } 558 559 if (c == null) { 560 // If still not found, then invoke findClass in order 561 // to find the class. 562 long t1 = System.nanoTime(); 563 c = findClass(name); 564 565 // this is the defining class loader; record the stats 566 PerfCounter.getParentDelegationTime().addTime(t1 - t0); 567 PerfCounter.getFindClassTime().addElapsedTimeFrom(t1); 568 PerfCounter.getFindClasses().increment(); 569 } 570 } 571 if (resolve) { 572 resolveClass(c); 573 } 574 return c; 575 } 576 } 577 578 /** 579 * Loads the class with the specified <a href="#name">binary name</a> 580 * in a module defined to this class loader. This method returns {@code null} 581 * if the class could not be found. 582 * 583 * @apiNote This method does not delegate to the parent class loader. 584 * 585 * @implSpec The default implementation of this method searches for classes 586 * in the following order: 587 * 588 * <ol> 589 * <li>Invoke {@link #findLoadedClass(String)} to check if the class 590 * has already been loaded.</li> 591 * <li>Invoke the {@link #findClass(String, String)} method to find the 592 * class in the given module.</li> 593 * </ol> 594 * 595 * @param module 596 * The module 597 * @param name 598 * The <a href="#name">binary name</a> of the class 599 * 600 * @return The resulting {@code Class} object in a module defined by 601 * this class loader, or {@code null} if the class could not be found. 602 */ 603 final Class<?> loadClass(Module module, String name) { 604 synchronized (getClassLoadingLock(name)) { 605 // First, check if the class has already been loaded 606 Class<?> c = findLoadedClass(name); 607 if (c == null) { 608 c = findClass(module.getName(), name); 609 } 610 if (c != null && c.getModule() == module) { 611 return c; 612 } else { 613 return null; 614 } 615 } 616 } 617 618 /** 619 * Returns the lock object for class loading operations. 620 * For backward compatibility, the default implementation of this method 621 * behaves as follows. If this ClassLoader object is registered as 622 * parallel capable, the method returns a dedicated object associated 623 * with the specified class name. Otherwise, the method returns this 624 * ClassLoader object. 625 * 626 * @param className 627 * The name of the to-be-loaded class 628 * 629 * @return the lock for class loading operations 630 * 631 * @throws NullPointerException 632 * If registered as parallel capable and {@code className} is null 633 * 634 * @see #loadClass(String, boolean) 635 * 636 * @since 1.7 637 */ 638 protected Object getClassLoadingLock(String className) { 639 Object lock = this; 640 if (parallelLockMap != null) { 641 Object newLock = new Object(); 642 lock = parallelLockMap.putIfAbsent(className, newLock); 643 if (lock == null) { 644 lock = newLock; 645 } 646 } 647 return lock; 648 } 649 650 // This method is invoked by the virtual machine to load a class. 651 private Class<?> loadClassInternal(String name) 652 throws ClassNotFoundException 653 { 654 // For backward compatibility, explicitly lock on 'this' when 655 // the current class loader is not parallel capable. 656 if (parallelLockMap == null) { 657 synchronized (this) { 658 return loadClass(name); 659 } 660 } else { 661 return loadClass(name); 662 } 663 } 664 665 // Invoked by the VM after loading class with this loader. 666 private void checkPackageAccess(Class<?> cls, ProtectionDomain pd) { 667 final SecurityManager sm = System.getSecurityManager(); 668 if (sm != null) { 669 if (ReflectUtil.isNonPublicProxyClass(cls)) { 670 for (Class<?> intf: cls.getInterfaces()) { 671 checkPackageAccess(intf, pd); 672 } 673 return; 674 } 675 676 final String name = cls.getName(); 677 final int i = name.lastIndexOf('.'); 678 if (i != -1) { 679 AccessController.doPrivileged(new PrivilegedAction<>() { 680 public Void run() { 681 sm.checkPackageAccess(name.substring(0, i)); 682 return null; 683 } 684 }, new AccessControlContext(new ProtectionDomain[] {pd})); 685 } 686 } 687 } 688 689 /** 690 * Finds the class with the specified <a href="#name">binary name</a>. 691 * This method should be overridden by class loader implementations that 692 * follow the delegation model for loading classes, and will be invoked by 693 * the {@link #loadClass loadClass} method after checking the 694 * parent class loader for the requested class. 695 * 696 * @implSpec The default implementation throws {@code ClassNotFoundException}. 697 * 698 * @param name 699 * The <a href="#name">binary name</a> of the class 700 * 701 * @return The resulting {@code Class} object 702 * 703 * @throws ClassNotFoundException 704 * If the class could not be found 705 * 706 * @since 1.2 707 */ 708 protected Class<?> findClass(String name) throws ClassNotFoundException { 709 throw new ClassNotFoundException(name); 710 } 711 712 /** 713 * Finds the class with the given <a href="#name">binary name</a> 714 * in a module defined to this class loader. 715 * Class loader implementations that support the loading from modules 716 * should override this method. 717 * 718 * @apiNote This method returns {@code null} rather than throwing 719 * {@code ClassNotFoundException} if the class could not be found. 720 * 721 * @implSpec The default implementation attempts to find the class by 722 * invoking {@link #findClass(String)} when the {@code moduleName} is 723 * {@code null}. It otherwise returns {@code null}. 724 * 725 * @param moduleName 726 * The module name; or {@code null} to find the class in the 727 * {@linkplain #getUnnamedModule() unnamed module} for this 728 * class loader 729 730 * @param name 731 * The <a href="#name">binary name</a> of the class 732 * 733 * @return The resulting {@code Class} object, or {@code null} 734 * if the class could not be found. 735 * 736 * @since 9 737 * @spec JPMS 738 */ 739 protected Class<?> findClass(String moduleName, String name) { 740 if (moduleName == null) { 741 try { 742 return findClass(name); 743 } catch (ClassNotFoundException ignore) { } 744 } 745 return null; 746 } 747 748 749 /** 750 * Converts an array of bytes into an instance of class {@code Class}. 751 * Before the {@code Class} can be used it must be resolved. This method 752 * is deprecated in favor of the version that takes a <a 753 * href="#name">binary name</a> as its first argument, and is more secure. 754 * 755 * @param b 756 * The bytes that make up the class data. The bytes in positions 757 * {@code off} through {@code off+len-1} should have the format 758 * of a valid class file as defined by 759 * <cite>The Java™ Virtual Machine Specification</cite>. 760 * 761 * @param off 762 * The start offset in {@code b} of the class data 763 * 764 * @param len 765 * The length of the class data 766 * 767 * @return The {@code Class} object that was created from the specified 768 * class data 769 * 770 * @throws ClassFormatError 771 * If the data did not contain a valid class 772 * 773 * @throws IndexOutOfBoundsException 774 * If either {@code off} or {@code len} is negative, or if 775 * {@code off+len} is greater than {@code b.length}. 776 * 777 * @throws SecurityException 778 * If an attempt is made to add this class to a package that 779 * contains classes that were signed by a different set of 780 * certificates than this class, or if an attempt is made 781 * to define a class in a package with a fully-qualified name 782 * that starts with "{@code java.}". 783 * 784 * @see #loadClass(String, boolean) 785 * @see #resolveClass(Class) 786 * 787 * @deprecated Replaced by {@link #defineClass(String, byte[], int, int) 788 * defineClass(String, byte[], int, int)} 789 */ 790 @Deprecated(since="1.1") 791 protected final Class<?> defineClass(byte[] b, int off, int len) 792 throws ClassFormatError 793 { 794 return defineClass(null, b, off, len, null); 795 } 796 797 /** 798 * Converts an array of bytes into an instance of class {@code Class}. 799 * Before the {@code Class} can be used it must be resolved. 800 * 801 * <p> This method assigns a default {@link java.security.ProtectionDomain 802 * ProtectionDomain} to the newly defined class. The 803 * {@code ProtectionDomain} is effectively granted the same set of 804 * permissions returned when {@link 805 * java.security.Policy#getPermissions(java.security.CodeSource) 806 * Policy.getPolicy().getPermissions(new CodeSource(null, null))} 807 * is invoked. The default protection domain is created on the first invocation 808 * of {@link #defineClass(String, byte[], int, int) defineClass}, 809 * and re-used on subsequent invocations. 810 * 811 * <p> To assign a specific {@code ProtectionDomain} to the class, use 812 * the {@link #defineClass(String, byte[], int, int, 813 * java.security.ProtectionDomain) defineClass} method that takes a 814 * {@code ProtectionDomain} as one of its arguments. </p> 815 * 816 * <p> 817 * This method defines a package in this class loader corresponding to the 818 * package of the {@code Class} (if such a package has not already been defined 819 * in this class loader). The name of the defined package is derived from 820 * the <a href="#name">binary name</a> of the class specified by 821 * the byte array {@code b}. 822 * Other properties of the defined package are as specified by {@link Package}. 823 * 824 * @param name 825 * The expected <a href="#name">binary name</a> of the class, or 826 * {@code null} if not known 827 * 828 * @param b 829 * The bytes that make up the class data. The bytes in positions 830 * {@code off} through {@code off+len-1} should have the format 831 * of a valid class file as defined by 832 * <cite>The Java™ Virtual Machine Specification</cite>. 833 * 834 * @param off 835 * The start offset in {@code b} of the class data 836 * 837 * @param len 838 * The length of the class data 839 * 840 * @return The {@code Class} object that was created from the specified 841 * class data. 842 * 843 * @throws ClassFormatError 844 * If the data did not contain a valid class 845 * 846 * @throws IndexOutOfBoundsException 847 * If either {@code off} or {@code len} is negative, or if 848 * {@code off+len} is greater than {@code b.length}. 849 * 850 * @throws SecurityException 851 * If an attempt is made to add this class to a package that 852 * contains classes that were signed by a different set of 853 * certificates than this class (which is unsigned), or if 854 * {@code name} begins with "{@code java.}". 855 * 856 * @see #loadClass(String, boolean) 857 * @see #resolveClass(Class) 858 * @see java.security.CodeSource 859 * @see java.security.SecureClassLoader 860 * 861 * @since 1.1 862 * @revised 9 863 * @spec JPMS 864 */ 865 protected final Class<?> defineClass(String name, byte[] b, int off, int len) 866 throws ClassFormatError 867 { 868 return defineClass(name, b, off, len, null); 869 } 870 871 /* Determine protection domain, and check that: 872 - not define java.* class, 873 - signer of this class matches signers for the rest of the classes in 874 package. 875 */ 876 private ProtectionDomain preDefineClass(String name, 877 ProtectionDomain pd) 878 { 879 if (!checkName(name)) 880 throw new NoClassDefFoundError("IllegalName: " + name); 881 882 // Note: Checking logic in java.lang.invoke.MemberName.checkForTypeAlias 883 // relies on the fact that spoofing is impossible if a class has a name 884 // of the form "java.*" 885 if ((name != null) && name.startsWith("java.") 886 && this != getBuiltinPlatformClassLoader()) { 887 throw new SecurityException 888 ("Prohibited package name: " + 889 name.substring(0, name.lastIndexOf('.'))); 890 } 891 if (pd == null) { 892 pd = defaultDomain; 893 } 894 895 if (name != null) { 896 checkCerts(name, pd.getCodeSource()); 897 } 898 899 return pd; 900 } 901 902 private String defineClassSourceLocation(ProtectionDomain pd) { 903 CodeSource cs = pd.getCodeSource(); 904 String source = null; 905 if (cs != null && cs.getLocation() != null) { 906 source = cs.getLocation().toString(); 907 } 908 return source; 909 } 910 911 private void postDefineClass(Class<?> c, ProtectionDomain pd) { 912 // define a named package, if not present 913 getNamedPackage(c.getPackageName(), c.getModule()); 914 915 if (pd.getCodeSource() != null) { 916 Certificate certs[] = pd.getCodeSource().getCertificates(); 917 if (certs != null) 918 setSigners(c, certs); 919 } 920 } 921 922 /** 923 * Converts an array of bytes into an instance of class {@code Class}, 924 * with a given {@code ProtectionDomain}. 925 * 926 * <p> If the given {@code ProtectionDomain} is {@code null}, 927 * then a default protection domain will be assigned to the class as specified 928 * in the documentation for {@link #defineClass(String, byte[], int, int)}. 929 * Before the class can be used it must be resolved. 930 * 931 * <p> The first class defined in a package determines the exact set of 932 * certificates that all subsequent classes defined in that package must 933 * contain. The set of certificates for a class is obtained from the 934 * {@link java.security.CodeSource CodeSource} within the 935 * {@code ProtectionDomain} of the class. Any classes added to that 936 * package must contain the same set of certificates or a 937 * {@code SecurityException} will be thrown. Note that if 938 * {@code name} is {@code null}, this check is not performed. 939 * You should always pass in the <a href="#name">binary name</a> of the 940 * class you are defining as well as the bytes. This ensures that the 941 * class you are defining is indeed the class you think it is. 942 * 943 * <p> If the specified {@code name} begins with "{@code java.}", it can 944 * only be defined by the {@linkplain #getPlatformClassLoader() 945 * platform class loader} or its ancestors; otherwise {@code SecurityException} 946 * will be thrown. If {@code name} is not {@code null}, it must be equal to 947 * the <a href="#name">binary name</a> of the class 948 * specified by the byte array {@code b}, otherwise a {@link 949 * NoClassDefFoundError NoClassDefFoundError} will be thrown. 950 * 951 * <p> This method defines a package in this class loader corresponding to the 952 * package of the {@code Class} (if such a package has not already been defined 953 * in this class loader). The name of the defined package is derived from 954 * the <a href="#name">binary name</a> of the class specified by 955 * the byte array {@code b}. 956 * Other properties of the defined package are as specified by {@link Package}. 957 * 958 * @param name 959 * The expected <a href="#name">binary name</a> of the class, or 960 * {@code null} if not known 961 * 962 * @param b 963 * The bytes that make up the class data. The bytes in positions 964 * {@code off} through {@code off+len-1} should have the format 965 * of a valid class file as defined by 966 * <cite>The Java™ Virtual Machine Specification</cite>. 967 * 968 * @param off 969 * The start offset in {@code b} of the class data 970 * 971 * @param len 972 * The length of the class data 973 * 974 * @param protectionDomain 975 * The {@code ProtectionDomain} of the class 976 * 977 * @return The {@code Class} object created from the data, 978 * and {@code ProtectionDomain}. 979 * 980 * @throws ClassFormatError 981 * If the data did not contain a valid class 982 * 983 * @throws NoClassDefFoundError 984 * If {@code name} is not {@code null} and not equal to the 985 * <a href="#name">binary name</a> of the class specified by {@code b} 986 * 987 * @throws IndexOutOfBoundsException 988 * If either {@code off} or {@code len} is negative, or if 989 * {@code off+len} is greater than {@code b.length}. 990 * 991 * @throws SecurityException 992 * If an attempt is made to add this class to a package that 993 * contains classes that were signed by a different set of 994 * certificates than this class, or if {@code name} begins with 995 * "{@code java.}" and this class loader is not the platform 996 * class loader or its ancestor. 997 * 998 * @revised 9 999 * @spec JPMS 1000 */ 1001 protected final Class<?> defineClass(String name, byte[] b, int off, int len, 1002 ProtectionDomain protectionDomain) 1003 throws ClassFormatError 1004 { 1005 protectionDomain = preDefineClass(name, protectionDomain); 1006 String source = defineClassSourceLocation(protectionDomain); 1007 Class<?> c = defineClass1(this, name, b, off, len, protectionDomain, source); 1008 postDefineClass(c, protectionDomain); 1009 return c; 1010 } 1011 1012 /** 1013 * Converts a {@link java.nio.ByteBuffer ByteBuffer} into an instance 1014 * of class {@code Class}, with the given {@code ProtectionDomain}. 1015 * If the given {@code ProtectionDomain} is {@code null}, then a default 1016 * protection domain will be assigned to the class as 1017 * specified in the documentation for {@link #defineClass(String, byte[], 1018 * int, int)}. Before the class can be used it must be resolved. 1019 * 1020 * <p>The rules about the first class defined in a package determining the 1021 * set of certificates for the package, the restrictions on class names, 1022 * and the defined package of the class 1023 * are identical to those specified in the documentation for {@link 1024 * #defineClass(String, byte[], int, int, ProtectionDomain)}. 1025 * 1026 * <p> An invocation of this method of the form 1027 * <i>cl</i>{@code .defineClass(}<i>name</i>{@code ,} 1028 * <i>bBuffer</i>{@code ,} <i>pd</i>{@code )} yields exactly the same 1029 * result as the statements 1030 * 1031 *<p> <code> 1032 * ...<br> 1033 * byte[] temp = new byte[bBuffer.{@link 1034 * java.nio.ByteBuffer#remaining remaining}()];<br> 1035 * bBuffer.{@link java.nio.ByteBuffer#get(byte[]) 1036 * get}(temp);<br> 1037 * return {@link #defineClass(String, byte[], int, int, ProtectionDomain) 1038 * cl.defineClass}(name, temp, 0, 1039 * temp.length, pd);<br> 1040 * </code></p> 1041 * 1042 * @param name 1043 * The expected <a href="#name">binary name</a>. of the class, or 1044 * {@code null} if not known 1045 * 1046 * @param b 1047 * The bytes that make up the class data. The bytes from positions 1048 * {@code b.position()} through {@code b.position() + b.limit() -1 1049 * } should have the format of a valid class file as defined by 1050 * <cite>The Java™ Virtual Machine Specification</cite>. 1051 * 1052 * @param protectionDomain 1053 * The {@code ProtectionDomain} of the class, or {@code null}. 1054 * 1055 * @return The {@code Class} object created from the data, 1056 * and {@code ProtectionDomain}. 1057 * 1058 * @throws ClassFormatError 1059 * If the data did not contain a valid class. 1060 * 1061 * @throws NoClassDefFoundError 1062 * If {@code name} is not {@code null} and not equal to the 1063 * <a href="#name">binary name</a> of the class specified by {@code b} 1064 * 1065 * @throws SecurityException 1066 * If an attempt is made to add this class to a package that 1067 * contains classes that were signed by a different set of 1068 * certificates than this class, or if {@code name} begins with 1069 * "{@code java.}". 1070 * 1071 * @see #defineClass(String, byte[], int, int, ProtectionDomain) 1072 * 1073 * @since 1.5 1074 * @revised 9 1075 * @spec JPMS 1076 */ 1077 protected final Class<?> defineClass(String name, java.nio.ByteBuffer b, 1078 ProtectionDomain protectionDomain) 1079 throws ClassFormatError 1080 { 1081 int len = b.remaining(); 1082 1083 // Use byte[] if not a direct ByteBuffer: 1084 if (!b.isDirect()) { 1085 if (b.hasArray()) { 1086 return defineClass(name, b.array(), 1087 b.position() + b.arrayOffset(), len, 1088 protectionDomain); 1089 } else { 1090 // no array, or read-only array 1091 byte[] tb = new byte[len]; 1092 b.get(tb); // get bytes out of byte buffer. 1093 return defineClass(name, tb, 0, len, protectionDomain); 1094 } 1095 } 1096 1097 protectionDomain = preDefineClass(name, protectionDomain); 1098 String source = defineClassSourceLocation(protectionDomain); 1099 Class<?> c = defineClass2(this, name, b, b.position(), len, protectionDomain, source); 1100 postDefineClass(c, protectionDomain); 1101 return c; 1102 } 1103 1104 static native Class<?> defineClass1(ClassLoader loader, String name, byte[] b, int off, int len, 1105 ProtectionDomain pd, String source); 1106 1107 static native Class<?> defineClass2(ClassLoader loader, String name, java.nio.ByteBuffer b, 1108 int off, int len, ProtectionDomain pd, 1109 String source); 1110 1111 // true if the name is null or has the potential to be a valid binary name 1112 private boolean checkName(String name) { 1113 if ((name == null) || (name.length() == 0)) 1114 return true; 1115 if ((name.indexOf('/') != -1) || (name.charAt(0) == '[')) 1116 return false; 1117 return true; 1118 } 1119 1120 private void checkCerts(String name, CodeSource cs) { 1121 int i = name.lastIndexOf('.'); 1122 String pname = (i == -1) ? "" : name.substring(0, i); 1123 1124 Certificate[] certs = null; 1125 if (cs != null) { 1126 certs = cs.getCertificates(); 1127 } 1128 Certificate[] pcerts = null; 1129 if (parallelLockMap == null) { 1130 synchronized (this) { 1131 pcerts = package2certs.get(pname); 1132 if (pcerts == null) { 1133 package2certs.put(pname, (certs == null? nocerts:certs)); 1134 } 1135 } 1136 } else { 1137 pcerts = ((ConcurrentHashMap<String, Certificate[]>)package2certs). 1138 putIfAbsent(pname, (certs == null? nocerts:certs)); 1139 } 1140 if (pcerts != null && !compareCerts(pcerts, certs)) { 1141 throw new SecurityException("class \"" + name 1142 + "\"'s signer information does not match signer information" 1143 + " of other classes in the same package"); 1144 } 1145 } 1146 1147 /** 1148 * check to make sure the certs for the new class (certs) are the same as 1149 * the certs for the first class inserted in the package (pcerts) 1150 */ 1151 private boolean compareCerts(Certificate[] pcerts, 1152 Certificate[] certs) 1153 { 1154 // certs can be null, indicating no certs. 1155 if ((certs == null) || (certs.length == 0)) { 1156 return pcerts.length == 0; 1157 } 1158 1159 // the length must be the same at this point 1160 if (certs.length != pcerts.length) 1161 return false; 1162 1163 // go through and make sure all the certs in one array 1164 // are in the other and vice-versa. 1165 boolean match; 1166 for (Certificate cert : certs) { 1167 match = false; 1168 for (Certificate pcert : pcerts) { 1169 if (cert.equals(pcert)) { 1170 match = true; 1171 break; 1172 } 1173 } 1174 if (!match) return false; 1175 } 1176 1177 // now do the same for pcerts 1178 for (Certificate pcert : pcerts) { 1179 match = false; 1180 for (Certificate cert : certs) { 1181 if (pcert.equals(cert)) { 1182 match = true; 1183 break; 1184 } 1185 } 1186 if (!match) return false; 1187 } 1188 1189 return true; 1190 } 1191 1192 /** 1193 * Links the specified class. This (misleadingly named) method may be 1194 * used by a class loader to link a class. If the class {@code c} has 1195 * already been linked, then this method simply returns. Otherwise, the 1196 * class is linked as described in the "Execution" chapter of 1197 * <cite>The Java™ Language Specification</cite>. 1198 * 1199 * @param c 1200 * The class to link 1201 * 1202 * @throws NullPointerException 1203 * If {@code c} is {@code null}. 1204 * 1205 * @see #defineClass(String, byte[], int, int) 1206 */ 1207 protected final void resolveClass(Class<?> c) { 1208 if (c == null) { 1209 throw new NullPointerException(); 1210 } 1211 } 1212 1213 /** 1214 * Finds a class with the specified <a href="#name">binary name</a>, 1215 * loading it if necessary. 1216 * 1217 * <p> This method loads the class through the system class loader (see 1218 * {@link #getSystemClassLoader()}). The {@code Class} object returned 1219 * might have more than one {@code ClassLoader} associated with it. 1220 * Subclasses of {@code ClassLoader} need not usually invoke this method, 1221 * because most class loaders need to override just {@link 1222 * #findClass(String)}. </p> 1223 * 1224 * @param name 1225 * The <a href="#name">binary name</a> of the class 1226 * 1227 * @return The {@code Class} object for the specified {@code name} 1228 * 1229 * @throws ClassNotFoundException 1230 * If the class could not be found 1231 * 1232 * @see #ClassLoader(ClassLoader) 1233 * @see #getParent() 1234 */ 1235 protected final Class<?> findSystemClass(String name) 1236 throws ClassNotFoundException 1237 { 1238 return getSystemClassLoader().loadClass(name); 1239 } 1240 1241 /** 1242 * Returns a class loaded by the bootstrap class loader; 1243 * or return null if not found. 1244 */ 1245 Class<?> findBootstrapClassOrNull(String name) { 1246 if (!checkName(name)) return null; 1247 1248 return findBootstrapClass(name); 1249 } 1250 1251 // return null if not found 1252 private native Class<?> findBootstrapClass(String name); 1253 1254 /** 1255 * Returns the class with the given <a href="#name">binary name</a> if this 1256 * loader has been recorded by the Java virtual machine as an initiating 1257 * loader of a class with that <a href="#name">binary name</a>. Otherwise 1258 * {@code null} is returned. 1259 * 1260 * @param name 1261 * The <a href="#name">binary name</a> of the class 1262 * 1263 * @return The {@code Class} object, or {@code null} if the class has 1264 * not been loaded 1265 * 1266 * @since 1.1 1267 */ 1268 protected final Class<?> findLoadedClass(String name) { 1269 if (!checkName(name)) 1270 return null; 1271 return findLoadedClass0(name); 1272 } 1273 1274 private final native Class<?> findLoadedClass0(String name); 1275 1276 /** 1277 * Sets the signers of a class. This should be invoked after defining a 1278 * class. 1279 * 1280 * @param c 1281 * The {@code Class} object 1282 * 1283 * @param signers 1284 * The signers for the class 1285 * 1286 * @since 1.1 1287 */ 1288 protected final void setSigners(Class<?> c, Object[] signers) { 1289 c.setSigners(signers); 1290 } 1291 1292 1293 // -- Resources -- 1294 1295 /** 1296 * Returns a URL to a resource in a module defined to this class loader. 1297 * Class loader implementations that support the loading from modules 1298 * should override this method. 1299 * 1300 * @apiNote This method is the basis for the {@link 1301 * Class#getResource Class.getResource}, {@link Class#getResourceAsStream 1302 * Class.getResourceAsStream}, and {@link Module#getResourceAsStream 1303 * Module.getResourceAsStream} methods. It is not subject to the rules for 1304 * encapsulation specified by {@code Module.getResourceAsStream}. 1305 * 1306 * @implSpec The default implementation attempts to find the resource by 1307 * invoking {@link #findResource(String)} when the {@code moduleName} is 1308 * {@code null}. It otherwise returns {@code null}. 1309 * 1310 * @param moduleName 1311 * The module name; or {@code null} to find a resource in the 1312 * {@linkplain #getUnnamedModule() unnamed module} for this 1313 * class loader 1314 * @param name 1315 * The resource name 1316 * 1317 * @return A URL to the resource; {@code null} if the resource could not be 1318 * found, a URL could not be constructed to locate the resource, 1319 * access to the resource is denied by the security manager, or 1320 * there isn't a module of the given name defined to the class 1321 * loader. 1322 * 1323 * @throws IOException 1324 * If I/O errors occur 1325 * 1326 * @see java.lang.module.ModuleReader#find(String) 1327 * @since 9 1328 * @spec JPMS 1329 */ 1330 protected URL findResource(String moduleName, String name) throws IOException { 1331 if (moduleName == null) { 1332 return findResource(name); 1333 } else { 1334 return null; 1335 } 1336 } 1337 1338 /** 1339 * Finds the resource with the given name. A resource is some data 1340 * (images, audio, text, etc) that can be accessed by class code in a way 1341 * that is independent of the location of the code. 1342 * 1343 * <p> The name of a resource is a '{@code /}'-separated path name that 1344 * identifies the resource. </p> 1345 * 1346 * <p> Resources in named modules are subject to the encapsulation rules 1347 * specified by {@link Module#getResourceAsStream Module.getResourceAsStream}. 1348 * Additionally, and except for the special case where the resource has a 1349 * name ending with "{@code .class}", this method will only find resources in 1350 * packages of named modules when the package is {@link Module#isOpen(String) 1351 * opened} unconditionally (even if the caller of this method is in the 1352 * same module as the resource). </p> 1353 * 1354 * @implSpec The default implementation will first search the parent class 1355 * loader for the resource; if the parent is {@code null} the path of the 1356 * class loader built into the virtual machine is searched. If not found, 1357 * this method will invoke {@link #findResource(String)} to find the resource. 1358 * 1359 * @apiNote Where several modules are defined to the same class loader, 1360 * and where more than one module contains a resource with the given name, 1361 * then the ordering that modules are searched is not specified and may be 1362 * very unpredictable. 1363 * When overriding this method it is recommended that an implementation 1364 * ensures that any delegation is consistent with the {@link 1365 * #getResources(java.lang.String) getResources(String)} method. 1366 * 1367 * @param name 1368 * The resource name 1369 * 1370 * @return {@code URL} object for reading the resource; {@code null} if 1371 * the resource could not be found, a {@code URL} could not be 1372 * constructed to locate the resource, the resource is in a package 1373 * that is not opened unconditionally, or access to the resource is 1374 * denied by the security manager. 1375 * 1376 * @throws NullPointerException If {@code name} is {@code null} 1377 * 1378 * @since 1.1 1379 * @revised 9 1380 * @spec JPMS 1381 */ 1382 public URL getResource(String name) { 1383 Objects.requireNonNull(name); 1384 URL url; 1385 if (parent != null) { 1386 url = parent.getResource(name); 1387 } else { 1388 url = BootLoader.findResource(name); 1389 } 1390 if (url == null) { 1391 url = findResource(name); 1392 } 1393 return url; 1394 } 1395 1396 /** 1397 * Finds all the resources with the given name. A resource is some data 1398 * (images, audio, text, etc) that can be accessed by class code in a way 1399 * that is independent of the location of the code. 1400 * 1401 * <p> The name of a resource is a {@code /}-separated path name that 1402 * identifies the resource. </p> 1403 * 1404 * <p> Resources in named modules are subject to the encapsulation rules 1405 * specified by {@link Module#getResourceAsStream Module.getResourceAsStream}. 1406 * Additionally, and except for the special case where the resource has a 1407 * name ending with "{@code .class}", this method will only find resources in 1408 * packages of named modules when the package is {@link Module#isOpen(String) 1409 * opened} unconditionally (even if the caller of this method is in the 1410 * same module as the resource). </p> 1411 * 1412 * @implSpec The default implementation will first search the parent class 1413 * loader for the resource; if the parent is {@code null} the path of the 1414 * class loader built into the virtual machine is searched. It then 1415 * invokes {@link #findResources(String)} to find the resources with the 1416 * name in this class loader. It returns an enumeration whose elements 1417 * are the URLs found by searching the parent class loader followed by 1418 * the elements found with {@code findResources}. 1419 * 1420 * @apiNote Where several modules are defined to the same class loader, 1421 * and where more than one module contains a resource with the given name, 1422 * then the ordering is not specified and may be very unpredictable. 1423 * When overriding this method it is recommended that an 1424 * implementation ensures that any delegation is consistent with the {@link 1425 * #getResource(java.lang.String) getResource(String)} method. This should 1426 * ensure that the first element returned by the Enumeration's 1427 * {@code nextElement} method is the same resource that the 1428 * {@code getResource(String)} method would return. 1429 * 1430 * @param name 1431 * The resource name 1432 * 1433 * @return An enumeration of {@link java.net.URL URL} objects for 1434 * the resource. If no resources could be found, the enumeration 1435 * will be empty. Resources for which a {@code URL} cannot be 1436 * constructed, are in package that is not opened unconditionally, 1437 * or access to the resource is denied by the security manager, 1438 * are not returned in the enumeration. 1439 * 1440 * @throws IOException 1441 * If I/O errors occur 1442 * @throws NullPointerException If {@code name} is {@code null} 1443 * 1444 * @since 1.2 1445 * @revised 9 1446 * @spec JPMS 1447 */ 1448 public Enumeration<URL> getResources(String name) throws IOException { 1449 Objects.requireNonNull(name); 1450 @SuppressWarnings("unchecked") 1451 Enumeration<URL>[] tmp = (Enumeration<URL>[]) new Enumeration<?>[2]; 1452 if (parent != null) { 1453 tmp[0] = parent.getResources(name); 1454 } else { 1455 tmp[0] = BootLoader.findResources(name); 1456 } 1457 tmp[1] = findResources(name); 1458 1459 return new CompoundEnumeration<>(tmp); 1460 } 1461 1462 /** 1463 * Returns a stream whose elements are the URLs of all the resources with 1464 * the given name. A resource is some data (images, audio, text, etc) that 1465 * can be accessed by class code in a way that is independent of the 1466 * location of the code. 1467 * 1468 * <p> The name of a resource is a {@code /}-separated path name that 1469 * identifies the resource. 1470 * 1471 * <p> The resources will be located when the returned stream is evaluated. 1472 * If the evaluation results in an {@code IOException} then the I/O 1473 * exception is wrapped in an {@link UncheckedIOException} that is then 1474 * thrown. 1475 * 1476 * <p> Resources in named modules are subject to the encapsulation rules 1477 * specified by {@link Module#getResourceAsStream Module.getResourceAsStream}. 1478 * Additionally, and except for the special case where the resource has a 1479 * name ending with "{@code .class}", this method will only find resources in 1480 * packages of named modules when the package is {@link Module#isOpen(String) 1481 * opened} unconditionally (even if the caller of this method is in the 1482 * same module as the resource). </p> 1483 * 1484 * @implSpec The default implementation invokes {@link #getResources(String) 1485 * getResources} to find all the resources with the given name and returns 1486 * a stream with the elements in the enumeration as the source. 1487 * 1488 * @apiNote When overriding this method it is recommended that an 1489 * implementation ensures that any delegation is consistent with the {@link 1490 * #getResource(java.lang.String) getResource(String)} method. This should 1491 * ensure that the first element returned by the stream is the same 1492 * resource that the {@code getResource(String)} method would return. 1493 * 1494 * @param name 1495 * The resource name 1496 * 1497 * @return A stream of resource {@link java.net.URL URL} objects. If no 1498 * resources could be found, the stream will be empty. Resources 1499 * for which a {@code URL} cannot be constructed, are in a package 1500 * that is not opened unconditionally, or access to the resource 1501 * is denied by the security manager, will not be in the stream. 1502 * 1503 * @throws NullPointerException If {@code name} is {@code null} 1504 * 1505 * @since 9 1506 */ 1507 public Stream<URL> resources(String name) { 1508 Objects.requireNonNull(name); 1509 int characteristics = Spliterator.NONNULL | Spliterator.IMMUTABLE; 1510 Supplier<Spliterator<URL>> si = () -> { 1511 try { 1512 return Spliterators.spliteratorUnknownSize( 1513 getResources(name).asIterator(), characteristics); 1514 } catch (IOException e) { 1515 throw new UncheckedIOException(e); 1516 } 1517 }; 1518 return StreamSupport.stream(si, characteristics, false); 1519 } 1520 1521 /** 1522 * Finds the resource with the given name. Class loader implementations 1523 * should override this method. 1524 * 1525 * <p> For resources in named modules then the method must implement the 1526 * rules for encapsulation specified in the {@code Module} {@link 1527 * Module#getResourceAsStream getResourceAsStream} method. Additionally, 1528 * it must not find non-"{@code .class}" resources in packages of named 1529 * modules unless the package is {@link Module#isOpen(String) opened} 1530 * unconditionally. </p> 1531 * 1532 * @implSpec The default implementation returns {@code null}. 1533 * 1534 * @param name 1535 * The resource name 1536 * 1537 * @return {@code URL} object for reading the resource; {@code null} if 1538 * the resource could not be found, a {@code URL} could not be 1539 * constructed to locate the resource, the resource is in a package 1540 * that is not opened unconditionally, or access to the resource is 1541 * denied by the security manager. 1542 * 1543 * @since 1.2 1544 * @revised 9 1545 * @spec JPMS 1546 */ 1547 protected URL findResource(String name) { 1548 return null; 1549 } 1550 1551 /** 1552 * Returns an enumeration of {@link java.net.URL URL} objects 1553 * representing all the resources with the given name. Class loader 1554 * implementations should override this method. 1555 * 1556 * <p> For resources in named modules then the method must implement the 1557 * rules for encapsulation specified in the {@code Module} {@link 1558 * Module#getResourceAsStream getResourceAsStream} method. Additionally, 1559 * it must not find non-"{@code .class}" resources in packages of named 1560 * modules unless the package is {@link Module#isOpen(String) opened} 1561 * unconditionally. </p> 1562 * 1563 * @implSpec The default implementation returns an enumeration that 1564 * contains no elements. 1565 * 1566 * @param name 1567 * The resource name 1568 * 1569 * @return An enumeration of {@link java.net.URL URL} objects for 1570 * the resource. If no resources could be found, the enumeration 1571 * will be empty. Resources for which a {@code URL} cannot be 1572 * constructed, are in a package that is not opened unconditionally, 1573 * or access to the resource is denied by the security manager, 1574 * are not returned in the enumeration. 1575 * 1576 * @throws IOException 1577 * If I/O errors occur 1578 * 1579 * @since 1.2 1580 * @revised 9 1581 * @spec JPMS 1582 */ 1583 protected Enumeration<URL> findResources(String name) throws IOException { 1584 return Collections.emptyEnumeration(); 1585 } 1586 1587 /** 1588 * Registers the caller as 1589 * {@linkplain #isRegisteredAsParallelCapable() parallel capable}. 1590 * The registration succeeds if and only if all of the following 1591 * conditions are met: 1592 * <ol> 1593 * <li> no instance of the caller has been created</li> 1594 * <li> all of the super classes (except class Object) of the caller are 1595 * registered as parallel capable</li> 1596 * </ol> 1597 * <p>Note that once a class loader is registered as parallel capable, there 1598 * is no way to change it back.</p> 1599 * 1600 * @return {@code true} if the caller is successfully registered as 1601 * parallel capable and {@code false} if otherwise. 1602 * 1603 * @see #isRegisteredAsParallelCapable() 1604 * 1605 * @since 1.7 1606 */ 1607 @CallerSensitive 1608 protected static boolean registerAsParallelCapable() { 1609 Class<? extends ClassLoader> callerClass = 1610 Reflection.getCallerClass().asSubclass(ClassLoader.class); 1611 return ParallelLoaders.register(callerClass); 1612 } 1613 1614 /** 1615 * Returns {@code true} if this class loader is registered as 1616 * {@linkplain #registerAsParallelCapable parallel capable}, otherwise 1617 * {@code false}. 1618 * 1619 * @return {@code true} if this class loader is parallel capable, 1620 * otherwise {@code false}. 1621 * 1622 * @see #registerAsParallelCapable() 1623 * 1624 * @since 9 1625 */ 1626 public final boolean isRegisteredAsParallelCapable() { 1627 return ParallelLoaders.isRegistered(this.getClass()); 1628 } 1629 1630 /** 1631 * Find a resource of the specified name from the search path used to load 1632 * classes. This method locates the resource through the system class 1633 * loader (see {@link #getSystemClassLoader()}). 1634 * 1635 * <p> Resources in named modules are subject to the encapsulation rules 1636 * specified by {@link Module#getResourceAsStream Module.getResourceAsStream}. 1637 * Additionally, and except for the special case where the resource has a 1638 * name ending with "{@code .class}", this method will only find resources in 1639 * packages of named modules when the package is {@link Module#isOpen(String) 1640 * opened} unconditionally. </p> 1641 * 1642 * @param name 1643 * The resource name 1644 * 1645 * @return A {@link java.net.URL URL} to the resource; {@code 1646 * null} if the resource could not be found, a URL could not be 1647 * constructed to locate the resource, the resource is in a package 1648 * that is not opened unconditionally or access to the resource is 1649 * denied by the security manager. 1650 * 1651 * @since 1.1 1652 * @revised 9 1653 * @spec JPMS 1654 */ 1655 public static URL getSystemResource(String name) { 1656 return getSystemClassLoader().getResource(name); 1657 } 1658 1659 /** 1660 * Finds all resources of the specified name from the search path used to 1661 * load classes. The resources thus found are returned as an 1662 * {@link java.util.Enumeration Enumeration} of {@link 1663 * java.net.URL URL} objects. 1664 * 1665 * <p> The search order is described in the documentation for {@link 1666 * #getSystemResource(String)}. </p> 1667 * 1668 * <p> Resources in named modules are subject to the encapsulation rules 1669 * specified by {@link Module#getResourceAsStream Module.getResourceAsStream}. 1670 * Additionally, and except for the special case where the resource has a 1671 * name ending with "{@code .class}", this method will only find resources in 1672 * packages of named modules when the package is {@link Module#isOpen(String) 1673 * opened} unconditionally. </p> 1674 * 1675 * @param name 1676 * The resource name 1677 * 1678 * @return An enumeration of {@link java.net.URL URL} objects for 1679 * the resource. If no resources could be found, the enumeration 1680 * will be empty. Resources for which a {@code URL} cannot be 1681 * constructed, are in a package that is not opened unconditionally, 1682 * or access to the resource is denied by the security manager, 1683 * are not returned in the enumeration. 1684 * 1685 * @throws IOException 1686 * If I/O errors occur 1687 * 1688 * @since 1.2 1689 * @revised 9 1690 * @spec JPMS 1691 */ 1692 public static Enumeration<URL> getSystemResources(String name) 1693 throws IOException 1694 { 1695 return getSystemClassLoader().getResources(name); 1696 } 1697 1698 /** 1699 * Returns an input stream for reading the specified resource. 1700 * 1701 * <p> The search order is described in the documentation for {@link 1702 * #getResource(String)}. </p> 1703 * 1704 * <p> Resources in named modules are subject to the encapsulation rules 1705 * specified by {@link Module#getResourceAsStream Module.getResourceAsStream}. 1706 * Additionally, and except for the special case where the resource has a 1707 * name ending with "{@code .class}", this method will only find resources in 1708 * packages of named modules when the package is {@link Module#isOpen(String) 1709 * opened} unconditionally. </p> 1710 * 1711 * @param name 1712 * The resource name 1713 * 1714 * @return An input stream for reading the resource; {@code null} if the 1715 * resource could not be found, the resource is in a package that 1716 * is not opened unconditionally, or access to the resource is 1717 * denied by the security manager. 1718 * 1719 * @throws NullPointerException If {@code name} is {@code null} 1720 * 1721 * @since 1.1 1722 * @revised 9 1723 * @spec JPMS 1724 */ 1725 public InputStream getResourceAsStream(String name) { 1726 Objects.requireNonNull(name); 1727 URL url = getResource(name); 1728 try { 1729 return url != null ? url.openStream() : null; 1730 } catch (IOException e) { 1731 return null; 1732 } 1733 } 1734 1735 /** 1736 * Open for reading, a resource of the specified name from the search path 1737 * used to load classes. This method locates the resource through the 1738 * system class loader (see {@link #getSystemClassLoader()}). 1739 * 1740 * <p> Resources in named modules are subject to the encapsulation rules 1741 * specified by {@link Module#getResourceAsStream Module.getResourceAsStream}. 1742 * Additionally, and except for the special case where the resource has a 1743 * name ending with "{@code .class}", this method will only find resources in 1744 * packages of named modules when the package is {@link Module#isOpen(String) 1745 * opened} unconditionally. </p> 1746 * 1747 * @param name 1748 * The resource name 1749 * 1750 * @return An input stream for reading the resource; {@code null} if the 1751 * resource could not be found, the resource is in a package that 1752 * is not opened unconditionally, or access to the resource is 1753 * denied by the security manager. 1754 * 1755 * @since 1.1 1756 * @revised 9 1757 * @spec JPMS 1758 */ 1759 public static InputStream getSystemResourceAsStream(String name) { 1760 URL url = getSystemResource(name); 1761 try { 1762 return url != null ? url.openStream() : null; 1763 } catch (IOException e) { 1764 return null; 1765 } 1766 } 1767 1768 1769 // -- Hierarchy -- 1770 1771 /** 1772 * Returns the parent class loader for delegation. Some implementations may 1773 * use {@code null} to represent the bootstrap class loader. This method 1774 * will return {@code null} in such implementations if this class loader's 1775 * parent is the bootstrap class loader. 1776 * 1777 * @return The parent {@code ClassLoader} 1778 * 1779 * @throws SecurityException 1780 * If a security manager is present, and the caller's class loader 1781 * is not {@code null} and is not an ancestor of this class loader, 1782 * and the caller does not have the 1783 * {@link RuntimePermission}{@code ("getClassLoader")} 1784 * 1785 * @since 1.2 1786 */ 1787 @CallerSensitive 1788 public final ClassLoader getParent() { 1789 if (parent == null) 1790 return null; 1791 SecurityManager sm = System.getSecurityManager(); 1792 if (sm != null) { 1793 // Check access to the parent class loader 1794 // If the caller's class loader is same as this class loader, 1795 // permission check is performed. 1796 checkClassLoaderPermission(parent, Reflection.getCallerClass()); 1797 } 1798 return parent; 1799 } 1800 1801 /** 1802 * Returns the unnamed {@code Module} for this class loader. 1803 * 1804 * @return The unnamed Module for this class loader 1805 * 1806 * @see Module#isNamed() 1807 * @since 9 1808 * @spec JPMS 1809 */ 1810 public final Module getUnnamedModule() { 1811 return unnamedModule; 1812 } 1813 1814 /** 1815 * Returns the platform class loader for delegation. All 1816 * <a href="#builtinLoaders">platform classes</a> are visible to 1817 * the platform class loader. 1818 * 1819 * @implNote The name of the builtin platform class loader is 1820 * {@code "platform"}. 1821 * 1822 * @return The platform {@code ClassLoader}. 1823 * 1824 * @throws SecurityException 1825 * If a security manager is present, and the caller's class loader is 1826 * not {@code null}, and the caller's class loader is not the same 1827 * as or an ancestor of the platform class loader, 1828 * and the caller does not have the 1829 * {@link RuntimePermission}{@code ("getClassLoader")} 1830 * 1831 * @since 9 1832 * @spec JPMS 1833 */ 1834 @CallerSensitive 1835 public static ClassLoader getPlatformClassLoader() { 1836 SecurityManager sm = System.getSecurityManager(); 1837 ClassLoader loader = getBuiltinPlatformClassLoader(); 1838 if (sm != null) { 1839 checkClassLoaderPermission(loader, Reflection.getCallerClass()); 1840 } 1841 return loader; 1842 } 1843 1844 /** 1845 * Returns the system class loader for delegation. This is the default 1846 * delegation parent for new {@code ClassLoader} instances, and is 1847 * typically the class loader used to start the application. 1848 * 1849 * <p> This method is first invoked early in the runtime's startup 1850 * sequence, at which point it creates the system class loader. This 1851 * class loader will be the context class loader for the main application 1852 * thread (for example, the thread that invokes the {@code main} method of 1853 * the main class). 1854 * 1855 * <p> The default system class loader is an implementation-dependent 1856 * instance of this class. 1857 * 1858 * <p> If the system property "{@code java.system.class.loader}" is defined 1859 * when this method is first invoked then the value of that property is 1860 * taken to be the name of a class that will be returned as the system 1861 * class loader. The class is loaded using the default system class loader 1862 * and must define a public constructor that takes a single parameter of 1863 * type {@code ClassLoader} which is used as the delegation parent. An 1864 * instance is then created using this constructor with the default system 1865 * class loader as the parameter. The resulting class loader is defined 1866 * to be the system class loader. During construction, the class loader 1867 * should take great care to avoid calling {@code getSystemClassLoader()}. 1868 * If circular initialization of the system class loader is detected then 1869 * an unspecified error or exception is thrown. 1870 * 1871 * @implNote The system property to override the system class loader is not 1872 * examined until the VM is almost fully initialized. Code that executes 1873 * this method during startup should take care not to cache the return 1874 * value until the system is fully initialized. 1875 * 1876 * <p> The name of the built-in system class loader is {@code "app"}. 1877 * The class path used by the built-in system class loader is determined 1878 * by the system property "{@code java.class.path}" during early 1879 * initialization of the VM. If the system property is not defined, 1880 * or its value is an empty string, then there is no class path 1881 * when the initial module is a module on the application module path, 1882 * i.e. <em>a named module</em>. If the initial module is not on 1883 * the application module path then the class path defaults to 1884 * the current working directory. 1885 * 1886 * @return The system {@code ClassLoader} for delegation 1887 * 1888 * @throws SecurityException 1889 * If a security manager is present, and the caller's class loader 1890 * is not {@code null} and is not the same as or an ancestor of the 1891 * system class loader, and the caller does not have the 1892 * {@link RuntimePermission}{@code ("getClassLoader")} 1893 * 1894 * @throws IllegalStateException 1895 * If invoked recursively during the construction of the class 1896 * loader specified by the "{@code java.system.class.loader}" 1897 * property. 1898 * 1899 * @throws Error 1900 * If the system property "{@code java.system.class.loader}" 1901 * is defined but the named class could not be loaded, the 1902 * provider class does not define the required constructor, or an 1903 * exception is thrown by that constructor when it is invoked. The 1904 * underlying cause of the error can be retrieved via the 1905 * {@link Throwable#getCause()} method. 1906 * 1907 * @revised 1.4 1908 * @revised 9 1909 * @spec JPMS 1910 */ 1911 @CallerSensitive 1912 public static ClassLoader getSystemClassLoader() { 1913 switch (VM.initLevel()) { 1914 case 0: 1915 case 1: 1916 case 2: 1917 // the system class loader is the built-in app class loader during startup 1918 return getBuiltinAppClassLoader(); 1919 case 3: 1920 String msg = "getSystemClassLoader should only be called after VM booted"; 1921 throw new InternalError(msg); 1922 case 4: 1923 // system fully initialized 1924 assert VM.isBooted() && scl != null; 1925 SecurityManager sm = System.getSecurityManager(); 1926 if (sm != null) { 1927 checkClassLoaderPermission(scl, Reflection.getCallerClass()); 1928 } 1929 return scl; 1930 default: 1931 throw new InternalError("should not reach here"); 1932 } 1933 } 1934 1935 static ClassLoader getBuiltinPlatformClassLoader() { 1936 return ClassLoaders.platformClassLoader(); 1937 } 1938 1939 static ClassLoader getBuiltinAppClassLoader() { 1940 return ClassLoaders.appClassLoader(); 1941 } 1942 1943 /* 1944 * Initialize the system class loader that may be a custom class on the 1945 * application class path or application module path. 1946 * 1947 * @see java.lang.System#initPhase3 1948 */ 1949 static synchronized ClassLoader initSystemClassLoader() { 1950 if (VM.initLevel() != 3) { 1951 throw new InternalError("system class loader cannot be set at initLevel " + 1952 VM.initLevel()); 1953 } 1954 1955 // detect recursive initialization 1956 if (scl != null) { 1957 throw new IllegalStateException("recursive invocation"); 1958 } 1959 1960 ClassLoader builtinLoader = getBuiltinAppClassLoader(); 1961 1962 // All are privileged frames. No need to call doPrivileged. 1963 String cn = System.getProperty("java.system.class.loader"); 1964 if (cn != null) { 1965 try { 1966 // custom class loader is only supported to be loaded from unnamed module 1967 Constructor<?> ctor = Class.forName(cn, false, builtinLoader) 1968 .getDeclaredConstructor(ClassLoader.class); 1969 scl = (ClassLoader) ctor.newInstance(builtinLoader); 1970 } catch (Exception e) { 1971 throw new Error(e); 1972 } 1973 } else { 1974 scl = builtinLoader; 1975 } 1976 return scl; 1977 } 1978 1979 // Returns true if the specified class loader can be found in this class 1980 // loader's delegation chain. 1981 boolean isAncestor(ClassLoader cl) { 1982 ClassLoader acl = this; 1983 do { 1984 acl = acl.parent; 1985 if (cl == acl) { 1986 return true; 1987 } 1988 } while (acl != null); 1989 return false; 1990 } 1991 1992 // Tests if class loader access requires "getClassLoader" permission 1993 // check. A class loader 'from' can access class loader 'to' if 1994 // class loader 'from' is same as class loader 'to' or an ancestor 1995 // of 'to'. The class loader in a system domain can access 1996 // any class loader. 1997 private static boolean needsClassLoaderPermissionCheck(ClassLoader from, 1998 ClassLoader to) 1999 { 2000 if (from == to) 2001 return false; 2002 2003 if (from == null) 2004 return false; 2005 2006 return !to.isAncestor(from); 2007 } 2008 2009 // Returns the class's class loader, or null if none. 2010 static ClassLoader getClassLoader(Class<?> caller) { 2011 // This can be null if the VM is requesting it 2012 if (caller == null) { 2013 return null; 2014 } 2015 // Circumvent security check since this is package-private 2016 return caller.getClassLoader0(); 2017 } 2018 2019 /* 2020 * Checks RuntimePermission("getClassLoader") permission 2021 * if caller's class loader is not null and caller's class loader 2022 * is not the same as or an ancestor of the given cl argument. 2023 */ 2024 static void checkClassLoaderPermission(ClassLoader cl, Class<?> caller) { 2025 SecurityManager sm = System.getSecurityManager(); 2026 if (sm != null) { 2027 // caller can be null if the VM is requesting it 2028 ClassLoader ccl = getClassLoader(caller); 2029 if (needsClassLoaderPermissionCheck(ccl, cl)) { 2030 sm.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION); 2031 } 2032 } 2033 } 2034 2035 // The system class loader 2036 // @GuardedBy("ClassLoader.class") 2037 private static volatile ClassLoader scl; 2038 2039 // -- Package -- 2040 2041 /** 2042 * Define a Package of the given Class object. 2043 * 2044 * If the given class represents an array type, a primitive type or void, 2045 * this method returns {@code null}. 2046 * 2047 * This method does not throw IllegalArgumentException. 2048 */ 2049 Package definePackage(Class<?> c) { 2050 if (c.isPrimitive() || c.isArray()) { 2051 return null; 2052 } 2053 2054 return definePackage(c.getPackageName(), c.getModule()); 2055 } 2056 2057 /** 2058 * Defines a Package of the given name and module 2059 * 2060 * This method does not throw IllegalArgumentException. 2061 * 2062 * @param name package name 2063 * @param m module 2064 */ 2065 Package definePackage(String name, Module m) { 2066 if (name.isEmpty() && m.isNamed()) { 2067 throw new InternalError("unnamed package in " + m); 2068 } 2069 2070 // check if Package object is already defined 2071 NamedPackage pkg = packages.get(name); 2072 if (pkg instanceof Package) 2073 return (Package)pkg; 2074 2075 return (Package)packages.compute(name, (n, p) -> toPackage(n, p, m)); 2076 } 2077 2078 /* 2079 * Returns a Package object for the named package 2080 */ 2081 private Package toPackage(String name, NamedPackage p, Module m) { 2082 // define Package object if the named package is not yet defined 2083 if (p == null) 2084 return NamedPackage.toPackage(name, m); 2085 2086 // otherwise, replace the NamedPackage object with Package object 2087 if (p instanceof Package) 2088 return (Package)p; 2089 2090 return NamedPackage.toPackage(p.packageName(), p.module()); 2091 } 2092 2093 /** 2094 * Defines a package by <a href="#name">name</a> in this {@code ClassLoader}. 2095 * <p> 2096 * <a href="#name">Package names</a> must be unique within a class loader and 2097 * cannot be redefined or changed once created. 2098 * <p> 2099 * If a class loader wishes to define a package with specific properties, 2100 * such as version information, then the class loader should call this 2101 * {@code definePackage} method before calling {@code defineClass}. 2102 * Otherwise, the 2103 * {@link #defineClass(String, byte[], int, int, ProtectionDomain) defineClass} 2104 * method will define a package in this class loader corresponding to the package 2105 * of the newly defined class; the properties of this defined package are 2106 * specified by {@link Package}. 2107 * 2108 * @apiNote 2109 * A class loader that wishes to define a package for classes in a JAR 2110 * typically uses the specification and implementation titles, versions, and 2111 * vendors from the JAR's manifest. If the package is specified as 2112 * {@linkplain java.util.jar.Attributes.Name#SEALED sealed} in the JAR's manifest, 2113 * the {@code URL} of the JAR file is typically used as the {@code sealBase}. 2114 * If classes of package {@code 'p'} defined by this class loader 2115 * are loaded from multiple JARs, the {@code Package} object may contain 2116 * different information depending on the first class of package {@code 'p'} 2117 * defined and which JAR's manifest is read first to explicitly define 2118 * package {@code 'p'}. 2119 * 2120 * <p> It is strongly recommended that a class loader does not call this 2121 * method to explicitly define packages in <em>named modules</em>; instead, 2122 * the package will be automatically defined when a class is {@linkplain 2123 * #defineClass(String, byte[], int, int, ProtectionDomain) being defined}. 2124 * If it is desirable to define {@code Package} explicitly, it should ensure 2125 * that all packages in a named module are defined with the properties 2126 * specified by {@link Package}. Otherwise, some {@code Package} objects 2127 * in a named module may be for example sealed with different seal base. 2128 * 2129 * @param name 2130 * The <a href="#name">package name</a> 2131 * 2132 * @param specTitle 2133 * The specification title 2134 * 2135 * @param specVersion 2136 * The specification version 2137 * 2138 * @param specVendor 2139 * The specification vendor 2140 * 2141 * @param implTitle 2142 * The implementation title 2143 * 2144 * @param implVersion 2145 * The implementation version 2146 * 2147 * @param implVendor 2148 * The implementation vendor 2149 * 2150 * @param sealBase 2151 * If not {@code null}, then this package is sealed with 2152 * respect to the given code source {@link java.net.URL URL} 2153 * object. Otherwise, the package is not sealed. 2154 * 2155 * @return The newly defined {@code Package} object 2156 * 2157 * @throws NullPointerException 2158 * if {@code name} is {@code null}. 2159 * 2160 * @throws IllegalArgumentException 2161 * if a package of the given {@code name} is already 2162 * defined by this class loader 2163 * 2164 * @since 1.2 2165 * @revised 9 2166 * @spec JPMS 2167 * 2168 * @see <a href="{@docRoot}/../specs/jar/jar.html#sealing"> 2169 * The JAR File Specification: Package Sealing</a> 2170 */ 2171 protected Package definePackage(String name, String specTitle, 2172 String specVersion, String specVendor, 2173 String implTitle, String implVersion, 2174 String implVendor, URL sealBase) 2175 { 2176 Objects.requireNonNull(name); 2177 2178 // definePackage is not final and may be overridden by custom class loader 2179 Package p = new Package(name, specTitle, specVersion, specVendor, 2180 implTitle, implVersion, implVendor, 2181 sealBase, this); 2182 2183 if (packages.putIfAbsent(name, p) != null) 2184 throw new IllegalArgumentException(name); 2185 2186 return p; 2187 } 2188 2189 /** 2190 * Returns a {@code Package} of the given <a href="#name">name</a> that has been 2191 * defined by this class loader. 2192 * 2193 * @param name The <a href="#name">package name</a> 2194 * 2195 * @return The {@code Package} of the given name defined by this class loader, 2196 * or {@code null} if not found 2197 * 2198 * @throws NullPointerException 2199 * if {@code name} is {@code null}. 2200 * 2201 * @since 9 2202 * @spec JPMS 2203 */ 2204 public final Package getDefinedPackage(String name) { 2205 Objects.requireNonNull(name, "name cannot be null"); 2206 2207 NamedPackage p = packages.get(name); 2208 if (p == null) 2209 return null; 2210 2211 return definePackage(name, p.module()); 2212 } 2213 2214 /** 2215 * Returns all of the {@code Package}s defined by this class loader. 2216 * The returned array has no duplicated {@code Package}s of the same name. 2217 * 2218 * @apiNote This method returns an array rather than a {@code Set} or {@code Stream} 2219 * for consistency with the existing {@link #getPackages} method. 2220 * 2221 * @return The array of {@code Package} objects defined by this class loader; 2222 * or an zero length array if no package has been defined by this class loader. 2223 * 2224 * @since 9 2225 * @spec JPMS 2226 */ 2227 public final Package[] getDefinedPackages() { 2228 return packages().toArray(Package[]::new); 2229 } 2230 2231 /** 2232 * Finds a package by <a href="#name">name</a> in this class loader and its ancestors. 2233 * <p> 2234 * If this class loader defines a {@code Package} of the given name, 2235 * the {@code Package} is returned. Otherwise, the ancestors of 2236 * this class loader are searched recursively (parent by parent) 2237 * for a {@code Package} of the given name. 2238 * 2239 * @apiNote The {@link #getPlatformClassLoader() platform class loader} 2240 * may delegate to the application class loader but the application class 2241 * loader is not its ancestor. When invoked on the platform class loader, 2242 * this method will not find packages defined to the application 2243 * class loader. 2244 * 2245 * @param name 2246 * The <a href="#name">package name</a> 2247 * 2248 * @return The {@code Package} corresponding to the given name defined by 2249 * this class loader or its ancestors, or {@code null} if not found. 2250 * 2251 * @throws NullPointerException 2252 * if {@code name} is {@code null}. 2253 * 2254 * @deprecated 2255 * If multiple class loaders delegate to each other and define classes 2256 * with the same package name, and one such loader relies on the lookup 2257 * behavior of {@code getPackage} to return a {@code Package} from 2258 * a parent loader, then the properties exposed by the {@code Package} 2259 * may not be as expected in the rest of the program. 2260 * For example, the {@code Package} will only expose annotations from the 2261 * {@code package-info.class} file defined by the parent loader, even if 2262 * annotations exist in a {@code package-info.class} file defined by 2263 * a child loader. A more robust approach is to use the 2264 * {@link ClassLoader#getDefinedPackage} method which returns 2265 * a {@code Package} for the specified class loader. 2266 * 2267 * @since 1.2 2268 * @revised 9 2269 * @spec JPMS 2270 */ 2271 @Deprecated(since="9") 2272 protected Package getPackage(String name) { 2273 Package pkg = getDefinedPackage(name); 2274 if (pkg == null) { 2275 if (parent != null) { 2276 pkg = parent.getPackage(name); 2277 } else { 2278 pkg = BootLoader.getDefinedPackage(name); 2279 } 2280 } 2281 return pkg; 2282 } 2283 2284 /** 2285 * Returns all of the {@code Package}s defined by this class loader 2286 * and its ancestors. The returned array may contain more than one 2287 * {@code Package} object of the same package name, each defined by 2288 * a different class loader in the class loader hierarchy. 2289 * 2290 * @apiNote The {@link #getPlatformClassLoader() platform class loader} 2291 * may delegate to the application class loader. In other words, 2292 * packages in modules defined to the application class loader may be 2293 * visible to the platform class loader. On the other hand, 2294 * the application class loader is not its ancestor and hence 2295 * when invoked on the platform class loader, this method will not 2296 * return any packages defined to the application class loader. 2297 * 2298 * @return The array of {@code Package} objects defined by this 2299 * class loader and its ancestors 2300 * 2301 * @since 1.2 2302 * @revised 9 2303 * @spec JPMS 2304 */ 2305 protected Package[] getPackages() { 2306 Stream<Package> pkgs = packages(); 2307 ClassLoader ld = parent; 2308 while (ld != null) { 2309 pkgs = Stream.concat(ld.packages(), pkgs); 2310 ld = ld.parent; 2311 } 2312 return Stream.concat(BootLoader.packages(), pkgs) 2313 .toArray(Package[]::new); 2314 } 2315 2316 2317 2318 // package-private 2319 2320 /** 2321 * Returns a stream of Packages defined in this class loader 2322 */ 2323 Stream<Package> packages() { 2324 return packages.values().stream() 2325 .map(p -> definePackage(p.packageName(), p.module())); 2326 } 2327 2328 // -- Native library access -- 2329 2330 /** 2331 * Returns the absolute path name of a native library. The VM invokes this 2332 * method to locate the native libraries that belong to classes loaded with 2333 * this class loader. If this method returns {@code null}, the VM 2334 * searches the library along the path specified as the 2335 * "{@code java.library.path}" property. 2336 * 2337 * @param libname 2338 * The library name 2339 * 2340 * @return The absolute path of the native library 2341 * 2342 * @see System#loadLibrary(String) 2343 * @see System#mapLibraryName(String) 2344 * 2345 * @since 1.2 2346 */ 2347 protected String findLibrary(String libname) { 2348 return null; 2349 } 2350 2351 /** 2352 * The inner class NativeLibrary denotes a loaded native library instance. 2353 * Every classloader contains a vector of loaded native libraries in the 2354 * private field {@code nativeLibraries}. The native libraries loaded 2355 * into the system are entered into the {@code systemNativeLibraries} 2356 * vector. 2357 * 2358 * <p> Every native library requires a particular version of JNI. This is 2359 * denoted by the private {@code jniVersion} field. This field is set by 2360 * the VM when it loads the library, and used by the VM to pass the correct 2361 * version of JNI to the native methods. </p> 2362 * 2363 * @see ClassLoader 2364 * @since 1.2 2365 */ 2366 static class NativeLibrary { 2367 // opaque handle to native library, used in native code. 2368 long handle; 2369 // the version of JNI environment the native library requires. 2370 private int jniVersion; 2371 // the class from which the library is loaded, also indicates 2372 // the loader this native library belongs. 2373 private final Class<?> fromClass; 2374 // the canonicalized name of the native library. 2375 // or static library name 2376 String name; 2377 // Indicates if the native library is linked into the VM 2378 boolean isBuiltin; 2379 // Indicates if the native library is loaded 2380 boolean loaded; 2381 native void load(String name, boolean isBuiltin); 2382 2383 native long find(String name); 2384 native void unload(String name, boolean isBuiltin); 2385 2386 public NativeLibrary(Class<?> fromClass, String name, boolean isBuiltin) { 2387 this.name = name; 2388 this.fromClass = fromClass; 2389 this.isBuiltin = isBuiltin; 2390 } 2391 2392 @SuppressWarnings("deprecation") 2393 protected void finalize() { 2394 synchronized (loadedLibraryNames) { 2395 if (fromClass.getClassLoader() != null && loaded) { 2396 /* remove the native library name */ 2397 int size = loadedLibraryNames.size(); 2398 for (int i = 0; i < size; i++) { 2399 if (name.equals(loadedLibraryNames.elementAt(i))) { 2400 loadedLibraryNames.removeElementAt(i); 2401 break; 2402 } 2403 } 2404 /* unload the library. */ 2405 ClassLoader.nativeLibraryContext.push(this); 2406 try { 2407 unload(name, isBuiltin); 2408 } finally { 2409 ClassLoader.nativeLibraryContext.pop(); 2410 } 2411 } 2412 } 2413 } 2414 // Invoked in the VM to determine the context class in 2415 // JNI_Load/JNI_Unload 2416 static Class<?> getFromClass() { 2417 return ClassLoader.nativeLibraryContext.peek().fromClass; 2418 } 2419 } 2420 2421 // All native library names we've loaded. 2422 private static Vector<String> loadedLibraryNames = new Vector<>(); 2423 2424 // Native libraries belonging to system classes. 2425 private static Vector<NativeLibrary> systemNativeLibraries 2426 = new Vector<>(); 2427 2428 // Native libraries associated with the class loader. 2429 private Vector<NativeLibrary> nativeLibraries = new Vector<>(); 2430 2431 // native libraries being loaded/unloaded. 2432 private static Stack<NativeLibrary> nativeLibraryContext = new Stack<>(); 2433 2434 // The paths searched for libraries 2435 private static String usr_paths[]; 2436 private static String sys_paths[]; 2437 2438 private static String[] initializePath(String propName) { 2439 String ldPath = System.getProperty(propName, ""); 2440 int ldLen = ldPath.length(); 2441 char ps = File.pathSeparatorChar; 2442 int psCount = 0; 2443 2444 if (ClassLoaderHelper.allowsQuotedPathElements && 2445 ldPath.indexOf('\"') >= 0) { 2446 // First, remove quotes put around quoted parts of paths. 2447 // Second, use a quotation mark as a new path separator. 2448 // This will preserve any quoted old path separators. 2449 char[] buf = new char[ldLen]; 2450 int bufLen = 0; 2451 for (int i = 0; i < ldLen; ++i) { 2452 char ch = ldPath.charAt(i); 2453 if (ch == '\"') { 2454 while (++i < ldLen && 2455 (ch = ldPath.charAt(i)) != '\"') { 2456 buf[bufLen++] = ch; 2457 } 2458 } else { 2459 if (ch == ps) { 2460 psCount++; 2461 ch = '\"'; 2462 } 2463 buf[bufLen++] = ch; 2464 } 2465 } 2466 ldPath = new String(buf, 0, bufLen); 2467 ldLen = bufLen; 2468 ps = '\"'; 2469 } else { 2470 for (int i = ldPath.indexOf(ps); i >= 0; 2471 i = ldPath.indexOf(ps, i + 1)) { 2472 psCount++; 2473 } 2474 } 2475 2476 String[] paths = new String[psCount + 1]; 2477 int pathStart = 0; 2478 for (int j = 0; j < psCount; ++j) { 2479 int pathEnd = ldPath.indexOf(ps, pathStart); 2480 paths[j] = (pathStart < pathEnd) ? 2481 ldPath.substring(pathStart, pathEnd) : "."; 2482 pathStart = pathEnd + 1; 2483 } 2484 paths[psCount] = (pathStart < ldLen) ? 2485 ldPath.substring(pathStart, ldLen) : "."; 2486 return paths; 2487 } 2488 2489 // Invoked in the java.lang.Runtime class to implement load and loadLibrary. 2490 static void loadLibrary(Class<?> fromClass, String name, 2491 boolean isAbsolute) { 2492 ClassLoader loader = 2493 (fromClass == null) ? null : fromClass.getClassLoader(); 2494 if (sys_paths == null) { 2495 usr_paths = initializePath("java.library.path"); 2496 sys_paths = initializePath("sun.boot.library.path"); 2497 } 2498 if (isAbsolute) { 2499 if (loadLibrary0(fromClass, new File(name))) { 2500 return; 2501 } 2502 throw new UnsatisfiedLinkError("Can't load library: " + name); 2503 } 2504 if (loader != null) { 2505 String libfilename = loader.findLibrary(name); 2506 if (libfilename != null) { 2507 File libfile = new File(libfilename); 2508 if (!libfile.isAbsolute()) { 2509 throw new UnsatisfiedLinkError( 2510 "ClassLoader.findLibrary failed to return an absolute path: " + libfilename); 2511 } 2512 if (loadLibrary0(fromClass, libfile)) { 2513 return; 2514 } 2515 throw new UnsatisfiedLinkError("Can't load " + libfilename); 2516 } 2517 } 2518 for (String sys_path : sys_paths) { 2519 File libfile = new File(sys_path, System.mapLibraryName(name)); 2520 if (loadLibrary0(fromClass, libfile)) { 2521 return; 2522 } 2523 libfile = ClassLoaderHelper.mapAlternativeName(libfile); 2524 if (libfile != null && loadLibrary0(fromClass, libfile)) { 2525 return; 2526 } 2527 } 2528 if (loader != null) { 2529 for (String usr_path : usr_paths) { 2530 File libfile = new File(usr_path, System.mapLibraryName(name)); 2531 if (loadLibrary0(fromClass, libfile)) { 2532 return; 2533 } 2534 libfile = ClassLoaderHelper.mapAlternativeName(libfile); 2535 if (libfile != null && loadLibrary0(fromClass, libfile)) { 2536 return; 2537 } 2538 } 2539 } 2540 // Oops, it failed 2541 throw new UnsatisfiedLinkError("no " + name + " in java.library.path"); 2542 } 2543 2544 static native String findBuiltinLib(String name); 2545 2546 private static boolean loadLibrary0(Class<?> fromClass, final File file) { 2547 // Check to see if we're attempting to access a static library 2548 String name = findBuiltinLib(file.getName()); 2549 boolean isBuiltin = (name != null); 2550 if (!isBuiltin) { 2551 name = AccessController.doPrivileged( 2552 new PrivilegedAction<>() { 2553 public String run() { 2554 try { 2555 return file.exists() ? file.getCanonicalPath() : null; 2556 } catch (IOException e) { 2557 return null; 2558 } 2559 } 2560 }); 2561 if (name == null) { 2562 return false; 2563 } 2564 } 2565 ClassLoader loader = 2566 (fromClass == null) ? null : fromClass.getClassLoader(); 2567 Vector<NativeLibrary> libs = 2568 loader != null ? loader.nativeLibraries : systemNativeLibraries; 2569 synchronized (libs) { 2570 int size = libs.size(); 2571 for (int i = 0; i < size; i++) { 2572 NativeLibrary lib = libs.elementAt(i); 2573 if (name.equals(lib.name)) { 2574 return true; 2575 } 2576 } 2577 2578 synchronized (loadedLibraryNames) { 2579 if (loadedLibraryNames.contains(name)) { 2580 throw new UnsatisfiedLinkError 2581 ("Native Library " + 2582 name + 2583 " already loaded in another classloader"); 2584 } 2585 /* If the library is being loaded (must be by the same thread, 2586 * because Runtime.load and Runtime.loadLibrary are 2587 * synchronous). The reason is can occur is that the JNI_OnLoad 2588 * function can cause another loadLibrary invocation. 2589 * 2590 * Thus we can use a static stack to hold the list of libraries 2591 * we are loading. 2592 * 2593 * If there is a pending load operation for the library, we 2594 * immediately return success; otherwise, we raise 2595 * UnsatisfiedLinkError. 2596 */ 2597 int n = nativeLibraryContext.size(); 2598 for (int i = 0; i < n; i++) { 2599 NativeLibrary lib = nativeLibraryContext.elementAt(i); 2600 if (name.equals(lib.name)) { 2601 if (loader == lib.fromClass.getClassLoader()) { 2602 return true; 2603 } else { 2604 throw new UnsatisfiedLinkError 2605 ("Native Library " + 2606 name + 2607 " is being loaded in another classloader"); 2608 } 2609 } 2610 } 2611 NativeLibrary lib = new NativeLibrary(fromClass, name, isBuiltin); 2612 nativeLibraryContext.push(lib); 2613 try { 2614 lib.load(name, isBuiltin); 2615 } finally { 2616 nativeLibraryContext.pop(); 2617 } 2618 if (lib.loaded) { 2619 loadedLibraryNames.addElement(name); 2620 libs.addElement(lib); 2621 return true; 2622 } 2623 return false; 2624 } 2625 } 2626 } 2627 2628 // Invoked in the VM class linking code. 2629 static long findNative(ClassLoader loader, String name) { 2630 Vector<NativeLibrary> libs = 2631 loader != null ? loader.nativeLibraries : systemNativeLibraries; 2632 synchronized (libs) { 2633 int size = libs.size(); 2634 for (int i = 0; i < size; i++) { 2635 NativeLibrary lib = libs.elementAt(i); 2636 long entry = lib.find(name); 2637 if (entry != 0) 2638 return entry; 2639 } 2640 } 2641 return 0; 2642 } 2643 2644 2645 // -- Assertion management -- 2646 2647 final Object assertionLock; 2648 2649 // The default toggle for assertion checking. 2650 // @GuardedBy("assertionLock") 2651 private boolean defaultAssertionStatus = false; 2652 2653 // Maps String packageName to Boolean package default assertion status Note 2654 // that the default package is placed under a null map key. If this field 2655 // is null then we are delegating assertion status queries to the VM, i.e., 2656 // none of this ClassLoader's assertion status modification methods have 2657 // been invoked. 2658 // @GuardedBy("assertionLock") 2659 private Map<String, Boolean> packageAssertionStatus = null; 2660 2661 // Maps String fullyQualifiedClassName to Boolean assertionStatus If this 2662 // field is null then we are delegating assertion status queries to the VM, 2663 // i.e., none of this ClassLoader's assertion status modification methods 2664 // have been invoked. 2665 // @GuardedBy("assertionLock") 2666 Map<String, Boolean> classAssertionStatus = null; 2667 2668 /** 2669 * Sets the default assertion status for this class loader. This setting 2670 * determines whether classes loaded by this class loader and initialized 2671 * in the future will have assertions enabled or disabled by default. 2672 * This setting may be overridden on a per-package or per-class basis by 2673 * invoking {@link #setPackageAssertionStatus(String, boolean)} or {@link 2674 * #setClassAssertionStatus(String, boolean)}. 2675 * 2676 * @param enabled 2677 * {@code true} if classes loaded by this class loader will 2678 * henceforth have assertions enabled by default, {@code false} 2679 * if they will have assertions disabled by default. 2680 * 2681 * @since 1.4 2682 */ 2683 public void setDefaultAssertionStatus(boolean enabled) { 2684 synchronized (assertionLock) { 2685 if (classAssertionStatus == null) 2686 initializeJavaAssertionMaps(); 2687 2688 defaultAssertionStatus = enabled; 2689 } 2690 } 2691 2692 /** 2693 * Sets the package default assertion status for the named package. The 2694 * package default assertion status determines the assertion status for 2695 * classes initialized in the future that belong to the named package or 2696 * any of its "subpackages". 2697 * 2698 * <p> A subpackage of a package named p is any package whose name begins 2699 * with "{@code p.}". For example, {@code javax.swing.text} is a 2700 * subpackage of {@code javax.swing}, and both {@code java.util} and 2701 * {@code java.lang.reflect} are subpackages of {@code java}. 2702 * 2703 * <p> In the event that multiple package defaults apply to a given class, 2704 * the package default pertaining to the most specific package takes 2705 * precedence over the others. For example, if {@code javax.lang} and 2706 * {@code javax.lang.reflect} both have package defaults associated with 2707 * them, the latter package default applies to classes in 2708 * {@code javax.lang.reflect}. 2709 * 2710 * <p> Package defaults take precedence over the class loader's default 2711 * assertion status, and may be overridden on a per-class basis by invoking 2712 * {@link #setClassAssertionStatus(String, boolean)}. </p> 2713 * 2714 * @param packageName 2715 * The name of the package whose package default assertion status 2716 * is to be set. A {@code null} value indicates the unnamed 2717 * package that is "current" 2718 * (see section 7.4.2 of 2719 * <cite>The Java™ Language Specification</cite>.) 2720 * 2721 * @param enabled 2722 * {@code true} if classes loaded by this classloader and 2723 * belonging to the named package or any of its subpackages will 2724 * have assertions enabled by default, {@code false} if they will 2725 * have assertions disabled by default. 2726 * 2727 * @since 1.4 2728 */ 2729 public void setPackageAssertionStatus(String packageName, 2730 boolean enabled) { 2731 synchronized (assertionLock) { 2732 if (packageAssertionStatus == null) 2733 initializeJavaAssertionMaps(); 2734 2735 packageAssertionStatus.put(packageName, enabled); 2736 } 2737 } 2738 2739 /** 2740 * Sets the desired assertion status for the named top-level class in this 2741 * class loader and any nested classes contained therein. This setting 2742 * takes precedence over the class loader's default assertion status, and 2743 * over any applicable per-package default. This method has no effect if 2744 * the named class has already been initialized. (Once a class is 2745 * initialized, its assertion status cannot change.) 2746 * 2747 * <p> If the named class is not a top-level class, this invocation will 2748 * have no effect on the actual assertion status of any class. </p> 2749 * 2750 * @param className 2751 * The fully qualified class name of the top-level class whose 2752 * assertion status is to be set. 2753 * 2754 * @param enabled 2755 * {@code true} if the named class is to have assertions 2756 * enabled when (and if) it is initialized, {@code false} if the 2757 * class is to have assertions disabled. 2758 * 2759 * @since 1.4 2760 */ 2761 public void setClassAssertionStatus(String className, boolean enabled) { 2762 synchronized (assertionLock) { 2763 if (classAssertionStatus == null) 2764 initializeJavaAssertionMaps(); 2765 2766 classAssertionStatus.put(className, enabled); 2767 } 2768 } 2769 2770 /** 2771 * Sets the default assertion status for this class loader to 2772 * {@code false} and discards any package defaults or class assertion 2773 * status settings associated with the class loader. This method is 2774 * provided so that class loaders can be made to ignore any command line or 2775 * persistent assertion status settings and "start with a clean slate." 2776 * 2777 * @since 1.4 2778 */ 2779 public void clearAssertionStatus() { 2780 /* 2781 * Whether or not "Java assertion maps" are initialized, set 2782 * them to empty maps, effectively ignoring any present settings. 2783 */ 2784 synchronized (assertionLock) { 2785 classAssertionStatus = new HashMap<>(); 2786 packageAssertionStatus = new HashMap<>(); 2787 defaultAssertionStatus = false; 2788 } 2789 } 2790 2791 /** 2792 * Returns the assertion status that would be assigned to the specified 2793 * class if it were to be initialized at the time this method is invoked. 2794 * If the named class has had its assertion status set, the most recent 2795 * setting will be returned; otherwise, if any package default assertion 2796 * status pertains to this class, the most recent setting for the most 2797 * specific pertinent package default assertion status is returned; 2798 * otherwise, this class loader's default assertion status is returned. 2799 * </p> 2800 * 2801 * @param className 2802 * The fully qualified class name of the class whose desired 2803 * assertion status is being queried. 2804 * 2805 * @return The desired assertion status of the specified class. 2806 * 2807 * @see #setClassAssertionStatus(String, boolean) 2808 * @see #setPackageAssertionStatus(String, boolean) 2809 * @see #setDefaultAssertionStatus(boolean) 2810 * 2811 * @since 1.4 2812 */ 2813 boolean desiredAssertionStatus(String className) { 2814 synchronized (assertionLock) { 2815 // assert classAssertionStatus != null; 2816 // assert packageAssertionStatus != null; 2817 2818 // Check for a class entry 2819 Boolean result = classAssertionStatus.get(className); 2820 if (result != null) 2821 return result.booleanValue(); 2822 2823 // Check for most specific package entry 2824 int dotIndex = className.lastIndexOf('.'); 2825 if (dotIndex < 0) { // default package 2826 result = packageAssertionStatus.get(null); 2827 if (result != null) 2828 return result.booleanValue(); 2829 } 2830 while(dotIndex > 0) { 2831 className = className.substring(0, dotIndex); 2832 result = packageAssertionStatus.get(className); 2833 if (result != null) 2834 return result.booleanValue(); 2835 dotIndex = className.lastIndexOf('.', dotIndex-1); 2836 } 2837 2838 // Return the classloader default 2839 return defaultAssertionStatus; 2840 } 2841 } 2842 2843 // Set up the assertions with information provided by the VM. 2844 // Note: Should only be called inside a synchronized block 2845 private void initializeJavaAssertionMaps() { 2846 // assert Thread.holdsLock(assertionLock); 2847 2848 classAssertionStatus = new HashMap<>(); 2849 packageAssertionStatus = new HashMap<>(); 2850 AssertionStatusDirectives directives = retrieveDirectives(); 2851 2852 for(int i = 0; i < directives.classes.length; i++) 2853 classAssertionStatus.put(directives.classes[i], 2854 directives.classEnabled[i]); 2855 2856 for(int i = 0; i < directives.packages.length; i++) 2857 packageAssertionStatus.put(directives.packages[i], 2858 directives.packageEnabled[i]); 2859 2860 defaultAssertionStatus = directives.deflt; 2861 } 2862 2863 // Retrieves the assertion directives from the VM. 2864 private static native AssertionStatusDirectives retrieveDirectives(); 2865 2866 2867 // -- Misc -- 2868 2869 /** 2870 * Returns the ConcurrentHashMap used as a storage for ClassLoaderValue(s) 2871 * associated with this ClassLoader, creating it if it doesn't already exist. 2872 */ 2873 ConcurrentHashMap<?, ?> createOrGetClassLoaderValueMap() { 2874 ConcurrentHashMap<?, ?> map = classLoaderValueMap; 2875 if (map == null) { 2876 map = new ConcurrentHashMap<>(); 2877 boolean set = trySetObjectField("classLoaderValueMap", map); 2878 if (!set) { 2879 // beaten by someone else 2880 map = classLoaderValueMap; 2881 } 2882 } 2883 return map; 2884 } 2885 2886 // the storage for ClassLoaderValue(s) associated with this ClassLoader 2887 private volatile ConcurrentHashMap<?, ?> classLoaderValueMap; 2888 2889 /** 2890 * Attempts to atomically set a volatile field in this object. Returns 2891 * {@code true} if not beaten by another thread. Avoids the use of 2892 * AtomicReferenceFieldUpdater in this class. 2893 */ 2894 private boolean trySetObjectField(String name, Object obj) { 2895 Unsafe unsafe = Unsafe.getUnsafe(); 2896 Class<?> k = ClassLoader.class; 2897 long offset; 2898 try { 2899 Field f = k.getDeclaredField(name); 2900 offset = unsafe.objectFieldOffset(f); 2901 } catch (NoSuchFieldException e) { 2902 throw new InternalError(e); 2903 } 2904 return unsafe.compareAndSetObject(this, offset, null, obj); 2905 } 2906} 2907 2908/* 2909 * A utility class that will enumerate over an array of enumerations. 2910 */ 2911final class CompoundEnumeration<E> implements Enumeration<E> { 2912 private final Enumeration<E>[] enums; 2913 private int index; 2914 2915 public CompoundEnumeration(Enumeration<E>[] enums) { 2916 this.enums = enums; 2917 } 2918 2919 private boolean next() { 2920 while (index < enums.length) { 2921 if (enums[index] != null && enums[index].hasMoreElements()) { 2922 return true; 2923 } 2924 index++; 2925 } 2926 return false; 2927 } 2928 2929 public boolean hasMoreElements() { 2930 return next(); 2931 } 2932 2933 public E nextElement() { 2934 if (!next()) { 2935 throw new NoSuchElementException(); 2936 } 2937 return enums[index].nextElement(); 2938 } 2939} 2940