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