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