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