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         String[] packages = descriptor.packages().toArray(new String[0]);
 132         defineModule0(this, isOpen, vs, loc, packages);
 133     }
 134 
 135 
 136     /**
 137      * Create the unnamed Module for the given ClassLoader.
 138      *
 139      * @see ClassLoader#getUnnamedModule
 140      */
 141     private Module(ClassLoader loader) {
 142         this.layer = null;
 143         this.name = null;
 144         this.loader = loader;
 145         this.descriptor = null;
 146     }
 147 
 148 
 149     /**
 150      * Creates a named module but without defining the module to the VM.
 151      *
 152      * @apiNote This constructor is for VM white-box testing.
 153      */
 154     Module(ClassLoader loader, ModuleDescriptor descriptor) {
 155         this.layer = null;
 156         this.name = descriptor.name();
 157         this.loader = loader;
 158         this.descriptor = descriptor;
 159     }
 160 
 161 
 162 
 163     /**
 164      * Returns {@code true} if this module is a named module.
 165      *
 166      * @return {@code true} if this is a named module
 167      *
 168      * @see ClassLoader#getUnnamedModule()
 169      */
 170     public boolean isNamed() {
 171         return name != null;
 172     }
 173 
 174     /**
 175      * Returns the module name or {@code null} if this module is an unnamed
 176      * module.
 177      *
 178      * @return The module name
 179      */
 180     public String getName() {
 181         return name;
 182     }
 183 
 184     /**
 185      * Returns the {@code ClassLoader} for this module.
 186      *
 187      * <p> If there is a security manager then its {@code checkPermission}
 188      * method if first called with a {@code RuntimePermission("getClassLoader")}
 189      * permission to check that the caller is allowed to get access to the
 190      * class loader. </p>
 191      *
 192      * @return The class loader for this module
 193      *
 194      * @throws SecurityException
 195      *         If denied by the security manager
 196      */
 197     public ClassLoader getClassLoader() {
 198         SecurityManager sm = System.getSecurityManager();
 199         if (sm != null) {
 200             sm.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION);
 201         }
 202         return loader;
 203     }
 204 
 205     /**
 206      * Returns the module descriptor for this module or {@code null} if this
 207      * module is an unnamed module.
 208      *
 209      * @return The module descriptor for this module
 210      */
 211     public ModuleDescriptor getDescriptor() {
 212         return descriptor;
 213     }
 214 
 215     /**
 216      * Returns the layer that contains this module or {@code null} if this
 217      * module is not in a layer.
 218      *
 219      * A module {@code Layer} contains named modules and therefore this
 220      * method always returns {@code null} when invoked on an unnamed module.
 221      *
 222      * <p> <a href="Proxy.html#dynamicmodule">Dynamic modules</a> are named
 223      * modules that are generated at runtime. A dynamic module may or may
 224      * not be in a module Layer. </p>
 225      *
 226      * @return The layer that contains this module
 227      *
 228      * @see Proxy
 229      */
 230     public Layer getLayer() {
 231         if (isNamed()) {
 232             Layer layer = this.layer;
 233             if (layer != null)
 234                 return layer;
 235 
 236             // special-case java.base as it is created before the boot Layer
 237             if (loader == null && name.equals("java.base")) {
 238                 return SharedSecrets.getJavaLangAccess().getBootLayer();
 239             }
 240         }
 241 
 242         return null;
 243     }
 244 
 245 
 246     // --
 247 
 248     // special Module to mean "all unnamed modules"
 249     private static final Module ALL_UNNAMED_MODULE = new Module(null);
 250 
 251     // special Module to mean "everyone"
 252     private static final Module EVERYONE_MODULE = new Module(null);
 253 
 254     // set contains EVERYONE_MODULE, used when a package is opened or
 255     // exported unconditionally
 256     private static final Set<Module> EVERYONE_SET = Set.of(EVERYONE_MODULE);
 257 
 258 
 259     // -- readability --
 260 
 261     // the modules that this module reads
 262     private volatile Set<Module> reads;
 263 
 264     // additional module (2nd key) that some module (1st key) reflectively reads
 265     private static final WeakPairMap<Module, Module, Boolean> reflectivelyReads
 266         = new WeakPairMap<>();
 267 
 268 
 269     /**
 270      * Indicates if this module reads the given module. This method returns
 271      * {@code true} if invoked to test if this module reads itself. It also
 272      * returns {@code true} if invoked on an unnamed module (as unnamed
 273      * modules read all modules).
 274      *
 275      * @param  other
 276      *         The other module
 277      *
 278      * @return {@code true} if this module reads {@code other}
 279      *
 280      * @see #addReads(Module)
 281      */
 282     public boolean canRead(Module other) {
 283         Objects.requireNonNull(other);
 284 
 285         // an unnamed module reads all modules
 286         if (!this.isNamed())
 287             return true;
 288 
 289         // all modules read themselves
 290         if (other == this)
 291             return true;
 292 
 293         // check if this module reads other
 294         if (other.isNamed()) {
 295             Set<Module> reads = this.reads; // volatile read
 296             if (reads != null && reads.contains(other))
 297                 return true;
 298         }
 299 
 300         // check if this module reads the other module reflectively
 301         if (reflectivelyReads.containsKeyPair(this, other))
 302             return true;
 303 
 304         // if other is an unnamed module then check if this module reads
 305         // all unnamed modules
 306         if (!other.isNamed()
 307             && reflectivelyReads.containsKeyPair(this, ALL_UNNAMED_MODULE))
 308             return true;
 309 
 310         return false;
 311     }
 312 
 313     /**
 314      * If the caller's module is this module then update this module to read
 315      * the given module.
 316      *
 317      * This method is a no-op if {@code other} is this module (all modules read
 318      * themselves), this module is an unnamed module (as unnamed modules read
 319      * all modules), or this module already reads {@code other}.
 320      *
 321      * @implNote <em>Read edges</em> added by this method are <em>weak</em> and
 322      * do not prevent {@code other} from being GC'ed when this module is
 323      * strongly reachable.
 324      *
 325      * @param  other
 326      *         The other module
 327      *
 328      * @return this module
 329      *
 330      * @throws IllegalStateException
 331      *         If this is a named module and the caller is not this module
 332      *
 333      * @see #canRead
 334      */
 335     @CallerSensitive
 336     public Module addReads(Module other) {
 337         Objects.requireNonNull(other);
 338         if (this.isNamed()) {
 339             Module caller = Reflection.getCallerClass().getModule();
 340             if (caller != this) {
 341                 throw new IllegalStateException(caller + " != " + this);
 342             }
 343             implAddReads(other, true);
 344         }
 345         return this;
 346     }
 347 
 348     /**
 349      * Updates this module to read another module.
 350      *
 351      * @apiNote This method is for Proxy use and white-box testing.
 352      */
 353     void implAddReads(Module other) {
 354         implAddReads(other, true);
 355     }
 356 
 357     /**
 358      * Updates this module to read another module without notifying the VM.
 359      *
 360      * @apiNote This method is for VM white-box testing.
 361      */
 362     void implAddReadsNoSync(Module other) {
 363         implAddReads(other, false);
 364     }
 365 
 366     /**
 367      * Makes the given {@code Module} readable to this module.
 368      *
 369      * If {@code syncVM} is {@code true} then the VM is notified.
 370      */
 371     private void implAddReads(Module other, boolean syncVM) {
 372         Objects.requireNonNull(other);
 373 
 374         // nothing to do
 375         if (other == this || !this.isNamed())
 376             return;
 377 
 378         // check if we already read this module
 379         Set<Module> reads = this.reads;
 380         if (reads != null && reads.contains(other))
 381             return;
 382 
 383         // update VM first, just in case it fails
 384         if (syncVM) {
 385             if (other == ALL_UNNAMED_MODULE) {
 386                 addReads0(this, null);
 387             } else {
 388                 addReads0(this, other);
 389             }
 390         }
 391 
 392         // add reflective read
 393         reflectivelyReads.putIfAbsent(this, other, Boolean.TRUE);
 394     }
 395 
 396 
 397     // -- exported and open packages --
 398 
 399     // the packages are open to other modules, can be null
 400     // if the value contains EVERYONE_MODULE then the package is open to all
 401     private volatile Map<String, Set<Module>> openPackages;
 402 
 403     // the packages that are exported, can be null
 404     // if the value contains EVERYONE_MODULE then the package is exported to all
 405     private volatile Map<String, Set<Module>> exportedPackages;
 406 
 407     // additional exports or opens added at run-time
 408     // this module (1st key), other module (2nd key)
 409     // (package name, open?) (value)
 410     private static final WeakPairMap<Module, Module, Map<String, Boolean>>
 411         reflectivelyExports = new WeakPairMap<>();
 412 
 413 
 414     /**
 415      * Returns {@code true} if this module exports the given package to at
 416      * least the given module.
 417      *
 418      * <p> This method returns {@code true} if invoked to test if a package in
 419      * this module is exported to itself. It always returns {@code true} when
 420      * invoked on an unnamed module. A package that is {@link #isOpen open} to
 421      * the given module is considered exported to that module at run-time and
 422      * so this method returns {@code true} if the package is open to the given
 423      * module. </p>
 424      *
 425      * <p> This method does not check if the given module reads this module. </p>
 426      *
 427      * @param  pn
 428      *         The package name
 429      * @param  other
 430      *         The other module
 431      *
 432      * @return {@code true} if this module exports the package to at least the
 433      *         given module
 434      *
 435      * @see ModuleDescriptor#exports()
 436      * @see #addExports(String,Module)
 437      */
 438     public boolean isExported(String pn, Module other) {
 439         Objects.requireNonNull(pn);
 440         Objects.requireNonNull(other);
 441         return implIsExportedOrOpen(pn, other, /*open*/false);
 442     }
 443 
 444     /**
 445      * Returns {@code true} if this module has <em>opened</em> a package to at
 446      * least the given module.
 447      *
 448      * <p> This method returns {@code true} if invoked to test if a package in
 449      * this module is open to itself. It returns {@code true} when invoked on an
 450      * {@link ModuleDescriptor#isOpen open} module with a package in the module.
 451      * It always returns {@code true} when invoked on an unnamed module. </p>
 452      *
 453      * <p> This method does not check if the given module reads this module. </p>
 454      *
 455      * @param  pn
 456      *         The package name
 457      * @param  other
 458      *         The other module
 459      *
 460      * @return {@code true} if this module has <em>opened</em> the package
 461      *         to at least the given module
 462      *
 463      * @see ModuleDescriptor#opens()
 464      * @see #addOpens(String,Module)
 465      * @see AccessibleObject#setAccessible(boolean)
 466      * @see java.lang.invoke.MethodHandles#privateLookupIn
 467      */
 468     public boolean isOpen(String pn, Module other) {
 469         Objects.requireNonNull(pn);
 470         Objects.requireNonNull(other);
 471         return implIsExportedOrOpen(pn, other, /*open*/true);
 472     }
 473 
 474     /**
 475      * Returns {@code true} if this module exports the given package
 476      * unconditionally.
 477      *
 478      * <p> This method always returns {@code true} when invoked on an unnamed
 479      * module. A package that is {@link #isOpen(String) opened} unconditionally
 480      * is considered exported unconditionally at run-time and so this method
 481      * returns {@code true} if the package is opened unconditionally. </p>
 482      *
 483      * <p> This method does not check if the given module reads this module. </p>
 484      *
 485      * @param  pn
 486      *         The package name
 487      *
 488      * @return {@code true} if this module exports the package unconditionally
 489      *
 490      * @see ModuleDescriptor#exports()
 491      */
 492     public boolean isExported(String pn) {
 493         Objects.requireNonNull(pn);
 494         return implIsExportedOrOpen(pn, EVERYONE_MODULE, /*open*/false);
 495     }
 496 
 497     /**
 498      * Returns {@code true} if this module has <em>opened</em> a package
 499      * unconditionally.
 500      *
 501      * <p> This method always returns {@code true} when invoked on an unnamed
 502      * module. Additionally, it always returns {@code true} when invoked on an
 503      * {@link ModuleDescriptor#isOpen open} module with a package in the
 504      * module. </p>
 505      *
 506      * <p> This method does not check if the given module reads this module. </p>
 507      *
 508      * @param  pn
 509      *         The package name
 510      *
 511      * @return {@code true} if this module has <em>opened</em> the package
 512      *         unconditionally
 513      *
 514      * @see ModuleDescriptor#opens()
 515      */
 516     public boolean isOpen(String pn) {
 517         Objects.requireNonNull(pn);
 518         return implIsExportedOrOpen(pn, EVERYONE_MODULE, /*open*/true);
 519     }
 520 
 521 
 522     /**
 523      * Returns {@code true} if this module exports or opens the given package
 524      * to the given module. If the other module is {@code EVERYONE_MODULE} then
 525      * this method tests if the package is exported or opened unconditionally.
 526      */
 527     private boolean implIsExportedOrOpen(String pn, Module other, boolean open) {
 528         // all packages in unnamed modules are open
 529         if (!isNamed())
 530             return true;
 531 
 532         // all packages are exported/open to self
 533         if (other == this && containsPackage(pn))
 534             return true;
 535 
 536         // all packages in open modules are open
 537         if (descriptor.isOpen())
 538             return containsPackage(pn);
 539 
 540         // exported/opened via module declaration/descriptor
 541         if (isStaticallyExportedOrOpen(pn, other, open))
 542             return true;
 543 
 544         // exported via addExports/addOpens
 545         if (isReflectivelyExportedOrOpen(pn, other, open))
 546             return true;
 547 
 548         // not exported or open to other
 549         return false;
 550     }
 551 
 552     /**
 553      * Returns {@code true} if this module exports or opens a package to
 554      * the given module via its module declaration.
 555      */
 556     boolean isStaticallyExportedOrOpen(String pn, Module other, boolean open) {
 557         // package is open to everyone or <other>
 558         Map<String, Set<Module>> openPackages = this.openPackages;
 559         if (openPackages != null) {
 560             Set<Module> targets = openPackages.get(pn);
 561             if (targets != null) {
 562                 if (targets.contains(EVERYONE_MODULE))
 563                     return true;
 564                 if (other != EVERYONE_MODULE && targets.contains(other))
 565                     return true;
 566             }
 567         }
 568 
 569         if (!open) {
 570             // package is exported to everyone or <other>
 571             Map<String, Set<Module>> exportedPackages = this.exportedPackages;
 572             if (exportedPackages != null) {
 573                 Set<Module> targets = exportedPackages.get(pn);
 574                 if (targets != null) {
 575                     if (targets.contains(EVERYONE_MODULE))
 576                         return true;
 577                     if (other != EVERYONE_MODULE && targets.contains(other))
 578                         return true;
 579                 }
 580             }
 581         }
 582 
 583         return false;
 584     }
 585 
 586 
 587     /**
 588      * Returns {@code true} if this module reflectively exports or opens given
 589      * package package to the given module.
 590      */
 591     private boolean isReflectivelyExportedOrOpen(String pn, Module other, boolean open) {
 592         // exported or open to all modules
 593         Map<String, Boolean> exports = reflectivelyExports.get(this, EVERYONE_MODULE);
 594         if (exports != null) {
 595             Boolean b = exports.get(pn);
 596             if (b != null) {
 597                 boolean isOpen = b.booleanValue();
 598                 if (!open || isOpen) return true;
 599             }
 600         }
 601 
 602         if (other != EVERYONE_MODULE) {
 603 
 604             // exported or open to other
 605             exports = reflectivelyExports.get(this, other);
 606             if (exports != null) {
 607                 Boolean b = exports.get(pn);
 608                 if (b != null) {
 609                     boolean isOpen = b.booleanValue();
 610                     if (!open || isOpen) return true;
 611                 }
 612             }
 613 
 614             // other is an unnamed module && exported or open to all unnamed
 615             if (!other.isNamed()) {
 616                 exports = reflectivelyExports.get(this, ALL_UNNAMED_MODULE);
 617                 if (exports != null) {
 618                     Boolean b = exports.get(pn);
 619                     if (b != null) {
 620                         boolean isOpen = b.booleanValue();
 621                         if (!open || isOpen) return true;
 622                     }
 623                 }
 624             }
 625 
 626         }
 627 
 628         return false;
 629     }
 630 
 631 
 632     /**
 633      * If the caller's module is this module then update this module to export
 634      * the given package to the given module.
 635      *
 636      * <p> This method has no effect if the package is already exported (or
 637      * <em>open</em>) to the given module. It also has no effect if
 638      * invoked on an {@link ModuleDescriptor#isOpen open} module. </p>
 639      *
 640      * @apiNote As specified in section 5.4.3 of the <cite>The Java&trade;
 641      * Virtual Machine Specification </cite>, if an attempt to resolve a
 642      * symbolic reference fails because of a linkage error, then subsequent
 643      * attempts to resolve the reference always fail with the same error that
 644      * was thrown as a result of the initial resolution attempt.
 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      * @jvms 5.4.3 Resolution
 660      * @see #isExported(String,Module)
 661      */
 662     @CallerSensitive
 663     public Module addExports(String pn, Module other) {
 664         if (pn == null)
 665             throw new IllegalArgumentException("package is null");
 666         Objects.requireNonNull(other);
 667 
 668         if (isNamed() && !descriptor.isOpen()) {
 669             Module caller = Reflection.getCallerClass().getModule();
 670             if (caller != this) {
 671                 throw new IllegalStateException(caller + " != " + this);
 672             }
 673             implAddExportsOrOpens(pn, other, /*open*/false, /*syncVM*/true);
 674         }
 675 
 676         return this;
 677     }
 678 
 679     /**
 680      * If this module has <em>opened</em> a package to at least the caller
 681      * module then update this module to open the package to the given module.
 682      * Opening a package with this method allows all types in the package,
 683      * and all their members, not just public types and their public members,
 684      * to be reflected on by the given module when using APIs that support
 685      * private access or a way to bypass or suppress default Java language
 686      * access control checks.
 687      *
 688      * <p> This method has no effect if the package is already <em>open</em>
 689      * to the given module. It also has no effect if invoked on an {@link
 690      * ModuleDescriptor#isOpen open} module. </p>
 691      *
 692      * @param  pn
 693      *         The package name
 694      * @param  other
 695      *         The module
 696      *
 697      * @return this module
 698      *
 699      * @throws IllegalArgumentException
 700      *         If {@code pn} is {@code null}, or this is a named module and the
 701      *         package {@code pn} is not a package in this module
 702      * @throws IllegalStateException
 703      *         If this is a named module and this module has not opened the
 704      *         package to at least the caller
 705      *
 706      * @see #isOpen(String,Module)
 707      * @see AccessibleObject#setAccessible(boolean)
 708      * @see java.lang.invoke.MethodHandles#privateLookupIn
 709      */
 710     @CallerSensitive
 711     public Module addOpens(String pn, Module other) {
 712         if (pn == null)
 713             throw new IllegalArgumentException("package is null");
 714         Objects.requireNonNull(other);
 715 
 716         if (isNamed() && !descriptor.isOpen()) {
 717             Module caller = Reflection.getCallerClass().getModule();
 718             if (caller != this && !isOpen(pn, caller))
 719                 throw new IllegalStateException(pn + " is not open to " + caller);
 720             implAddExportsOrOpens(pn, other, /*open*/true, /*syncVM*/true);
 721         }
 722 
 723         return this;
 724     }
 725 
 726 
 727     /**
 728      * Updates the exports so that package {@code pn} is exported to module
 729      * {@code other} but without notifying the VM.
 730      *
 731      * @apiNote This method is for VM white-box testing.
 732      */
 733     void implAddExportsNoSync(String pn, Module other) {
 734         if (other == null)
 735             other = EVERYONE_MODULE;
 736         implAddExportsOrOpens(pn.replace('/', '.'), other, false, false);
 737     }
 738 
 739     /**
 740      * Updates the exports so that package {@code pn} is exported to module
 741      * {@code other}.
 742      *
 743      * @apiNote This method is for white-box testing.
 744      */
 745     void implAddExports(String pn, Module other) {
 746         implAddExportsOrOpens(pn, other, false, true);
 747     }
 748 
 749     /**
 750      * Updates the module to open package {@code pn} to module {@code other}.
 751      *
 752      * @apiNote This method is for white-box tests and jtreg
 753      */
 754     void implAddOpens(String pn, Module other) {
 755         implAddExportsOrOpens(pn, other, true, true);
 756     }
 757 
 758     /**
 759      * Updates a module to export or open a module to another module.
 760      *
 761      * If {@code syncVM} is {@code true} then the VM is notified.
 762      */
 763     private void implAddExportsOrOpens(String pn,
 764                                        Module other,
 765                                        boolean open,
 766                                        boolean syncVM) {
 767         Objects.requireNonNull(other);
 768         Objects.requireNonNull(pn);
 769 
 770         // all packages are open in unnamed and open modules
 771         if (!isNamed() || descriptor.isOpen())
 772             return;
 773 
 774         // nothing to do if already exported/open to other
 775         if (implIsExportedOrOpen(pn, other, open))
 776             return;
 777 
 778         // can only export a package in the module
 779         if (!containsPackage(pn)) {
 780             throw new IllegalArgumentException("package " + pn
 781                                                + " not in contents");
 782         }
 783 
 784         // update VM first, just in case it fails
 785         if (syncVM) {
 786             if (other == EVERYONE_MODULE) {
 787                 addExportsToAll0(this, pn);
 788             } else if (other == ALL_UNNAMED_MODULE) {
 789                 addExportsToAllUnnamed0(this, pn);
 790             } else {
 791                 addExports0(this, pn, 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);
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                 addExportsToAll0(m, source);
1177             }
1178             return;
1179         }
1180 
1181         Map<String, Set<Module>> openPackages = new HashMap<>();
1182         Map<String, Set<Module>> exportedPackages = new HashMap<>();
1183 
1184         // process the open packages first
1185         for (Opens opens : descriptor.opens()) {
1186             String source = opens.source();
1187 
1188             if (opens.isQualified()) {
1189                 // qualified opens
1190                 Set<Module> targets = new HashSet<>();
1191                 for (String target : opens.targets()) {
1192                     // only open to modules that are in this configuration
1193                     Module m2 = nameToModule.get(target);
1194                     if (m2 != null) {
1195                         addExports0(m, source, m2);
1196                         targets.add(m2);
1197                     }
1198                 }
1199                 if (!targets.isEmpty()) {
1200                     openPackages.put(source, targets);
1201                 }
1202             } else {
1203                 // unqualified opens
1204                 addExportsToAll0(m, source);
1205                 openPackages.put(source, EVERYONE_SET);
1206             }
1207         }
1208 
1209         // next the exports, skipping exports when the package is open
1210         for (Exports exports : descriptor.exports()) {
1211             String source = exports.source();
1212 
1213             // skip export if package is already open to everyone
1214             Set<Module> openToTargets = openPackages.get(source);
1215             if (openToTargets != null && openToTargets.contains(EVERYONE_MODULE))
1216                 continue;
1217 
1218             if (exports.isQualified()) {
1219                 // qualified exports
1220                 Set<Module> targets = new HashSet<>();
1221                 for (String target : exports.targets()) {
1222                     // only export to modules that are in this configuration
1223                     Module m2 = nameToModule.get(target);
1224                     if (m2 != null) {
1225                         // skip qualified export if already open to m2
1226                         if (openToTargets == null || !openToTargets.contains(m2)) {
1227                             addExports0(m, source, m2);
1228                             targets.add(m2);
1229                         }
1230                     }
1231                 }
1232                 if (!targets.isEmpty()) {
1233                     exportedPackages.put(source, targets);
1234                 }
1235 
1236             } else {
1237                 // unqualified exports
1238                 addExportsToAll0(m, source);
1239                 exportedPackages.put(source, EVERYONE_SET);
1240             }
1241         }
1242 
1243         if (!openPackages.isEmpty())
1244             m.openPackages = openPackages;
1245         if (!exportedPackages.isEmpty())
1246             m.exportedPackages = exportedPackages;
1247     }
1248 
1249 
1250     // -- annotations --
1251 
1252     /**
1253      * {@inheritDoc}
1254      * This method returns {@code null} when invoked on an unnamed module.
1255      */
1256     @Override
1257     public <T extends Annotation> T getAnnotation(Class<T> annotationClass) {
1258         return moduleInfoClass().getDeclaredAnnotation(annotationClass);
1259     }
1260 
1261     /**
1262      * {@inheritDoc}
1263      * This method returns an empty array when invoked on an unnamed module.
1264      */
1265     @Override
1266     public Annotation[] getAnnotations() {
1267         return moduleInfoClass().getAnnotations();
1268     }
1269 
1270     /**
1271      * {@inheritDoc}
1272      * This method returns an empty array when invoked on an unnamed module.
1273      */
1274     @Override
1275     public Annotation[] getDeclaredAnnotations() {
1276         return moduleInfoClass().getDeclaredAnnotations();
1277     }
1278 
1279     // cached class file with annotations
1280     private volatile Class<?> moduleInfoClass;
1281 
1282     private Class<?> moduleInfoClass() {
1283         Class<?> clazz = this.moduleInfoClass;
1284         if (clazz != null)
1285             return clazz;
1286 
1287         synchronized (this) {
1288             clazz = this.moduleInfoClass;
1289             if (clazz == null) {
1290                 if (isNamed()) {
1291                     PrivilegedAction<Class<?>> pa = this::loadModuleInfoClass;
1292                     clazz = AccessController.doPrivileged(pa);
1293                 }
1294                 if (clazz == null) {
1295                     class DummyModuleInfo { }
1296                     clazz = DummyModuleInfo.class;
1297                 }
1298                 this.moduleInfoClass = clazz;
1299             }
1300             return clazz;
1301         }
1302     }
1303 
1304     private Class<?> loadModuleInfoClass() {
1305         Class<?> clazz = null;
1306         try (InputStream in = getResourceAsStream("module-info.class")) {
1307             if (in != null)
1308                 clazz = loadModuleInfoClass(in);
1309         } catch (Exception ignore) { }
1310         return clazz;
1311     }
1312 
1313     /**
1314      * Loads module-info.class as a package-private interface in a class loader
1315      * that is a child of this module's class loader.
1316      */
1317     private Class<?> loadModuleInfoClass(InputStream in) throws IOException {
1318         final String MODULE_INFO = "module-info";
1319 
1320         ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS
1321                                          + ClassWriter.COMPUTE_FRAMES);
1322 
1323         ClassVisitor cv = new ClassVisitor(Opcodes.ASM5, cw) {
1324             @Override
1325             public void visit(int version,
1326                               int access,
1327                               String name,
1328                               String signature,
1329                               String superName,
1330                               String[] interfaces) {
1331                 cw.visit(version,
1332                         Opcodes.ACC_INTERFACE
1333                             + Opcodes.ACC_ABSTRACT
1334                             + Opcodes.ACC_SYNTHETIC,
1335                         MODULE_INFO,
1336                         null,
1337                         "java/lang/Object",
1338                         null);
1339             }
1340             @Override
1341             public AnnotationVisitor visitAnnotation(String desc, boolean visible) {
1342                 // keep annotations
1343                 return super.visitAnnotation(desc, visible);
1344             }
1345             @Override
1346             public void visitAttribute(Attribute attr) {
1347                 // drop non-annotation attributes
1348             }
1349         };
1350 
1351         ClassReader cr = new ClassReader(in);
1352         cr.accept(cv, 0);
1353         byte[] bytes = cw.toByteArray();
1354 
1355         ClassLoader cl = new ClassLoader(loader) {
1356             @Override
1357             protected Class<?> findClass(String cn)throws ClassNotFoundException {
1358                 if (cn.equals(MODULE_INFO)) {
1359                     return super.defineClass(cn, bytes, 0, bytes.length);
1360                 } else {
1361                     throw new ClassNotFoundException(cn);
1362                 }
1363             }
1364         };
1365 
1366         try {
1367             return cl.loadClass(MODULE_INFO);
1368         } catch (ClassNotFoundException e) {
1369             throw new InternalError(e);
1370         }
1371     }
1372 
1373 
1374     // -- misc --
1375 
1376 
1377     /**
1378      * Returns an input stream for reading a resource in this module. The
1379      * {@code name} parameter is a {@code '/'}-separated path name that
1380      * identifies the resource.
1381      *
1382      * <p> A resource in a named modules may be <em>encapsulated</em> so that
1383      * it cannot be located by code in other modules. Whether a resource can be
1384      * located or not is determined as follows:
1385      *
1386      * <ul>
1387      *     <li> The <em>package name</em> of the resource is derived from the
1388      *     subsequence of characters that precedes the last {@code '/'} and then
1389      *     replacing each {@code '/'} character in the subsequence with
1390      *     {@code '.'}. For example, the package name derived for a resource
1391      *     named "{@code a/b/c/foo.properties}" is "{@code a.b.c}". </li>
1392      *
1393      *     <li> If the package name is a package in the module then the package
1394      *     must be {@link #isOpen open} the module of the caller of this method.
1395      *     If the package is not in the module then the resource is not
1396      *     encapsulated. Resources in the unnamed package or "{@code META-INF}",
1397      *     for example, are never encapsulated because they can never be
1398      *     packages in a named module. </li>
1399      *
1400      *     <li> As a special case, resources ending with "{@code .class}" are
1401      *     never encapsulated. </li>
1402      * </ul>
1403      *
1404      * <p> This method returns {@code null} if the resource is not in this
1405      * module, the resource is encapsulated and cannot be located by the caller,
1406      * or access to the resource is denied by the security manager.
1407      *
1408      * @param  name
1409      *         The resource name
1410      *
1411      * @return An input stream for reading the resource or {@code null}
1412      *
1413      * @throws IOException
1414      *         If an I/O error occurs
1415      *
1416      * @see java.lang.module.ModuleReader#open(String)
1417      */
1418     @CallerSensitive
1419     public InputStream getResourceAsStream(String name) throws IOException {
1420         Objects.requireNonNull(name);
1421 
1422         if (isNamed() && !ResourceHelper.isSimpleResource(name)) {
1423             Module caller = Reflection.getCallerClass().getModule();
1424             if (caller != this && caller != Object.class.getModule()) {
1425                 // ignore packages added for proxies via addPackage
1426                 Set<String> packages = getDescriptor().packages();
1427                 String pn = ResourceHelper.getPackageName(name);
1428                 if (packages.contains(pn) && !isOpen(pn, caller)) {
1429                     // resource is in package not open to caller
1430                     return null;
1431                 }
1432             }
1433         }
1434 
1435         String mn = this.name;
1436 
1437         // special-case built-in class loaders to avoid URL connection
1438         if (loader == null) {
1439             return BootLoader.findResourceAsStream(mn, name);
1440         } else if (loader instanceof BuiltinClassLoader) {
1441             return ((BuiltinClassLoader) loader).findResourceAsStream(mn, name);
1442         }
1443 
1444         // locate resource in module
1445         JavaLangAccess jla = SharedSecrets.getJavaLangAccess();
1446         URL url = jla.findResource(loader, mn, name);
1447         if (url != null) {
1448             try {
1449                 return url.openStream();
1450             } catch (SecurityException e) { }
1451         }
1452 
1453         return null;
1454     }
1455 
1456     /**
1457      * Returns the string representation of this module. For a named module,
1458      * the representation is the string {@code "module"}, followed by a space,
1459      * and then the module name. For an unnamed module, the representation is
1460      * the string {@code "unnamed module"}, followed by a space, and then an
1461      * implementation specific string that identifies the unnamed module.
1462      *
1463      * @return The string representation of this module
1464      */
1465     @Override
1466     public String toString() {
1467         if (isNamed()) {
1468             return "module " + name;
1469         } else {
1470             String id = Integer.toHexString(System.identityHashCode(this));
1471             return "unnamed module @" + id;
1472         }
1473     }
1474 
1475 
1476     // -- native methods --
1477 
1478     // JVM_DefineModule
1479     private static native void defineModule0(Module module,
1480                                              boolean isOpen,
1481                                              String version,
1482                                              String location,
1483                                              String[] pns);
1484 
1485     // JVM_AddReadsModule
1486     private static native void addReads0(Module from, Module to);
1487 
1488     // JVM_AddModuleExports
1489     private static native void addExports0(Module from, String pn, Module to);
1490 
1491     // JVM_AddModuleExportsToAll
1492     private static native void addExportsToAll0(Module from, String pn);
1493 
1494     // JVM_AddModuleExportsToAllUnnamed
1495     private static native void addExportsToAllUnnamed0(Module from, String pn);
1496 
1497     // JVM_AddModulePackage
1498     private static native void addPackage0(Module m, String pn);
1499 
1500     /**
1501      * Register shared secret to provide access to package-private methods
1502      */
1503     static {
1504         SharedSecrets.setJavaLangReflectModuleAccess(
1505             new JavaLangReflectModuleAccess() {
1506                 @Override
1507                 public Module defineUnnamedModule(ClassLoader loader) {
1508                     return new Module(loader);
1509                 }
1510                 @Override
1511                 public Module defineModule(ClassLoader loader,
1512                                            ModuleDescriptor descriptor,
1513                                            URI uri) {
1514                    return new Module(null, loader, descriptor, uri);
1515                 }
1516                 @Override
1517                 public void addReads(Module m1, Module m2) {
1518                     m1.implAddReads(m2, true);
1519                 }
1520                 @Override
1521                 public void addReadsAllUnnamed(Module m) {
1522                     m.implAddReads(Module.ALL_UNNAMED_MODULE);
1523                 }
1524                 @Override
1525                 public void addExports(Module m, String pn, Module other) {
1526                     m.implAddExportsOrOpens(pn, other, false, true);
1527                 }
1528                 @Override
1529                 public void addOpens(Module m, String pn, Module other) {
1530                     m.implAddExportsOrOpens(pn, other, true, true);
1531                 }
1532                 @Override
1533                 public void addExportsToAll(Module m, String pn) {
1534                     m.implAddExportsOrOpens(pn, Module.EVERYONE_MODULE, false, true);
1535                 }
1536                 @Override
1537                 public void addOpensToAll(Module m, String pn) {
1538                     m.implAddExportsOrOpens(pn, Module.EVERYONE_MODULE, true, true);
1539                 }
1540                 @Override
1541                 public void addExportsToAllUnnamed(Module m, String pn) {
1542                     m.implAddExportsOrOpens(pn, Module.ALL_UNNAMED_MODULE, false, true);
1543                 }
1544                 @Override
1545                 public void addOpensToAllUnnamed(Module m, String pn) {
1546                     m.implAddExportsOrOpens(pn, Module.ALL_UNNAMED_MODULE, true, true);
1547                 }
1548                 @Override
1549                 public void addUses(Module m, Class<?> service) {
1550                     m.implAddUses(service);
1551                 }
1552                 @Override
1553                 public void addPackage(Module m, String pn) {
1554                     m.implAddPackage(pn, true);
1555                 }
1556                 @Override
1557                 public ServicesCatalog getServicesCatalog(Layer layer) {
1558                     return layer.getServicesCatalog();
1559                 }
1560                 @Override
1561                 public Stream<Layer> layers(Layer layer) {
1562                     return layer.layers();
1563                 }
1564                 @Override
1565                 public Stream<Layer> layers(ClassLoader loader) {
1566                     return Layer.layers(loader);
1567                 }
1568                 @Override
1569                 public boolean isStaticallyExported(Module module, String pn, Module other) {
1570                     return module.isStaticallyExportedOrOpen(pn, other, false);
1571                 }
1572             });
1573     }
1574 }