1 /* 2 * Copyright (c) 2014, 2018, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. Oracle designates this 8 * particular file as subject to the "Classpath" exception as provided 9 * by Oracle in the LICENSE file that accompanied this code. 10 * 11 * This code is distributed in the hope that it will be useful, but WITHOUT 12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14 * version 2 for more details (a copy is included in the LICENSE file that 15 * accompanied this code). 16 * 17 * You should have received a copy of the GNU General Public License version 18 * 2 along with this work; if not, write to the Free Software Foundation, 19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 20 * 21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 22 * or visit www.oracle.com if you need additional information or have any 23 * questions. 24 */ 25 26 package java.lang; 27 28 import java.io.IOException; 29 import java.io.InputStream; 30 import java.lang.annotation.Annotation; 31 import java.lang.module.Configuration; 32 import java.lang.module.ModuleReference; 33 import java.lang.module.ModuleDescriptor; 34 import java.lang.module.ModuleDescriptor.Exports; 35 import java.lang.module.ModuleDescriptor.Opens; 36 import java.lang.module.ModuleDescriptor.Version; 37 import java.lang.module.ResolvedModule; 38 import java.lang.reflect.AnnotatedElement; 39 import java.net.URI; 40 import java.net.URL; 41 import java.security.AccessController; 42 import java.security.PrivilegedAction; 43 import java.util.HashMap; 44 import java.util.HashSet; 45 import java.util.Iterator; 46 import java.util.List; 47 import java.util.Map; 48 import java.util.Objects; 49 import java.util.Optional; 50 import java.util.Set; 51 import java.util.concurrent.ConcurrentHashMap; 52 import java.util.function.Function; 53 import java.util.stream.Collectors; 54 import java.util.stream.Stream; 55 56 import jdk.internal.loader.BuiltinClassLoader; 57 import jdk.internal.loader.BootLoader; 58 import jdk.internal.loader.ClassLoaders; 59 import jdk.internal.module.IllegalAccessLogger; 60 import jdk.internal.module.ModuleLoaderMap; 61 import jdk.internal.module.ServicesCatalog; 62 import jdk.internal.module.Resources; 63 import jdk.internal.org.objectweb.asm.AnnotationVisitor; 64 import jdk.internal.org.objectweb.asm.Attribute; 65 import jdk.internal.org.objectweb.asm.ClassReader; 66 import jdk.internal.org.objectweb.asm.ClassVisitor; 67 import jdk.internal.org.objectweb.asm.ClassWriter; 68 import jdk.internal.org.objectweb.asm.ModuleVisitor; 69 import jdk.internal.org.objectweb.asm.Opcodes; 70 import jdk.internal.reflect.CallerSensitive; 71 import jdk.internal.reflect.Reflection; 72 import sun.security.util.SecurityConstants; 73 74 /** 75 * Represents a run-time module, either {@link #isNamed() named} or unnamed. 76 * 77 * <p> Named modules have a {@link #getName() name} and are constructed by the 78 * Java Virtual Machine when a graph of modules is defined to the Java virtual 79 * machine to create a {@linkplain ModuleLayer module layer}. </p> 80 * 81 * <p> An unnamed module does not have a name. There is an unnamed module for 82 * each {@link ClassLoader ClassLoader}, obtained by invoking its {@link 83 * ClassLoader#getUnnamedModule() getUnnamedModule} method. All types that are 84 * not in a named module are members of their defining class loader's unnamed 85 * module. </p> 86 * 87 * <p> The package names that are parameters or returned by methods defined in 88 * this class are the fully-qualified names of the packages as defined in 89 * section 6.5.3 of <cite>The Java™ Language Specification</cite>, for 90 * example, {@code "java.lang"}. </p> 91 * 92 * <p> Unless otherwise specified, passing a {@code null} argument to a method 93 * in this class causes a {@link NullPointerException NullPointerException} to 94 * be thrown. </p> 95 * 96 * @since 9 97 * @spec JPMS 98 * @see Class#getModule() 99 */ 100 101 public final class Module implements AnnotatedElement { 102 103 // the layer that contains this module, can be null 104 private final ModuleLayer layer; 105 106 // module name and loader, these fields are read by VM 107 private final String name; 108 private final ClassLoader loader; 109 110 // the module descriptor 111 private final ModuleDescriptor descriptor; 112 113 114 /** 115 * Creates a new named Module. The resulting Module will be defined to the 116 * VM but will not read any other modules, will not have any exports setup 117 * and will not be registered in the service catalog. 118 */ Module(ModuleLayer layer, ClassLoader loader, ModuleDescriptor descriptor, URI uri)119 Module(ModuleLayer layer, 120 ClassLoader loader, 121 ModuleDescriptor descriptor, 122 URI uri) 123 { 124 this.layer = layer; 125 this.name = descriptor.name(); 126 this.loader = loader; 127 this.descriptor = descriptor; 128 129 // define module to VM 130 131 boolean isOpen = descriptor.isOpen() || descriptor.isAutomatic(); 132 Version version = descriptor.version().orElse(null); 133 String vs = Objects.toString(version, null); 134 String loc = Objects.toString(uri, null); 135 String[] packages = descriptor.packages().toArray(new String[0]); 136 defineModule0(this, isOpen, vs, loc, packages); 137 } 138 139 140 /** 141 * Create the unnamed Module for the given ClassLoader. 142 * 143 * @see ClassLoader#getUnnamedModule 144 */ Module(ClassLoader loader)145 Module(ClassLoader loader) { 146 this.layer = null; 147 this.name = null; 148 this.loader = loader; 149 this.descriptor = null; 150 } 151 152 153 /** 154 * Creates a named module but without defining the module to the VM. 155 * 156 * @apiNote This constructor is for VM white-box testing. 157 */ Module(ClassLoader loader, ModuleDescriptor descriptor)158 Module(ClassLoader loader, ModuleDescriptor descriptor) { 159 this.layer = null; 160 this.name = descriptor.name(); 161 this.loader = loader; 162 this.descriptor = descriptor; 163 } 164 165 166 /** 167 * Returns {@code true} if this module is a named module. 168 * 169 * @return {@code true} if this is a named module 170 * 171 * @see ClassLoader#getUnnamedModule() 172 */ isNamed()173 public boolean isNamed() { 174 return name != null; 175 } 176 177 /** 178 * Returns the module name or {@code null} if this module is an unnamed 179 * module. 180 * 181 * @return The module name 182 */ getName()183 public String getName() { 184 return name; 185 } 186 187 /** 188 * Returns the {@code ClassLoader} for this module. 189 * 190 * <p> If there is a security manager then its {@code checkPermission} 191 * method if first called with a {@code RuntimePermission("getClassLoader")} 192 * permission to check that the caller is allowed to get access to the 193 * class loader. </p> 194 * 195 * @return The class loader for this module 196 * 197 * @throws SecurityException 198 * If denied by the security manager 199 */ getClassLoader()200 public ClassLoader getClassLoader() { 201 SecurityManager sm = System.getSecurityManager(); 202 if (sm != null) { 203 sm.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION); 204 } 205 return loader; 206 } 207 208 /** 209 * Returns the module descriptor for this module or {@code null} if this 210 * module is an unnamed module. 211 * 212 * @return The module descriptor for this module 213 */ getDescriptor()214 public ModuleDescriptor getDescriptor() { 215 return descriptor; 216 } 217 218 /** 219 * Returns the module layer that contains this module or {@code null} if 220 * this module is not in a module layer. 221 * 222 * A module layer contains named modules and therefore this method always 223 * returns {@code null} when invoked on an unnamed module. 224 * 225 * <p> <a href="reflect/Proxy.html#dynamicmodule">Dynamic modules</a> are 226 * named modules that are generated at runtime. A dynamic module may or may 227 * not be in a module layer. </p> 228 * 229 * @return The module layer that contains this module 230 * 231 * @see java.lang.reflect.Proxy 232 */ getLayer()233 public ModuleLayer getLayer() { 234 if (isNamed()) { 235 ModuleLayer layer = this.layer; 236 if (layer != null) 237 return layer; 238 239 // special-case java.base as it is created before the boot layer 240 if (loader == null && name.equals("java.base")) { 241 return ModuleLayer.boot(); 242 } 243 } 244 return null; 245 } 246 247 // -- 248 249 // special Module to mean "all unnamed modules" 250 private static final Module ALL_UNNAMED_MODULE = new Module(null); 251 private static final Set<Module> ALL_UNNAMED_MODULE_SET = Set.of(ALL_UNNAMED_MODULE); 252 253 // special Module to mean "everyone" 254 private static final Module EVERYONE_MODULE = new Module(null); 255 private static final Set<Module> EVERYONE_SET = Set.of(EVERYONE_MODULE); 256 257 /** 258 * The holder of data structures to support readability, exports, and 259 * service use added at runtime with the reflective APIs. 260 */ 261 private static class ReflectionData { 262 /** 263 * A module (1st key) reads another module (2nd key) 264 */ 265 static final WeakPairMap<Module, Module, Boolean> reads = 266 new WeakPairMap<>(); 267 268 /** 269 * A module (1st key) exports or opens a package to another module 270 * (2nd key). The map value is a map of package name to a boolean 271 * that indicates if the package is opened. 272 */ 273 static final WeakPairMap<Module, Module, Map<String, Boolean>> exports = 274 new WeakPairMap<>(); 275 276 /** 277 * A module (1st key) uses a service (2nd key) 278 */ 279 static final WeakPairMap<Module, Class<?>, Boolean> uses = 280 new WeakPairMap<>(); 281 } 282 283 284 // -- readability -- 285 286 // the modules that this module reads 287 private volatile Set<Module> reads; 288 289 /** 290 * Indicates if this module reads the given module. This method returns 291 * {@code true} if invoked to test if this module reads itself. It also 292 * returns {@code true} if invoked on an unnamed module (as unnamed 293 * modules read all modules). 294 * 295 * @param other 296 * The other module 297 * 298 * @return {@code true} if this module reads {@code other} 299 * 300 * @see #addReads(Module) 301 */ canRead(Module other)302 public boolean canRead(Module other) { 303 Objects.requireNonNull(other); 304 305 // an unnamed module reads all modules 306 if (!this.isNamed()) 307 return true; 308 309 // all modules read themselves 310 if (other == this) 311 return true; 312 313 // check if this module reads other 314 if (other.isNamed()) { 315 Set<Module> reads = this.reads; // volatile read 316 if (reads != null && reads.contains(other)) 317 return true; 318 } 319 320 // check if this module reads the other module reflectively 321 if (ReflectionData.reads.containsKeyPair(this, other)) 322 return true; 323 324 // if other is an unnamed module then check if this module reads 325 // all unnamed modules 326 if (!other.isNamed() 327 && ReflectionData.reads.containsKeyPair(this, ALL_UNNAMED_MODULE)) 328 return true; 329 330 return false; 331 } 332 333 /** 334 * If the caller's module is this module then update this module to read 335 * the given module. 336 * 337 * This method is a no-op if {@code other} is this module (all modules read 338 * themselves), this module is an unnamed module (as unnamed modules read 339 * all modules), or this module already reads {@code other}. 340 * 341 * @implNote <em>Read edges</em> added by this method are <em>weak</em> and 342 * do not prevent {@code other} from being GC'ed when this module is 343 * strongly reachable. 344 * 345 * @param other 346 * The other module 347 * 348 * @return this module 349 * 350 * @throws IllegalCallerException 351 * If this is a named module and the caller's module is not this 352 * module 353 * 354 * @see #canRead 355 */ 356 @CallerSensitive addReads(Module other)357 public Module addReads(Module other) { 358 Objects.requireNonNull(other); 359 if (this.isNamed()) { 360 Module caller = getCallerModule(Reflection.getCallerClass()); 361 if (caller != this) { 362 throw new IllegalCallerException(caller + " != " + this); 363 } 364 implAddReads(other, true); 365 } 366 return this; 367 } 368 369 /** 370 * Updates this module to read another module. 371 * 372 * @apiNote Used by the --add-reads command line option. 373 */ implAddReads(Module other)374 void implAddReads(Module other) { 375 implAddReads(other, true); 376 } 377 378 /** 379 * Updates this module to read all unnamed modules. 380 * 381 * @apiNote Used by the --add-reads command line option. 382 */ implAddReadsAllUnnamed()383 void implAddReadsAllUnnamed() { 384 implAddReads(Module.ALL_UNNAMED_MODULE, true); 385 } 386 387 /** 388 * Updates this module to read another module without notifying the VM. 389 * 390 * @apiNote This method is for VM white-box testing. 391 */ implAddReadsNoSync(Module other)392 void implAddReadsNoSync(Module other) { 393 implAddReads(other, false); 394 } 395 396 /** 397 * Makes the given {@code Module} readable to this module. 398 * 399 * If {@code syncVM} is {@code true} then the VM is notified. 400 */ implAddReads(Module other, boolean syncVM)401 private void implAddReads(Module other, boolean syncVM) { 402 Objects.requireNonNull(other); 403 if (!canRead(other)) { 404 // update VM first, just in case it fails 405 if (syncVM) { 406 if (other == ALL_UNNAMED_MODULE) { 407 addReads0(this, null); 408 } else { 409 addReads0(this, other); 410 } 411 } 412 413 // add reflective read 414 ReflectionData.reads.putIfAbsent(this, other, Boolean.TRUE); 415 } 416 } 417 418 419 // -- exported and open packages -- 420 421 // the packages are open to other modules, can be null 422 // if the value contains EVERYONE_MODULE then the package is open to all 423 private volatile Map<String, Set<Module>> openPackages; 424 425 // the packages that are exported, can be null 426 // if the value contains EVERYONE_MODULE then the package is exported to all 427 private volatile Map<String, Set<Module>> exportedPackages; 428 429 /** 430 * Returns {@code true} if this module exports the given package to at 431 * least the given module. 432 * 433 * <p> This method returns {@code true} if invoked to test if a package in 434 * this module is exported to itself. It always returns {@code true} when 435 * invoked on an unnamed module. A package that is {@link #isOpen open} to 436 * the given module is considered exported to that module at run-time and 437 * so this method returns {@code true} if the package is open to the given 438 * module. </p> 439 * 440 * <p> This method does not check if the given module reads this module. </p> 441 * 442 * @param pn 443 * The package name 444 * @param other 445 * The other module 446 * 447 * @return {@code true} if this module exports the package to at least the 448 * given module 449 * 450 * @see ModuleDescriptor#exports() 451 * @see #addExports(String,Module) 452 */ isExported(String pn, Module other)453 public boolean isExported(String pn, Module other) { 454 Objects.requireNonNull(pn); 455 Objects.requireNonNull(other); 456 return implIsExportedOrOpen(pn, other, /*open*/false); 457 } 458 459 /** 460 * Returns {@code true} if this module has <em>opened</em> a package to at 461 * least the given module. 462 * 463 * <p> This method returns {@code true} if invoked to test if a package in 464 * this module is open to itself. It returns {@code true} when invoked on an 465 * {@link ModuleDescriptor#isOpen open} module with a package in the module. 466 * It always returns {@code true} when invoked on an unnamed module. </p> 467 * 468 * <p> This method does not check if the given module reads this module. </p> 469 * 470 * @param pn 471 * The package name 472 * @param other 473 * The other module 474 * 475 * @return {@code true} if this module has <em>opened</em> the package 476 * to at least the given module 477 * 478 * @see ModuleDescriptor#opens() 479 * @see #addOpens(String,Module) 480 * @see java.lang.reflect.AccessibleObject#setAccessible(boolean) 481 * @see java.lang.invoke.MethodHandles#privateLookupIn 482 */ isOpen(String pn, Module other)483 public boolean isOpen(String pn, Module other) { 484 Objects.requireNonNull(pn); 485 Objects.requireNonNull(other); 486 return implIsExportedOrOpen(pn, other, /*open*/true); 487 } 488 489 /** 490 * Returns {@code true} if this module exports the given package 491 * unconditionally. 492 * 493 * <p> This method always returns {@code true} when invoked on an unnamed 494 * module. A package that is {@link #isOpen(String) opened} unconditionally 495 * is considered exported unconditionally at run-time and so this method 496 * returns {@code true} if the package is opened unconditionally. </p> 497 * 498 * <p> This method does not check if the given module reads this module. </p> 499 * 500 * @param pn 501 * The package name 502 * 503 * @return {@code true} if this module exports the package unconditionally 504 * 505 * @see ModuleDescriptor#exports() 506 */ isExported(String pn)507 public boolean isExported(String pn) { 508 Objects.requireNonNull(pn); 509 return implIsExportedOrOpen(pn, EVERYONE_MODULE, /*open*/false); 510 } 511 512 /** 513 * Returns {@code true} if this module has <em>opened</em> a package 514 * unconditionally. 515 * 516 * <p> This method always returns {@code true} when invoked on an unnamed 517 * module. Additionally, it always returns {@code true} when invoked on an 518 * {@link ModuleDescriptor#isOpen open} module with a package in the 519 * module. </p> 520 * 521 * <p> This method does not check if the given module reads this module. </p> 522 * 523 * @param pn 524 * The package name 525 * 526 * @return {@code true} if this module has <em>opened</em> the package 527 * unconditionally 528 * 529 * @see ModuleDescriptor#opens() 530 */ isOpen(String pn)531 public boolean isOpen(String pn) { 532 Objects.requireNonNull(pn); 533 return implIsExportedOrOpen(pn, EVERYONE_MODULE, /*open*/true); 534 } 535 536 537 /** 538 * Returns {@code true} if this module exports or opens the given package 539 * to the given module. If the other module is {@code EVERYONE_MODULE} then 540 * this method tests if the package is exported or opened unconditionally. 541 */ implIsExportedOrOpen(String pn, Module other, boolean open)542 private boolean implIsExportedOrOpen(String pn, Module other, boolean open) { 543 // all packages in unnamed modules are open 544 if (!isNamed()) 545 return true; 546 547 // all packages are exported/open to self 548 if (other == this && descriptor.packages().contains(pn)) 549 return true; 550 551 // all packages in open and automatic modules are open 552 if (descriptor.isOpen() || descriptor.isAutomatic()) 553 return descriptor.packages().contains(pn); 554 555 // exported/opened via module declaration/descriptor 556 if (isStaticallyExportedOrOpen(pn, other, open)) 557 return true; 558 559 // exported via addExports/addOpens 560 if (isReflectivelyExportedOrOpen(pn, other, open)) 561 return true; 562 563 // not exported or open to other 564 return false; 565 } 566 567 /** 568 * Returns {@code true} if this module exports or opens a package to 569 * the given module via its module declaration or CLI options. 570 */ isStaticallyExportedOrOpen(String pn, Module other, boolean open)571 private boolean isStaticallyExportedOrOpen(String pn, Module other, boolean open) { 572 // test if package is open to everyone or <other> 573 Map<String, Set<Module>> openPackages = this.openPackages; 574 if (openPackages != null && allows(openPackages.get(pn), other)) { 575 return true; 576 } 577 578 if (!open) { 579 // test package is exported to everyone or <other> 580 Map<String, Set<Module>> exportedPackages = this.exportedPackages; 581 if (exportedPackages != null && allows(exportedPackages.get(pn), other)) { 582 return true; 583 } 584 } 585 586 return false; 587 } 588 589 /** 590 * Returns {@code true} if targets is non-null and contains EVERYONE_MODULE 591 * or the given module. Also returns true if the given module is an unnamed 592 * module and targets contains ALL_UNNAMED_MODULE. 593 */ allows(Set<Module> targets, Module module)594 private boolean allows(Set<Module> targets, Module module) { 595 if (targets != null) { 596 if (targets.contains(EVERYONE_MODULE)) 597 return true; 598 if (module != EVERYONE_MODULE) { 599 if (targets.contains(module)) 600 return true; 601 if (!module.isNamed() && targets.contains(ALL_UNNAMED_MODULE)) 602 return true; 603 } 604 } 605 return false; 606 } 607 608 /** 609 * Returns {@code true} if this module reflectively exports or opens the 610 * given package to the given module. 611 */ isReflectivelyExportedOrOpen(String pn, Module other, boolean open)612 private boolean isReflectivelyExportedOrOpen(String pn, Module other, boolean open) { 613 // exported or open to all modules 614 Map<String, Boolean> exports = ReflectionData.exports.get(this, EVERYONE_MODULE); 615 if (exports != null) { 616 Boolean b = exports.get(pn); 617 if (b != null) { 618 boolean isOpen = b.booleanValue(); 619 if (!open || isOpen) return true; 620 } 621 } 622 623 if (other != EVERYONE_MODULE) { 624 625 // exported or open to other 626 exports = ReflectionData.exports.get(this, other); 627 if (exports != null) { 628 Boolean b = exports.get(pn); 629 if (b != null) { 630 boolean isOpen = b.booleanValue(); 631 if (!open || isOpen) return true; 632 } 633 } 634 635 // other is an unnamed module && exported or open to all unnamed 636 if (!other.isNamed()) { 637 exports = ReflectionData.exports.get(this, ALL_UNNAMED_MODULE); 638 if (exports != null) { 639 Boolean b = exports.get(pn); 640 if (b != null) { 641 boolean isOpen = b.booleanValue(); 642 if (!open || isOpen) return true; 643 } 644 } 645 } 646 647 } 648 649 return false; 650 } 651 652 /** 653 * Returns {@code true} if this module reflectively exports the 654 * given package to the given module. 655 */ isReflectivelyExported(String pn, Module other)656 boolean isReflectivelyExported(String pn, Module other) { 657 return isReflectivelyExportedOrOpen(pn, other, false); 658 } 659 660 /** 661 * Returns {@code true} if this module reflectively opens the 662 * given package to the given module. 663 */ isReflectivelyOpened(String pn, Module other)664 boolean isReflectivelyOpened(String pn, Module other) { 665 return isReflectivelyExportedOrOpen(pn, other, true); 666 } 667 668 669 /** 670 * If the caller's module is this module then update this module to export 671 * the given package to the given module. 672 * 673 * <p> This method has no effect if the package is already exported (or 674 * <em>open</em>) to the given module. </p> 675 * 676 * @apiNote As specified in section 5.4.3 of the <cite>The Java™ 677 * Virtual Machine Specification </cite>, if an attempt to resolve a 678 * symbolic reference fails because of a linkage error, then subsequent 679 * attempts to resolve the reference always fail with the same error that 680 * was thrown as a result of the initial resolution attempt. 681 * 682 * @param pn 683 * The package name 684 * @param other 685 * The module 686 * 687 * @return this module 688 * 689 * @throws IllegalArgumentException 690 * If {@code pn} is {@code null}, or this is a named module and the 691 * package {@code pn} is not a package in this module 692 * @throws IllegalCallerException 693 * If this is a named module and the caller's module is not this 694 * module 695 * 696 * @jvms 5.4.3 Resolution 697 * @see #isExported(String,Module) 698 */ 699 @CallerSensitive addExports(String pn, Module other)700 public Module addExports(String pn, Module other) { 701 if (pn == null) 702 throw new IllegalArgumentException("package is null"); 703 Objects.requireNonNull(other); 704 705 if (isNamed()) { 706 Module caller = getCallerModule(Reflection.getCallerClass()); 707 if (caller != this) { 708 throw new IllegalCallerException(caller + " != " + this); 709 } 710 implAddExportsOrOpens(pn, other, /*open*/false, /*syncVM*/true); 711 } 712 713 return this; 714 } 715 716 /** 717 * If this module has <em>opened</em> a package to at least the caller 718 * module then update this module to open the package to the given module. 719 * Opening a package with this method allows all types in the package, 720 * and all their members, not just public types and their public members, 721 * to be reflected on by the given module when using APIs that support 722 * private access or a way to bypass or suppress default Java language 723 * access control checks. 724 * 725 * <p> This method has no effect if the package is already <em>open</em> 726 * to the given module. </p> 727 * 728 * @apiNote This method can be used for cases where a <em>consumer 729 * module</em> uses a qualified opens to open a package to an <em>API 730 * module</em> but where the reflective access to the members of classes in 731 * the consumer module is delegated to code in another module. Code in the 732 * API module can use this method to open the package in the consumer module 733 * to the other module. 734 * 735 * @param pn 736 * The package name 737 * @param other 738 * The module 739 * 740 * @return this module 741 * 742 * @throws IllegalArgumentException 743 * If {@code pn} is {@code null}, or this is a named module and the 744 * package {@code pn} is not a package in this module 745 * @throws IllegalCallerException 746 * If this is a named module and this module has not opened the 747 * package to at least the caller's module 748 * 749 * @see #isOpen(String,Module) 750 * @see java.lang.reflect.AccessibleObject#setAccessible(boolean) 751 * @see java.lang.invoke.MethodHandles#privateLookupIn 752 */ 753 @CallerSensitive addOpens(String pn, Module other)754 public Module addOpens(String pn, Module other) { 755 if (pn == null) 756 throw new IllegalArgumentException("package is null"); 757 Objects.requireNonNull(other); 758 759 if (isNamed()) { 760 Module caller = getCallerModule(Reflection.getCallerClass()); 761 if (caller != this && (caller == null || !isOpen(pn, caller))) 762 throw new IllegalCallerException(pn + " is not open to " + caller); 763 implAddExportsOrOpens(pn, other, /*open*/true, /*syncVM*/true); 764 } 765 766 return this; 767 } 768 769 770 /** 771 * Updates this module to export a package unconditionally. 772 * 773 * @apiNote This method is for JDK tests only. 774 */ implAddExports(String pn)775 void implAddExports(String pn) { 776 implAddExportsOrOpens(pn, Module.EVERYONE_MODULE, false, true); 777 } 778 779 /** 780 * Updates this module to export a package to another module. 781 * 782 * @apiNote Used by Instrumentation::redefineModule and --add-exports 783 */ implAddExports(String pn, Module other)784 void implAddExports(String pn, Module other) { 785 implAddExportsOrOpens(pn, other, false, true); 786 } 787 788 /** 789 * Updates this module to export a package to all unnamed modules. 790 * 791 * @apiNote Used by the --add-exports command line option. 792 */ implAddExportsToAllUnnamed(String pn)793 void implAddExportsToAllUnnamed(String pn) { 794 implAddExportsOrOpens(pn, Module.ALL_UNNAMED_MODULE, false, true); 795 } 796 797 /** 798 * Updates this export to export a package unconditionally without 799 * notifying the VM. 800 * 801 * @apiNote This method is for VM white-box testing. 802 */ implAddExportsNoSync(String pn)803 void implAddExportsNoSync(String pn) { 804 implAddExportsOrOpens(pn.replace('/', '.'), Module.EVERYONE_MODULE, false, false); 805 } 806 807 /** 808 * Updates a module to export a package to another module without 809 * notifying the VM. 810 * 811 * @apiNote This method is for VM white-box testing. 812 */ implAddExportsNoSync(String pn, Module other)813 void implAddExportsNoSync(String pn, Module other) { 814 implAddExportsOrOpens(pn.replace('/', '.'), other, false, false); 815 } 816 817 /** 818 * Updates this module to open a package unconditionally. 819 * 820 * @apiNote This method is for JDK tests only. 821 */ implAddOpens(String pn)822 void implAddOpens(String pn) { 823 implAddExportsOrOpens(pn, Module.EVERYONE_MODULE, true, true); 824 } 825 826 /** 827 * Updates this module to open a package to another module. 828 * 829 * @apiNote Used by Instrumentation::redefineModule and --add-opens 830 */ implAddOpens(String pn, Module other)831 void implAddOpens(String pn, Module other) { 832 implAddExportsOrOpens(pn, other, true, true); 833 } 834 835 /** 836 * Updates this module to open a package to all unnamed modules. 837 * 838 * @apiNote Used by the --add-opens command line option. 839 */ implAddOpensToAllUnnamed(String pn)840 void implAddOpensToAllUnnamed(String pn) { 841 implAddExportsOrOpens(pn, Module.ALL_UNNAMED_MODULE, true, true); 842 } 843 844 /** 845 * Updates a module to export or open a module to another module. 846 * 847 * If {@code syncVM} is {@code true} then the VM is notified. 848 */ implAddExportsOrOpens(String pn, Module other, boolean open, boolean syncVM)849 private void implAddExportsOrOpens(String pn, 850 Module other, 851 boolean open, 852 boolean syncVM) { 853 Objects.requireNonNull(other); 854 Objects.requireNonNull(pn); 855 856 // all packages are open in unnamed, open, and automatic modules 857 if (!isNamed() || descriptor.isOpen() || descriptor.isAutomatic()) 858 return; 859 860 // check if the package is already exported/open to other 861 if (implIsExportedOrOpen(pn, other, open)) { 862 863 // if the package is exported/open for illegal access then we need 864 // to record that it has also been exported/opened reflectively so 865 // that the IllegalAccessLogger doesn't emit a warning. 866 boolean needToAdd = false; 867 if (!other.isNamed()) { 868 IllegalAccessLogger l = IllegalAccessLogger.illegalAccessLogger(); 869 if (l != null) { 870 if (open) { 871 needToAdd = l.isOpenForIllegalAccess(this, pn); 872 } else { 873 needToAdd = l.isExportedForIllegalAccess(this, pn); 874 } 875 } 876 } 877 if (!needToAdd) { 878 // nothing to do 879 return; 880 } 881 } 882 883 // can only export a package in the module 884 if (!descriptor.packages().contains(pn)) { 885 throw new IllegalArgumentException("package " + pn 886 + " not in contents"); 887 } 888 889 // update VM first, just in case it fails 890 if (syncVM) { 891 if (other == EVERYONE_MODULE) { 892 addExportsToAll0(this, pn); 893 } else if (other == ALL_UNNAMED_MODULE) { 894 addExportsToAllUnnamed0(this, pn); 895 } else { 896 addExports0(this, pn, other); 897 } 898 } 899 900 // add package name to exports if absent 901 Map<String, Boolean> map = ReflectionData.exports 902 .computeIfAbsent(this, other, 903 (m1, m2) -> new ConcurrentHashMap<>()); 904 if (open) { 905 map.put(pn, Boolean.TRUE); // may need to promote from FALSE to TRUE 906 } else { 907 map.putIfAbsent(pn, Boolean.FALSE); 908 } 909 } 910 911 /** 912 * Updates a module to open all packages returned by the given iterator to 913 * all unnamed modules. 914 * 915 * @apiNote Used during startup to open packages for illegal access. 916 */ implAddOpensToAllUnnamed(Iterator<String> iterator)917 void implAddOpensToAllUnnamed(Iterator<String> iterator) { 918 if (jdk.internal.misc.VM.isModuleSystemInited()) { 919 throw new IllegalStateException("Module system already initialized"); 920 } 921 922 // replace this module's openPackages map with a new map that opens 923 // the packages to all unnamed modules. 924 Map<String, Set<Module>> openPackages = this.openPackages; 925 if (openPackages == null) { 926 openPackages = new HashMap<>(); 927 } else { 928 openPackages = new HashMap<>(openPackages); 929 } 930 while (iterator.hasNext()) { 931 String pn = iterator.next(); 932 Set<Module> prev = openPackages.putIfAbsent(pn, ALL_UNNAMED_MODULE_SET); 933 if (prev != null) { 934 prev.add(ALL_UNNAMED_MODULE); 935 } 936 937 // update VM to export the package 938 addExportsToAllUnnamed0(this, pn); 939 } 940 this.openPackages = openPackages; 941 } 942 943 944 // -- services -- 945 946 /** 947 * If the caller's module is this module then update this module to add a 948 * service dependence on the given service type. This method is intended 949 * for use by frameworks that invoke {@link java.util.ServiceLoader 950 * ServiceLoader} on behalf of other modules or where the framework is 951 * passed a reference to the service type by other code. This method is 952 * a no-op when invoked on an unnamed module or an automatic module. 953 * 954 * <p> This method does not cause {@link Configuration#resolveAndBind 955 * resolveAndBind} to be re-run. </p> 956 * 957 * @param service 958 * The service type 959 * 960 * @return this module 961 * 962 * @throws IllegalCallerException 963 * If this is a named module and the caller's module is not this 964 * module 965 * 966 * @see #canUse(Class) 967 * @see ModuleDescriptor#uses() 968 */ 969 @CallerSensitive addUses(Class<?> service)970 public Module addUses(Class<?> service) { 971 Objects.requireNonNull(service); 972 973 if (isNamed() && !descriptor.isAutomatic()) { 974 Module caller = getCallerModule(Reflection.getCallerClass()); 975 if (caller != this) { 976 throw new IllegalCallerException(caller + " != " + this); 977 } 978 implAddUses(service); 979 } 980 981 return this; 982 } 983 984 /** 985 * Update this module to add a service dependence on the given service 986 * type. 987 */ implAddUses(Class<?> service)988 void implAddUses(Class<?> service) { 989 if (!canUse(service)) { 990 ReflectionData.uses.putIfAbsent(this, service, Boolean.TRUE); 991 } 992 } 993 994 995 /** 996 * Indicates if this module has a service dependence on the given service 997 * type. This method always returns {@code true} when invoked on an unnamed 998 * module or an automatic module. 999 * 1000 * @param service 1001 * The service type 1002 * 1003 * @return {@code true} if this module uses service type {@code st} 1004 * 1005 * @see #addUses(Class) 1006 */ canUse(Class<?> service)1007 public boolean canUse(Class<?> service) { 1008 Objects.requireNonNull(service); 1009 1010 if (!isNamed()) 1011 return true; 1012 1013 if (descriptor.isAutomatic()) 1014 return true; 1015 1016 // uses was declared 1017 if (descriptor.uses().contains(service.getName())) 1018 return true; 1019 1020 // uses added via addUses 1021 return ReflectionData.uses.containsKeyPair(this, service); 1022 } 1023 1024 1025 1026 // -- packages -- 1027 1028 /** 1029 * Returns the set of package names for the packages in this module. 1030 * 1031 * <p> For named modules, the returned set contains an element for each 1032 * package in the module. </p> 1033 * 1034 * <p> For unnamed modules, this method is the equivalent to invoking the 1035 * {@link ClassLoader#getDefinedPackages() getDefinedPackages} method of 1036 * this module's class loader and returning the set of package names. </p> 1037 * 1038 * @return the set of the package names of the packages in this module 1039 */ getPackages()1040 public Set<String> getPackages() { 1041 if (isNamed()) { 1042 return descriptor.packages(); 1043 } else { 1044 // unnamed module 1045 Stream<Package> packages; 1046 if (loader == null) { 1047 packages = BootLoader.packages(); 1048 } else { 1049 packages = loader.packages(); 1050 } 1051 return packages.map(Package::getName).collect(Collectors.toSet()); 1052 } 1053 } 1054 1055 1056 // -- creating Module objects -- 1057 1058 /** 1059 * Defines all module in a configuration to the runtime. 1060 * 1061 * @return a map of module name to runtime {@code Module} 1062 * 1063 * @throws IllegalArgumentException 1064 * If the function maps a module to the null or platform class loader 1065 * @throws IllegalStateException 1066 * If the module cannot be defined to the VM or its packages overlap 1067 * with another module mapped to the same class loader 1068 */ defineModules(Configuration cf, Function<String, ClassLoader> clf, ModuleLayer layer)1069 static Map<String, Module> defineModules(Configuration cf, 1070 Function<String, ClassLoader> clf, 1071 ModuleLayer layer) 1072 { 1073 boolean isBootLayer = (ModuleLayer.boot() == null); 1074 1075 int cap = (int)(cf.modules().size() / 0.75f + 1.0f); 1076 Map<String, Module> nameToModule = new HashMap<>(cap); 1077 Map<String, ClassLoader> nameToLoader = new HashMap<>(cap); 1078 1079 Set<ClassLoader> loaders = new HashSet<>(); 1080 boolean hasPlatformModules = false; 1081 1082 // map each module to a class loader 1083 for (ResolvedModule resolvedModule : cf.modules()) { 1084 String name = resolvedModule.name(); 1085 ClassLoader loader = clf.apply(name); 1086 nameToLoader.put(name, loader); 1087 if (loader == null || loader == ClassLoaders.platformClassLoader()) { 1088 if (!(clf instanceof ModuleLoaderMap.Mapper)) { 1089 throw new IllegalArgumentException("loader can't be 'null'" 1090 + " or the platform class loader"); 1091 } 1092 hasPlatformModules = true; 1093 } else { 1094 loaders.add(loader); 1095 } 1096 } 1097 1098 // define each module in the configuration to the VM 1099 for (ResolvedModule resolvedModule : cf.modules()) { 1100 ModuleReference mref = resolvedModule.reference(); 1101 ModuleDescriptor descriptor = mref.descriptor(); 1102 String name = descriptor.name(); 1103 ClassLoader loader = nameToLoader.get(name); 1104 Module m; 1105 if (loader == null && name.equals("java.base")) { 1106 // java.base is already defined to the VM 1107 m = Object.class.getModule(); 1108 } else { 1109 URI uri = mref.location().orElse(null); 1110 m = new Module(layer, loader, descriptor, uri); 1111 } 1112 nameToModule.put(name, m); 1113 } 1114 1115 // setup readability and exports/opens 1116 for (ResolvedModule resolvedModule : cf.modules()) { 1117 ModuleReference mref = resolvedModule.reference(); 1118 ModuleDescriptor descriptor = mref.descriptor(); 1119 1120 String mn = descriptor.name(); 1121 Module m = nameToModule.get(mn); 1122 assert m != null; 1123 1124 // reads 1125 Set<Module> reads = new HashSet<>(); 1126 1127 // name -> source Module when in parent layer 1128 Map<String, Module> nameToSource = Map.of(); 1129 1130 for (ResolvedModule other : resolvedModule.reads()) { 1131 Module m2 = null; 1132 if (other.configuration() == cf) { 1133 // this configuration 1134 m2 = nameToModule.get(other.name()); 1135 assert m2 != null; 1136 } else { 1137 // parent layer 1138 for (ModuleLayer parent: layer.parents()) { 1139 m2 = findModule(parent, other); 1140 if (m2 != null) 1141 break; 1142 } 1143 assert m2 != null; 1144 if (nameToSource.isEmpty()) 1145 nameToSource = new HashMap<>(); 1146 nameToSource.put(other.name(), m2); 1147 } 1148 reads.add(m2); 1149 1150 // update VM view 1151 addReads0(m, m2); 1152 } 1153 m.reads = reads; 1154 1155 // automatic modules read all unnamed modules 1156 if (descriptor.isAutomatic()) { 1157 m.implAddReads(ALL_UNNAMED_MODULE, true); 1158 } 1159 1160 // exports and opens, skipped for open and automatic 1161 if (!descriptor.isOpen() && !descriptor.isAutomatic()) { 1162 if (isBootLayer && descriptor.opens().isEmpty()) { 1163 // no open packages, no qualified exports to modules in parent layers 1164 initExports(m, nameToModule); 1165 } else { 1166 initExportsAndOpens(m, nameToSource, nameToModule, layer.parents()); 1167 } 1168 } 1169 } 1170 1171 // if there are modules defined to the boot or platform class loaders 1172 // then register the modules in the class loader's services catalog 1173 if (hasPlatformModules) { 1174 ClassLoader pcl = ClassLoaders.platformClassLoader(); 1175 ServicesCatalog bootCatalog = BootLoader.getServicesCatalog(); 1176 ServicesCatalog pclCatalog = ServicesCatalog.getServicesCatalog(pcl); 1177 for (ResolvedModule resolvedModule : cf.modules()) { 1178 ModuleReference mref = resolvedModule.reference(); 1179 ModuleDescriptor descriptor = mref.descriptor(); 1180 if (!descriptor.provides().isEmpty()) { 1181 String name = descriptor.name(); 1182 Module m = nameToModule.get(name); 1183 ClassLoader loader = nameToLoader.get(name); 1184 if (loader == null) { 1185 bootCatalog.register(m); 1186 } else if (loader == pcl) { 1187 pclCatalog.register(m); 1188 } 1189 } 1190 } 1191 } 1192 1193 // record that there is a layer with modules defined to the class loader 1194 for (ClassLoader loader : loaders) { 1195 layer.bindToLoader(loader); 1196 } 1197 1198 return nameToModule; 1199 } 1200 1201 /** 1202 * Find the runtime Module corresponding to the given ResolvedModule 1203 * in the given parent layer (or its parents). 1204 */ findModule(ModuleLayer parent, ResolvedModule resolvedModule)1205 private static Module findModule(ModuleLayer parent, 1206 ResolvedModule resolvedModule) { 1207 Configuration cf = resolvedModule.configuration(); 1208 String dn = resolvedModule.name(); 1209 return parent.layers() 1210 .filter(l -> l.configuration() == cf) 1211 .findAny() 1212 .map(layer -> { 1213 Optional<Module> om = layer.findModule(dn); 1214 assert om.isPresent() : dn + " not found in layer"; 1215 Module m = om.get(); 1216 assert m.getLayer() == layer : m + " not in expected layer"; 1217 return m; 1218 }) 1219 .orElse(null); 1220 } 1221 1222 /** 1223 * Initialize/setup a module's exports. 1224 * 1225 * @param m the module 1226 * @param nameToModule map of module name to Module (for qualified exports) 1227 */ initExports(Module m, Map<String, Module> nameToModule)1228 private static void initExports(Module m, Map<String, Module> nameToModule) { 1229 Map<String, Set<Module>> exportedPackages = new HashMap<>(); 1230 1231 for (Exports exports : m.getDescriptor().exports()) { 1232 String source = exports.source(); 1233 if (exports.isQualified()) { 1234 // qualified exports 1235 Set<Module> targets = new HashSet<>(); 1236 for (String target : exports.targets()) { 1237 Module m2 = nameToModule.get(target); 1238 if (m2 != null) { 1239 addExports0(m, source, m2); 1240 targets.add(m2); 1241 } 1242 } 1243 if (!targets.isEmpty()) { 1244 exportedPackages.put(source, targets); 1245 } 1246 } else { 1247 // unqualified exports 1248 addExportsToAll0(m, source); 1249 exportedPackages.put(source, EVERYONE_SET); 1250 } 1251 } 1252 1253 if (!exportedPackages.isEmpty()) 1254 m.exportedPackages = exportedPackages; 1255 } 1256 1257 /** 1258 * Initialize/setup a module's exports. 1259 * 1260 * @param m the module 1261 * @param nameToSource map of module name to Module for modules that m reads 1262 * @param nameToModule map of module name to Module for modules in the layer 1263 * under construction 1264 * @param parents the parent layers 1265 */ initExportsAndOpens(Module m, Map<String, Module> nameToSource, Map<String, Module> nameToModule, List<ModuleLayer> parents)1266 private static void initExportsAndOpens(Module m, 1267 Map<String, Module> nameToSource, 1268 Map<String, Module> nameToModule, 1269 List<ModuleLayer> parents) { 1270 ModuleDescriptor descriptor = m.getDescriptor(); 1271 Map<String, Set<Module>> openPackages = new HashMap<>(); 1272 Map<String, Set<Module>> exportedPackages = new HashMap<>(); 1273 1274 // process the open packages first 1275 for (Opens opens : descriptor.opens()) { 1276 String source = opens.source(); 1277 1278 if (opens.isQualified()) { 1279 // qualified opens 1280 Set<Module> targets = new HashSet<>(); 1281 for (String target : opens.targets()) { 1282 Module m2 = findModule(target, nameToSource, nameToModule, parents); 1283 if (m2 != null) { 1284 addExports0(m, source, m2); 1285 targets.add(m2); 1286 } 1287 } 1288 if (!targets.isEmpty()) { 1289 openPackages.put(source, targets); 1290 } 1291 } else { 1292 // unqualified opens 1293 addExportsToAll0(m, source); 1294 openPackages.put(source, EVERYONE_SET); 1295 } 1296 } 1297 1298 // next the exports, skipping exports when the package is open 1299 for (Exports exports : descriptor.exports()) { 1300 String source = exports.source(); 1301 1302 // skip export if package is already open to everyone 1303 Set<Module> openToTargets = openPackages.get(source); 1304 if (openToTargets != null && openToTargets.contains(EVERYONE_MODULE)) 1305 continue; 1306 1307 if (exports.isQualified()) { 1308 // qualified exports 1309 Set<Module> targets = new HashSet<>(); 1310 for (String target : exports.targets()) { 1311 Module m2 = findModule(target, nameToSource, nameToModule, parents); 1312 if (m2 != null) { 1313 // skip qualified export if already open to m2 1314 if (openToTargets == null || !openToTargets.contains(m2)) { 1315 addExports0(m, source, m2); 1316 targets.add(m2); 1317 } 1318 } 1319 } 1320 if (!targets.isEmpty()) { 1321 exportedPackages.put(source, targets); 1322 } 1323 } else { 1324 // unqualified exports 1325 addExportsToAll0(m, source); 1326 exportedPackages.put(source, EVERYONE_SET); 1327 } 1328 } 1329 1330 if (!openPackages.isEmpty()) 1331 m.openPackages = openPackages; 1332 if (!exportedPackages.isEmpty()) 1333 m.exportedPackages = exportedPackages; 1334 } 1335 1336 /** 1337 * Find the runtime Module with the given name. The module name is the 1338 * name of a target module in a qualified exports or opens directive. 1339 * 1340 * @param target The target module to find 1341 * @param nameToSource The modules in parent layers that are read 1342 * @param nameToModule The modules in the layer under construction 1343 * @param parents The parent layers 1344 */ findModule(String target, Map<String, Module> nameToSource, Map<String, Module> nameToModule, List<ModuleLayer> parents)1345 private static Module findModule(String target, 1346 Map<String, Module> nameToSource, 1347 Map<String, Module> nameToModule, 1348 List<ModuleLayer> parents) { 1349 Module m = nameToSource.get(target); 1350 if (m == null) { 1351 m = nameToModule.get(target); 1352 if (m == null) { 1353 for (ModuleLayer parent : parents) { 1354 m = parent.findModule(target).orElse(null); 1355 if (m != null) break; 1356 } 1357 } 1358 } 1359 return m; 1360 } 1361 1362 1363 // -- annotations -- 1364 1365 /** 1366 * {@inheritDoc} 1367 * This method returns {@code null} when invoked on an unnamed module. 1368 */ 1369 @Override getAnnotation(Class<T> annotationClass)1370 public <T extends Annotation> T getAnnotation(Class<T> annotationClass) { 1371 return moduleInfoClass().getDeclaredAnnotation(annotationClass); 1372 } 1373 1374 /** 1375 * {@inheritDoc} 1376 * This method returns an empty array when invoked on an unnamed module. 1377 */ 1378 @Override getAnnotations()1379 public Annotation[] getAnnotations() { 1380 return moduleInfoClass().getAnnotations(); 1381 } 1382 1383 /** 1384 * {@inheritDoc} 1385 * This method returns an empty array when invoked on an unnamed module. 1386 */ 1387 @Override getDeclaredAnnotations()1388 public Annotation[] getDeclaredAnnotations() { 1389 return moduleInfoClass().getDeclaredAnnotations(); 1390 } 1391 1392 // cached class file with annotations 1393 private volatile Class<?> moduleInfoClass; 1394 moduleInfoClass()1395 private Class<?> moduleInfoClass() { 1396 Class<?> clazz = this.moduleInfoClass; 1397 if (clazz != null) 1398 return clazz; 1399 1400 synchronized (this) { 1401 clazz = this.moduleInfoClass; 1402 if (clazz == null) { 1403 if (isNamed()) { 1404 PrivilegedAction<Class<?>> pa = this::loadModuleInfoClass; 1405 clazz = AccessController.doPrivileged(pa); 1406 } 1407 if (clazz == null) { 1408 class DummyModuleInfo { } 1409 clazz = DummyModuleInfo.class; 1410 } 1411 this.moduleInfoClass = clazz; 1412 } 1413 return clazz; 1414 } 1415 } 1416 loadModuleInfoClass()1417 private Class<?> loadModuleInfoClass() { 1418 Class<?> clazz = null; 1419 try (InputStream in = getResourceAsStream("module-info.class")) { 1420 if (in != null) 1421 clazz = loadModuleInfoClass(in); 1422 } catch (Exception ignore) { } 1423 return clazz; 1424 } 1425 1426 /** 1427 * Loads module-info.class as a package-private interface in a class loader 1428 * that is a child of this module's class loader. 1429 */ loadModuleInfoClass(InputStream in)1430 private Class<?> loadModuleInfoClass(InputStream in) throws IOException { 1431 final String MODULE_INFO = "module-info"; 1432 1433 ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS 1434 + ClassWriter.COMPUTE_FRAMES); 1435 1436 ClassVisitor cv = new ClassVisitor(Opcodes.ASM7, cw) { 1437 @Override 1438 public void visit(int version, 1439 int access, 1440 String name, 1441 String signature, 1442 String superName, 1443 String[] interfaces) { 1444 cw.visit(version, 1445 Opcodes.ACC_INTERFACE 1446 + Opcodes.ACC_ABSTRACT 1447 + Opcodes.ACC_SYNTHETIC, 1448 MODULE_INFO, 1449 null, 1450 "java/lang/Object", 1451 null); 1452 } 1453 @Override 1454 public AnnotationVisitor visitAnnotation(String desc, boolean visible) { 1455 // keep annotations 1456 return super.visitAnnotation(desc, visible); 1457 } 1458 @Override 1459 public void visitAttribute(Attribute attr) { 1460 // drop non-annotation attributes 1461 } 1462 @Override 1463 public ModuleVisitor visitModule(String name, int flags, String version) { 1464 // drop Module attribute 1465 return null; 1466 } 1467 }; 1468 1469 ClassReader cr = new ClassReader(in); 1470 cr.accept(cv, 0); 1471 byte[] bytes = cw.toByteArray(); 1472 1473 ClassLoader cl = new ClassLoader(loader) { 1474 @Override 1475 protected Class<?> findClass(String cn)throws ClassNotFoundException { 1476 if (cn.equals(MODULE_INFO)) { 1477 return super.defineClass(cn, bytes, 0, bytes.length); 1478 } else { 1479 throw new ClassNotFoundException(cn); 1480 } 1481 } 1482 }; 1483 1484 try { 1485 return cl.loadClass(MODULE_INFO); 1486 } catch (ClassNotFoundException e) { 1487 throw new InternalError(e); 1488 } 1489 } 1490 1491 1492 // -- misc -- 1493 1494 1495 /** 1496 * Returns an input stream for reading a resource in this module. 1497 * The {@code name} parameter is a {@code '/'}-separated path name that 1498 * identifies the resource. As with {@link Class#getResourceAsStream 1499 * Class.getResourceAsStream}, this method delegates to the module's class 1500 * loader {@link ClassLoader#findResource(String,String) 1501 * findResource(String,String)} method, invoking it with the module name 1502 * (or {@code null} when the module is unnamed) and the name of the 1503 * resource. If the resource name has a leading slash then it is dropped 1504 * before delegation. 1505 * 1506 * <p> A resource in a named module may be <em>encapsulated</em> so that 1507 * it cannot be located by code in other modules. Whether a resource can be 1508 * located or not is determined as follows: </p> 1509 * 1510 * <ul> 1511 * <li> If the resource name ends with "{@code .class}" then it is not 1512 * encapsulated. </li> 1513 * 1514 * <li> A <em>package name</em> is derived from the resource name. If 1515 * the package name is a {@linkplain #getPackages() package} in the 1516 * module then the resource can only be located by the caller of this 1517 * method when the package is {@linkplain #isOpen(String,Module) open} 1518 * to at least the caller's module. If the resource is not in a 1519 * package in the module then the resource is not encapsulated. </li> 1520 * </ul> 1521 * 1522 * <p> In the above, the <em>package name</em> for a resource is derived 1523 * from the subsequence of characters that precedes the last {@code '/'} in 1524 * the name and then replacing each {@code '/'} character in the subsequence 1525 * with {@code '.'}. A leading slash is ignored when deriving the package 1526 * name. As an example, the package name derived for a resource named 1527 * "{@code a/b/c/foo.properties}" is "{@code a.b.c}". A resource name 1528 * with the name "{@code META-INF/MANIFEST.MF}" is never encapsulated 1529 * because "{@code META-INF}" is not a legal package name. </p> 1530 * 1531 * <p> This method returns {@code null} if the resource is not in this 1532 * module, the resource is encapsulated and cannot be located by the caller, 1533 * or access to the resource is denied by the security manager. </p> 1534 * 1535 * @param name 1536 * The resource name 1537 * 1538 * @return An input stream for reading the resource or {@code null} 1539 * 1540 * @throws IOException 1541 * If an I/O error occurs 1542 * 1543 * @see Class#getResourceAsStream(String) 1544 */ 1545 @CallerSensitive getResourceAsStream(String name)1546 public InputStream getResourceAsStream(String name) throws IOException { 1547 if (name.startsWith("/")) { 1548 name = name.substring(1); 1549 } 1550 1551 if (isNamed() && Resources.canEncapsulate(name)) { 1552 Module caller = getCallerModule(Reflection.getCallerClass()); 1553 if (caller != this && caller != Object.class.getModule()) { 1554 String pn = Resources.toPackageName(name); 1555 if (getPackages().contains(pn)) { 1556 if (caller == null && !isOpen(pn)) { 1557 // no caller, package not open 1558 return null; 1559 } 1560 if (!isOpen(pn, caller)) { 1561 // package not open to caller 1562 return null; 1563 } 1564 } 1565 } 1566 } 1567 1568 String mn = this.name; 1569 1570 // special-case built-in class loaders to avoid URL connection 1571 if (loader == null) { 1572 return BootLoader.findResourceAsStream(mn, name); 1573 } else if (loader instanceof BuiltinClassLoader) { 1574 return ((BuiltinClassLoader) loader).findResourceAsStream(mn, name); 1575 } 1576 1577 // locate resource in module 1578 URL url = loader.findResource(mn, name); 1579 if (url != null) { 1580 try { 1581 return url.openStream(); 1582 } catch (SecurityException e) { } 1583 } 1584 1585 return null; 1586 } 1587 1588 /** 1589 * Returns the string representation of this module. For a named module, 1590 * the representation is the string {@code "module"}, followed by a space, 1591 * and then the module name. For an unnamed module, the representation is 1592 * the string {@code "unnamed module"}, followed by a space, and then an 1593 * implementation specific string that identifies the unnamed module. 1594 * 1595 * @return The string representation of this module 1596 */ 1597 @Override toString()1598 public String toString() { 1599 if (isNamed()) { 1600 return "module " + name; 1601 } else { 1602 String id = Integer.toHexString(System.identityHashCode(this)); 1603 return "unnamed module @" + id; 1604 } 1605 } 1606 1607 /** 1608 * Returns the module that a given caller class is a member of. Returns 1609 * {@code null} if the caller is {@code null}. 1610 */ getCallerModule(Class<?> caller)1611 private Module getCallerModule(Class<?> caller) { 1612 return (caller != null) ? caller.getModule() : null; 1613 } 1614 1615 1616 // -- native methods -- 1617 1618 // JVM_DefineModule defineModule0(Module module, boolean isOpen, String version, String location, String[] pns)1619 private static native void defineModule0(Module module, 1620 boolean isOpen, 1621 String version, 1622 String location, 1623 String[] pns); 1624 1625 // JVM_AddReadsModule addReads0(Module from, Module to)1626 private static native void addReads0(Module from, Module to); 1627 1628 // JVM_AddModuleExports addExports0(Module from, String pn, Module to)1629 private static native void addExports0(Module from, String pn, Module to); 1630 1631 // JVM_AddModuleExportsToAll addExportsToAll0(Module from, String pn)1632 private static native void addExportsToAll0(Module from, String pn); 1633 1634 // JVM_AddModuleExportsToAllUnnamed addExportsToAllUnnamed0(Module from, String pn)1635 private static native void addExportsToAllUnnamed0(Module from, String pn); 1636 } 1637