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