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