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