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