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