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