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