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