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