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