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