1 /*
2  * Copyright (c) 2014, 2020, 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 jdk.internal.module;
27 
28 import java.io.File;
29 import java.io.PrintStream;
30 import java.lang.module.Configuration;
31 import java.lang.module.ModuleDescriptor;
32 import java.lang.module.ModuleFinder;
33 import java.lang.module.ModuleReference;
34 import java.lang.module.ResolvedModule;
35 import java.net.URI;
36 import java.nio.file.Path;
37 import java.util.ArrayList;
38 import java.util.Collections;
39 import java.util.HashMap;
40 import java.util.HashSet;
41 import java.util.Iterator;
42 import java.util.LinkedHashMap;
43 import java.util.List;
44 import java.util.Map;
45 import java.util.Objects;
46 import java.util.Optional;
47 import java.util.Set;
48 import java.util.function.Function;
49 import java.util.stream.Collectors;
50 
51 import jdk.internal.access.JavaLangAccess;
52 import jdk.internal.access.JavaLangModuleAccess;
53 import jdk.internal.access.SharedSecrets;
54 import jdk.internal.loader.BootLoader;
55 import jdk.internal.loader.BuiltinClassLoader;
56 import jdk.internal.loader.ClassLoaders;
57 import jdk.internal.misc.CDS;
58 import jdk.internal.perf.PerfCounter;
59 
60 /**
61  * Initializes/boots the module system.
62  *
63  * The {@link #boot() boot} method is called early in the startup to initialize
64  * the module system. In summary, the boot method creates a Configuration by
65  * resolving a set of module names specified via the launcher (or equivalent)
66  * -m and --add-modules options. The modules are located on a module path that
67  * is constructed from the upgrade module path, system modules, and application
68  * module path. The Configuration is instantiated as the boot layer with each
69  * module in the configuration defined to a class loader.
70  */
71 
72 public final class ModuleBootstrap {
ModuleBootstrap()73     private ModuleBootstrap() { }
74 
75     private static final String JAVA_BASE = "java.base";
76 
77     // the token for "all default modules"
78     private static final String ALL_DEFAULT = "ALL-DEFAULT";
79 
80     // the token for "all unnamed modules"
81     private static final String ALL_UNNAMED = "ALL-UNNAMED";
82 
83     // the token for "all system modules"
84     private static final String ALL_SYSTEM = "ALL-SYSTEM";
85 
86     // the token for "all modules on the module path"
87     private static final String ALL_MODULE_PATH = "ALL-MODULE-PATH";
88 
89     // access to java.lang/module
90     private static final JavaLangAccess JLA = SharedSecrets.getJavaLangAccess();
91     private static final JavaLangModuleAccess JLMA = SharedSecrets.getJavaLangModuleAccess();
92 
93     // The ModulePatcher for the initial configuration
94     private static final ModulePatcher patcher = initModulePatcher();
95 
96     /**
97      * Returns the ModulePatcher for the initial configuration.
98      */
patcher()99     public static ModulePatcher patcher() {
100         return patcher;
101     }
102 
103     // ModuleFinders for the initial configuration
104     private static volatile ModuleFinder unlimitedFinder;
105     private static volatile ModuleFinder limitedFinder;
106 
107     /**
108      * Returns the ModuleFinder for the initial configuration before
109      * observability is limited by the --limit-modules command line option.
110      *
111      * @apiNote Used to support locating modules {@code java.instrument} and
112      * {@code jdk.management.agent} modules when they are loaded dynamically.
113      */
unlimitedFinder()114     public static ModuleFinder unlimitedFinder() {
115         ModuleFinder finder = unlimitedFinder;
116         if (finder == null) {
117             return ModuleFinder.ofSystem();
118         } else {
119             return finder;
120         }
121     }
122 
123     /**
124      * Returns the ModuleFinder for the initial configuration.
125      *
126      * @apiNote Used to support "{@code java --list-modules}".
127      */
limitedFinder()128     public static ModuleFinder limitedFinder() {
129         ModuleFinder finder = limitedFinder;
130         if (finder == null) {
131             return unlimitedFinder();
132         } else {
133             return finder;
134         }
135     }
136 
137     /**
138      * Returns true if the archived boot layer can be used. The system properties
139      * are checked in the order that they are used by boot2.
140      */
canUseArchivedBootLayer()141     private static boolean canUseArchivedBootLayer() {
142         return getProperty("jdk.module.upgrade.path") == null &&
143                getProperty("jdk.module.path") == null &&
144                getProperty("jdk.module.patch.0") == null &&       // --patch-module
145                getProperty("jdk.module.main") == null &&          // --module
146                getProperty("jdk.module.addmods.0") == null  &&    // --add-modules
147                getProperty("jdk.module.limitmods") == null &&     // --limit-modules
148                getProperty("jdk.module.addreads.0") == null &&    // --add-reads
149                getProperty("jdk.module.addexports.0") == null &&  // --add-exports
150                getProperty("jdk.module.addopens.0") == null &&    // --add-opens
151                getProperty("jdk.module.illegalAccess") == null;   // --illegal-access
152     }
153 
154     /**
155      * Initialize the module system, returning the boot layer. The boot layer
156      * is obtained from the CDS archive if possible, otherwise it is generated
157      * from the module graph.
158      *
159      * @see java.lang.System#initPhase2(boolean, boolean)
160      */
boot()161     public static ModuleLayer boot() {
162         Counters.start();
163 
164         ModuleLayer bootLayer;
165         ArchivedBootLayer archivedBootLayer = ArchivedBootLayer.get();
166         if (archivedBootLayer != null) {
167             assert canUseArchivedBootLayer();
168             bootLayer = archivedBootLayer.bootLayer();
169             BootLoader.getUnnamedModule(); // trigger <clinit> of BootLoader.
170             CDS.defineArchivedModules(ClassLoaders.platformClassLoader(), ClassLoaders.appClassLoader());
171 
172             // assume boot layer has at least one module providing a service
173             // that is mapped to the application class loader.
174             JLA.bindToLoader(bootLayer, ClassLoaders.appClassLoader());
175         } else {
176             bootLayer = boot2();
177         }
178 
179         Counters.publish("jdk.module.boot.totalTime");
180         return bootLayer;
181     }
182 
boot2()183     private static ModuleLayer boot2() {
184         // Step 0: Command line options
185 
186         ModuleFinder upgradeModulePath = finderFor("jdk.module.upgrade.path");
187         ModuleFinder appModulePath = finderFor("jdk.module.path");
188         boolean isPatched = patcher.hasPatches();
189         String mainModule = System.getProperty("jdk.module.main");
190         Set<String> addModules = addModules();
191         Set<String> limitModules = limitModules();
192         String illegalAccess = getAndRemoveProperty("jdk.module.illegalAccess");
193 
194         PrintStream traceOutput = null;
195         String trace = getAndRemoveProperty("jdk.module.showModuleResolution");
196         if (trace != null && Boolean.parseBoolean(trace))
197             traceOutput = System.out;
198 
199         Counters.add("jdk.module.boot.0.commandLineTime");
200 
201         // Step 1: The observable system modules, either all system modules
202         // or the system modules pre-generated for the initial module (the
203         // initial module may be the unnamed module). If the system modules
204         // are pre-generated for the initial module then resolution can be
205         // skipped.
206 
207         SystemModules systemModules = null;
208         ModuleFinder systemModuleFinder;
209 
210         boolean haveModulePath = (appModulePath != null || upgradeModulePath != null);
211         boolean needResolution = true;
212         boolean canArchive = false;
213         boolean hasSplitPackages;
214         boolean hasIncubatorModules;
215 
216         // If the java heap was archived at CDS dump time and the environment
217         // at dump time matches the current environment then use the archived
218         // system modules and finder.
219         ArchivedModuleGraph archivedModuleGraph = ArchivedModuleGraph.get(mainModule);
220         if (archivedModuleGraph != null
221                 && !haveModulePath
222                 && addModules.isEmpty()
223                 && limitModules.isEmpty()
224                 && !isPatched
225                 && illegalAccess == null) {
226             systemModuleFinder = archivedModuleGraph.finder();
227             hasSplitPackages = archivedModuleGraph.hasSplitPackages();
228             hasIncubatorModules = archivedModuleGraph.hasIncubatorModules();
229             needResolution = (traceOutput != null);
230         } else {
231             if (!haveModulePath && addModules.isEmpty() && limitModules.isEmpty()) {
232                 systemModules = SystemModuleFinders.systemModules(mainModule);
233                 if (systemModules != null && !isPatched) {
234                     needResolution = (traceOutput != null);
235                     canArchive = true;
236                 }
237             }
238             if (systemModules == null) {
239                 // all system modules are observable
240                 systemModules = SystemModuleFinders.allSystemModules();
241             }
242             if (systemModules != null) {
243                 // images build
244                 systemModuleFinder = SystemModuleFinders.of(systemModules);
245             } else {
246                 // exploded build or testing
247                 systemModules = new ExplodedSystemModules();
248                 systemModuleFinder = SystemModuleFinders.ofSystem();
249             }
250 
251             hasSplitPackages = systemModules.hasSplitPackages();
252             hasIncubatorModules = systemModules.hasIncubatorModules();
253             // not using the archived module graph - avoid accidental use
254             archivedModuleGraph = null;
255         }
256 
257         Counters.add("jdk.module.boot.1.systemModulesTime");
258 
259         // Step 2: Define and load java.base. This patches all classes loaded
260         // to date so that they are members of java.base. Once java.base is
261         // loaded then resources in java.base are available for error messages
262         // needed from here on.
263 
264         ModuleReference base = systemModuleFinder.find(JAVA_BASE).orElse(null);
265         if (base == null)
266             throw new InternalError(JAVA_BASE + " not found");
267         URI baseUri = base.location().orElse(null);
268         if (baseUri == null)
269             throw new InternalError(JAVA_BASE + " does not have a location");
270         BootLoader.loadModule(base);
271         Modules.defineModule(null, base.descriptor(), baseUri);
272 
273         // Step 2a: Scan all modules when --validate-modules specified
274 
275         if (getAndRemoveProperty("jdk.module.validation") != null) {
276             int errors = ModulePathValidator.scanAllModules(System.out);
277             if (errors > 0) {
278                 fail("Validation of module path failed");
279             }
280         }
281 
282         Counters.add("jdk.module.boot.2.defineBaseTime");
283 
284         // Step 3: If resolution is needed then create the module finder and
285         // the set of root modules to resolve.
286 
287         ModuleFinder savedModuleFinder = null;
288         ModuleFinder finder;
289         Set<String> roots;
290         if (needResolution) {
291 
292             // upgraded modules override the modules in the run-time image
293             if (upgradeModulePath != null)
294                 systemModuleFinder = ModuleFinder.compose(upgradeModulePath,
295                                                           systemModuleFinder);
296 
297             // The module finder: [--upgrade-module-path] system [--module-path]
298             if (appModulePath != null) {
299                 finder = ModuleFinder.compose(systemModuleFinder, appModulePath);
300             } else {
301                 finder = systemModuleFinder;
302             }
303 
304             // The root modules to resolve
305             roots = new HashSet<>();
306 
307             // launcher -m option to specify the main/initial module
308             if (mainModule != null)
309                 roots.add(mainModule);
310 
311             // additional module(s) specified by --add-modules
312             boolean addAllDefaultModules = false;
313             boolean addAllSystemModules = false;
314             boolean addAllApplicationModules = false;
315             for (String mod : addModules) {
316                 switch (mod) {
317                     case ALL_DEFAULT:
318                         addAllDefaultModules = true;
319                         break;
320                     case ALL_SYSTEM:
321                         addAllSystemModules = true;
322                         break;
323                     case ALL_MODULE_PATH:
324                         addAllApplicationModules = true;
325                         break;
326                     default:
327                         roots.add(mod);
328                 }
329             }
330 
331             // --limit-modules
332             savedModuleFinder = finder;
333             if (!limitModules.isEmpty()) {
334                 finder = limitFinder(finder, limitModules, roots);
335             }
336 
337             // If there is no initial module specified then assume that the initial
338             // module is the unnamed module of the application class loader. This
339             // is implemented by resolving all observable modules that export an
340             // API. Modules that have the DO_NOT_RESOLVE_BY_DEFAULT bit set in
341             // their ModuleResolution attribute flags are excluded from the
342             // default set of roots.
343             if (mainModule == null || addAllDefaultModules) {
344                 roots.addAll(DefaultRoots.compute(systemModuleFinder, finder));
345             }
346 
347             // If `--add-modules ALL-SYSTEM` is specified then all observable system
348             // modules will be resolved.
349             if (addAllSystemModules) {
350                 ModuleFinder f = finder;  // observable modules
351                 systemModuleFinder.findAll()
352                     .stream()
353                     .map(ModuleReference::descriptor)
354                     .map(ModuleDescriptor::name)
355                     .filter(mn -> f.find(mn).isPresent())  // observable
356                     .forEach(mn -> roots.add(mn));
357             }
358 
359             // If `--add-modules ALL-MODULE-PATH` is specified then all observable
360             // modules on the application module path will be resolved.
361             if (appModulePath != null && addAllApplicationModules) {
362                 ModuleFinder f = finder;  // observable modules
363                 appModulePath.findAll()
364                     .stream()
365                     .map(ModuleReference::descriptor)
366                     .map(ModuleDescriptor::name)
367                     .filter(mn -> f.find(mn).isPresent())  // observable
368                     .forEach(mn -> roots.add(mn));
369             }
370         } else {
371             // no resolution case
372             finder = systemModuleFinder;
373             roots = null;
374         }
375 
376         Counters.add("jdk.module.boot.3.optionsAndRootsTime");
377 
378         // Step 4: Resolve the root modules, with service binding, to create
379         // the configuration for the boot layer. If resolution is not needed
380         // then create the configuration for the boot layer from the
381         // readability graph created at link time.
382 
383         Configuration cf;
384         if (needResolution) {
385             cf = Modules.newBootLayerConfiguration(finder, roots, traceOutput);
386         } else {
387             if (archivedModuleGraph != null) {
388                 cf = archivedModuleGraph.configuration();
389             } else {
390                 Map<String, Set<String>> map = systemModules.moduleReads();
391                 cf = JLMA.newConfiguration(systemModuleFinder, map);
392             }
393         }
394 
395         // check that modules specified to --patch-module are resolved
396         if (isPatched) {
397             patcher.patchedModules()
398                     .stream()
399                     .filter(mn -> !cf.findModule(mn).isPresent())
400                     .forEach(mn -> warnUnknownModule(PATCH_MODULE, mn));
401         }
402 
403         Counters.add("jdk.module.boot.4.resolveTime");
404 
405         // Step 5: Map the modules in the configuration to class loaders.
406         // The static configuration provides the mapping of standard and JDK
407         // modules to the boot and platform loaders. All other modules (JDK
408         // tool modules, and both explicit and automatic modules on the
409         // application module path) are defined to the application class
410         // loader.
411 
412         // mapping of modules to class loaders
413         Function<String, ClassLoader> clf;
414         if (archivedModuleGraph != null) {
415             clf = archivedModuleGraph.classLoaderFunction();
416         } else {
417             clf = ModuleLoaderMap.mappingFunction(cf);
418         }
419 
420         // check that all modules to be mapped to the boot loader will be
421         // loaded from the runtime image
422         if (haveModulePath) {
423             for (ResolvedModule resolvedModule : cf.modules()) {
424                 ModuleReference mref = resolvedModule.reference();
425                 String name = mref.descriptor().name();
426                 ClassLoader cl = clf.apply(name);
427                 if (cl == null) {
428                     if (upgradeModulePath != null
429                             && upgradeModulePath.find(name).isPresent())
430                         fail(name + ": cannot be loaded from upgrade module path");
431                     if (!systemModuleFinder.find(name).isPresent())
432                         fail(name + ": cannot be loaded from application module path");
433                 }
434             }
435         }
436 
437         // check for split packages in the modules mapped to the built-in loaders
438         if (hasSplitPackages || isPatched || haveModulePath) {
439             checkSplitPackages(cf, clf);
440         }
441 
442         // load/register the modules with the built-in class loaders
443         loadModules(cf, clf);
444         Counters.add("jdk.module.boot.5.loadModulesTime");
445 
446         // Step 6: Define all modules to the VM
447 
448         ModuleLayer bootLayer = ModuleLayer.empty().defineModules(cf, clf);
449         Counters.add("jdk.module.boot.6.layerCreateTime");
450 
451         // Step 7: Miscellaneous
452 
453         // check incubating status
454         if (hasIncubatorModules || haveModulePath) {
455             checkIncubatingStatus(cf);
456         }
457 
458         // --add-reads, --add-exports/--add-opens, and --illegal-access
459         addExtraReads(bootLayer);
460         boolean extraExportsOrOpens = addExtraExportsAndOpens(bootLayer);
461 
462         if (illegalAccess != null) {
463             assert systemModules != null;
464             addIllegalAccess(illegalAccess,
465                              systemModules,
466                              upgradeModulePath,
467                              bootLayer,
468                              extraExportsOrOpens);
469         }
470 
471         Counters.add("jdk.module.boot.7.adjustModulesTime");
472 
473         // save module finders for later use
474         if (savedModuleFinder != null) {
475             unlimitedFinder = new SafeModuleFinder(savedModuleFinder);
476             if (savedModuleFinder != finder)
477                 limitedFinder = new SafeModuleFinder(finder);
478         }
479 
480         // Archive module graph and boot layer can be archived at CDS dump time.
481         // Only allow the unnamed module case for now.
482         if (canArchive && (mainModule == null)) {
483             ArchivedModuleGraph.archive(hasSplitPackages,
484                                         hasIncubatorModules,
485                                         systemModuleFinder,
486                                         cf,
487                                         clf);
488             if (!hasSplitPackages && !hasIncubatorModules) {
489                 ArchivedBootLayer.archive(bootLayer);
490             }
491         }
492 
493         return bootLayer;
494     }
495 
496     /**
497      * Load/register the modules to the built-in class loaders.
498      */
loadModules(Configuration cf, Function<String, ClassLoader> clf)499     private static void loadModules(Configuration cf,
500                                     Function<String, ClassLoader> clf) {
501         for (ResolvedModule resolvedModule : cf.modules()) {
502             ModuleReference mref = resolvedModule.reference();
503             String name = resolvedModule.name();
504             ClassLoader loader = clf.apply(name);
505             if (loader == null) {
506                 // skip java.base as it is already loaded
507                 if (!name.equals(JAVA_BASE)) {
508                     BootLoader.loadModule(mref);
509                 }
510             } else if (loader instanceof BuiltinClassLoader) {
511                 ((BuiltinClassLoader) loader).loadModule(mref);
512             }
513         }
514     }
515 
516     /**
517      * Checks for split packages between modules defined to the built-in class
518      * loaders.
519      */
checkSplitPackages(Configuration cf, Function<String, ClassLoader> clf)520     private static void checkSplitPackages(Configuration cf,
521                                            Function<String, ClassLoader> clf) {
522         Map<String, String> packageToModule = new HashMap<>();
523         for (ResolvedModule resolvedModule : cf.modules()) {
524             ModuleDescriptor descriptor = resolvedModule.reference().descriptor();
525             String name = descriptor.name();
526             ClassLoader loader = clf.apply(name);
527             if (loader == null || loader instanceof BuiltinClassLoader) {
528                 for (String p : descriptor.packages()) {
529                     String other = packageToModule.putIfAbsent(p, name);
530                     if (other != null) {
531                         String msg = "Package " + p + " in both module "
532                                      + name + " and module " + other;
533                         throw new LayerInstantiationException(msg);
534                     }
535                 }
536             }
537         }
538     }
539 
540     /**
541      * Returns a ModuleFinder that limits observability to the given root
542      * modules, their transitive dependences, plus a set of other modules.
543      */
limitFinder(ModuleFinder finder, Set<String> roots, Set<String> otherMods)544     private static ModuleFinder limitFinder(ModuleFinder finder,
545                                             Set<String> roots,
546                                             Set<String> otherMods)
547     {
548         // resolve all root modules
549         Configuration cf = Configuration.empty().resolve(finder,
550                                                          ModuleFinder.of(),
551                                                          roots);
552 
553         // module name -> reference
554         Map<String, ModuleReference> map = new HashMap<>();
555 
556         // root modules and their transitive dependences
557         cf.modules().stream()
558             .map(ResolvedModule::reference)
559             .forEach(mref -> map.put(mref.descriptor().name(), mref));
560 
561         // additional modules
562         otherMods.stream()
563             .map(finder::find)
564             .flatMap(Optional::stream)
565             .forEach(mref -> map.putIfAbsent(mref.descriptor().name(), mref));
566 
567         // set of modules that are observable
568         Set<ModuleReference> mrefs = new HashSet<>(map.values());
569 
570         return new ModuleFinder() {
571             @Override
572             public Optional<ModuleReference> find(String name) {
573                 return Optional.ofNullable(map.get(name));
574             }
575             @Override
576             public Set<ModuleReference> findAll() {
577                 return mrefs;
578             }
579         };
580     }
581 
582     /**
583      * Creates a finder from the module path that is the value of the given
584      * system property and optionally patched by --patch-module
585      */
586     private static ModuleFinder finderFor(String prop) {
587         String s = System.getProperty(prop);
588         if (s == null) {
589             return null;
590         } else {
591             String[] dirs = s.split(File.pathSeparator);
592             Path[] paths = new Path[dirs.length];
593             int i = 0;
594             for (String dir: dirs) {
595                 paths[i++] = Path.of(dir);
596             }
597             return ModulePath.of(patcher, paths);
598         }
599     }
600 
601     /**
602      * Initialize the module patcher for the initial configuration passed on the
603      * value of the --patch-module options.
604      */
605     private static ModulePatcher initModulePatcher() {
606         Map<String, List<String>> map = decode("jdk.module.patch.",
607                                                File.pathSeparator,
608                                                false);
609         return new ModulePatcher(map);
610     }
611 
612     /**
613      * Returns the set of module names specified by --add-module options.
614      */
615     private static Set<String> addModules() {
616         String prefix = "jdk.module.addmods.";
617         int index = 0;
618         // the system property is removed after decoding
619         String value = getAndRemoveProperty(prefix + index);
620         if (value == null) {
621             return Set.of();
622         } else {
623             Set<String> modules = new HashSet<>();
624             while (value != null) {
625                 for (String s : value.split(",")) {
626                     if (!s.isEmpty())
627                         modules.add(s);
628                 }
629                 index++;
630                 value = getAndRemoveProperty(prefix + index);
631             }
632             return modules;
633         }
634     }
635 
636     /**
637      * Returns the set of module names specified by --limit-modules.
638      */
639     private static Set<String> limitModules() {
640         String value = getAndRemoveProperty("jdk.module.limitmods");
641         if (value == null) {
642             return Set.of();
643         } else {
644             Set<String> names = new HashSet<>();
645             for (String name : value.split(",")) {
646                 if (name.length() > 0) names.add(name);
647             }
648             return names;
649         }
650     }
651 
652     /**
653      * Process the --add-reads options to add any additional read edges that
654      * are specified on the command-line.
655      */
656     private static void addExtraReads(ModuleLayer bootLayer) {
657 
658         // decode the command line options
659         Map<String, List<String>> map = decode("jdk.module.addreads.");
660         if (map.isEmpty())
661             return;
662 
663         for (Map.Entry<String, List<String>> e : map.entrySet()) {
664 
665             // the key is $MODULE
666             String mn = e.getKey();
667             Optional<Module> om = bootLayer.findModule(mn);
668             if (!om.isPresent()) {
669                 warnUnknownModule(ADD_READS, mn);
670                 continue;
671             }
672             Module m = om.get();
673 
674             // the value is the set of other modules (by name)
675             for (String name : e.getValue()) {
676                 if (ALL_UNNAMED.equals(name)) {
677                     Modules.addReadsAllUnnamed(m);
678                 } else {
679                     om = bootLayer.findModule(name);
680                     if (om.isPresent()) {
681                         Modules.addReads(m, om.get());
682                     } else {
683                         warnUnknownModule(ADD_READS, name);
684                     }
685                 }
686             }
687         }
688     }
689 
690     /**
691      * Process the --add-exports and --add-opens options to export/open
692      * additional packages specified on the command-line.
693      */
694     private static boolean addExtraExportsAndOpens(ModuleLayer bootLayer) {
695         boolean extraExportsOrOpens = false;
696 
697         // --add-exports
698         String prefix = "jdk.module.addexports.";
699         Map<String, List<String>> extraExports = decode(prefix);
700         if (!extraExports.isEmpty()) {
701             addExtraExportsOrOpens(bootLayer, extraExports, false);
702             extraExportsOrOpens = true;
703         }
704 
705 
706         // --add-opens
707         prefix = "jdk.module.addopens.";
708         Map<String, List<String>> extraOpens = decode(prefix);
709         if (!extraOpens.isEmpty()) {
710             addExtraExportsOrOpens(bootLayer, extraOpens, true);
711             extraExportsOrOpens = true;
712         }
713 
714         return extraExportsOrOpens;
715     }
716 
717     private static void addExtraExportsOrOpens(ModuleLayer bootLayer,
718                                                Map<String, List<String>> map,
719                                                boolean opens)
720     {
721         String option = opens ? ADD_OPENS : ADD_EXPORTS;
722         for (Map.Entry<String, List<String>> e : map.entrySet()) {
723 
724             // the key is $MODULE/$PACKAGE
725             String key = e.getKey();
726             String[] s = key.split("/");
727             if (s.length != 2)
728                 fail(unableToParse(option, "<module>/<package>", key));
729 
730             String mn = s[0];
731             String pn = s[1];
732             if (mn.isEmpty() || pn.isEmpty())
733                 fail(unableToParse(option, "<module>/<package>", key));
734 
735             // The exporting module is in the boot layer
736             Module m;
737             Optional<Module> om = bootLayer.findModule(mn);
738             if (!om.isPresent()) {
739                 warnUnknownModule(option, mn);
740                 continue;
741             }
742 
743             m = om.get();
744 
745             if (!m.getDescriptor().packages().contains(pn)) {
746                 warn("package " + pn + " not in " + mn);
747                 continue;
748             }
749 
750             // the value is the set of modules to export to (by name)
751             for (String name : e.getValue()) {
752                 boolean allUnnamed = false;
753                 Module other = null;
754                 if (ALL_UNNAMED.equals(name)) {
755                     allUnnamed = true;
756                 } else {
757                     om = bootLayer.findModule(name);
758                     if (om.isPresent()) {
759                         other = om.get();
760                     } else {
761                         warnUnknownModule(option, name);
762                         continue;
763                     }
764                 }
765                 if (allUnnamed) {
766                     if (opens) {
767                         Modules.addOpensToAllUnnamed(m, pn);
768                     } else {
769                         Modules.addExportsToAllUnnamed(m, pn);
770                     }
771                 } else {
772                     if (opens) {
773                         Modules.addOpens(m, pn, other);
774                     } else {
775                         Modules.addExports(m, pn, other);
776                     }
777                 }
778             }
779         }
780     }
781 
782     /**
783      * Process the --illegal-access option to open packages of system modules
784      * in the boot layer to code in unnamed modules.
785      */
786     private static void addIllegalAccess(String illegalAccess,
787                                          SystemModules systemModules,
788                                          ModuleFinder upgradeModulePath,
789                                          ModuleLayer bootLayer,
790                                          boolean extraExportsOrOpens) {
791 
792         if (illegalAccess.equals("deny"))
793             return;  // nothing to do
794 
795         IllegalAccessLogger.Mode mode = switch (illegalAccess) {
796             case "permit" -> IllegalAccessLogger.Mode.ONESHOT;
797             case "warn"   -> IllegalAccessLogger.Mode.WARN;
798             case "debug"  -> IllegalAccessLogger.Mode.DEBUG;
799             default -> {
800                 fail("Value specified to --illegal-access not recognized:"
801                         + " '" + illegalAccess + "'");
802                 yield null;
803             }
804         };
805 
806         var builder = new IllegalAccessLogger.Builder(mode, System.err);
807         Map<String, Set<String>> concealedPackagesToOpen = systemModules.concealedPackagesToOpen();
808         Map<String, Set<String>> exportedPackagesToOpen = systemModules.exportedPackagesToOpen();
809         if (concealedPackagesToOpen.isEmpty() && exportedPackagesToOpen.isEmpty()) {
810             // need to generate (exploded build)
811             IllegalAccessMaps maps = IllegalAccessMaps.generate(limitedFinder());
812             concealedPackagesToOpen = maps.concealedPackagesToOpen();
813             exportedPackagesToOpen = maps.exportedPackagesToOpen();
814         }
815 
816         // open specific packages in the system modules
817         Set<String> emptySet = Set.of();
818         for (Module m : bootLayer.modules()) {
819             ModuleDescriptor descriptor = m.getDescriptor();
820             String name = m.getName();
821 
822             // skip open modules
823             if (descriptor.isOpen()) {
824                 continue;
825             }
826 
827             // skip modules loaded from the upgrade module path
828             if (upgradeModulePath != null
829                 && upgradeModulePath.find(name).isPresent()) {
830                 continue;
831             }
832 
833             Set<String> concealedPackages = concealedPackagesToOpen.getOrDefault(name, emptySet);
834             Set<String> exportedPackages = exportedPackagesToOpen.getOrDefault(name, emptySet);
835 
836             // refresh the set of concealed and exported packages if needed
837             if (extraExportsOrOpens) {
838                 concealedPackages = new HashSet<>(concealedPackages);
839                 exportedPackages = new HashSet<>(exportedPackages);
840                 Iterator<String> iterator = concealedPackages.iterator();
841                 while (iterator.hasNext()) {
842                     String pn = iterator.next();
843                     if (m.isExported(pn, BootLoader.getUnnamedModule())) {
844                         // concealed package is exported to ALL-UNNAMED
845                         iterator.remove();
846                         exportedPackages.add(pn);
847                     }
848                 }
849                 iterator = exportedPackages.iterator();
850                 while (iterator.hasNext()) {
851                     String pn = iterator.next();
852                     if (m.isOpen(pn, BootLoader.getUnnamedModule())) {
853                         // exported package is opened to ALL-UNNAMED
854                         iterator.remove();
855                     }
856                 }
857             }
858 
859             // log reflective access to all types in concealed packages
860             builder.logAccessToConcealedPackages(m, concealedPackages);
861 
862             // log reflective access to non-public members/types in exported packages
863             builder.logAccessToExportedPackages(m, exportedPackages);
864 
865             // open the packages to unnamed modules
866             JLA.addOpensToAllUnnamed(m, concealedPackages, exportedPackages);
867         }
868 
869         builder.complete();
870     }
871 
872     /**
873      * Decodes the values of --add-reads, -add-exports, --add-opens or
874      * --patch-modules options that are encoded in system properties.
875      *
876      * @param prefix the system property prefix
877      * @praam regex the regex for splitting the RHS of the option value
878      */
879     private static Map<String, List<String>> decode(String prefix,
880                                                     String regex,
881                                                     boolean allowDuplicates) {
882         int index = 0;
883         // the system property is removed after decoding
884         String value = getAndRemoveProperty(prefix + index);
885         if (value == null)
886             return Map.of();
887 
888         Map<String, List<String>> map = new HashMap<>();
889 
890         while (value != null) {
891 
892             int pos = value.indexOf('=');
893             if (pos == -1)
894                 fail(unableToParse(option(prefix), "<module>=<value>", value));
895             if (pos == 0)
896                 fail(unableToParse(option(prefix), "<module>=<value>", value));
897 
898             // key is <module> or <module>/<package>
899             String key = value.substring(0, pos);
900 
901             String rhs = value.substring(pos+1);
902             if (rhs.isEmpty())
903                 fail(unableToParse(option(prefix), "<module>=<value>", value));
904 
905             // value is <module>(,<module>)* or <file>(<pathsep><file>)*
906             if (!allowDuplicates && map.containsKey(key))
907                 fail(key + " specified more than once to " + option(prefix));
908             List<String> values = map.computeIfAbsent(key, k -> new ArrayList<>());
909             int ntargets = 0;
910             for (String s : rhs.split(regex)) {
911                 if (!s.isEmpty()) {
912                     values.add(s);
913                     ntargets++;
914                 }
915             }
916             if (ntargets == 0)
917                 fail("Target must be specified: " + option(prefix) + " " + value);
918 
919             index++;
920             value = getAndRemoveProperty(prefix + index);
921         }
922 
923         return map;
924     }
925 
926     /**
927      * Decodes the values of --add-reads, -add-exports or --add-opens
928      * which use the "," to separate the RHS of the option value.
929      */
930     private static Map<String, List<String>> decode(String prefix) {
931         return decode(prefix, ",", true);
932     }
933 
934 
935     /**
936      * Gets the named system property
937      */
938     private static String getProperty(String key) {
939         return System.getProperty(key);
940     }
941 
942     /**
943      * Gets and remove the named system property
944      */
945     private static String getAndRemoveProperty(String key) {
946         return (String) System.getProperties().remove(key);
947     }
948 
949     /**
950      * Checks incubating status of modules in the configuration
951      */
952     private static void checkIncubatingStatus(Configuration cf) {
953         String incubating = null;
954         for (ResolvedModule resolvedModule : cf.modules()) {
955             ModuleReference mref = resolvedModule.reference();
956 
957             // emit warning if the WARN_INCUBATING module resolution bit set
958             if (ModuleResolution.hasIncubatingWarning(mref)) {
959                 String mn = mref.descriptor().name();
960                 if (incubating == null) {
961                     incubating = mn;
962                 } else {
963                     incubating += ", " + mn;
964                 }
965             }
966         }
967         if (incubating != null)
968             warn("Using incubator modules: " + incubating);
969     }
970 
971     /**
972      * Throws a RuntimeException with the given message
973      */
974     static void fail(String m) {
975         throw new RuntimeException(m);
976     }
977 
978     static void warn(String m) {
979         System.err.println("WARNING: " + m);
980     }
981 
982     static void warnUnknownModule(String option, String mn) {
983         warn("Unknown module: " + mn + " specified to " + option);
984     }
985 
986     static String unableToParse(String option, String text, String value) {
987         return "Unable to parse " +  option + " " + text + ": " + value;
988     }
989 
990     private static final String ADD_MODULES  = "--add-modules";
991     private static final String ADD_EXPORTS  = "--add-exports";
992     private static final String ADD_OPENS    = "--add-opens";
993     private static final String ADD_READS    = "--add-reads";
994     private static final String PATCH_MODULE = "--patch-module";
995 
996 
997     /*
998      * Returns the command-line option name corresponds to the specified
999      * system property prefix.
1000      */
1001     static String option(String prefix) {
1002         switch (prefix) {
1003             case "jdk.module.addexports.":
1004                 return ADD_EXPORTS;
1005             case "jdk.module.addopens.":
1006                 return ADD_OPENS;
1007             case "jdk.module.addreads.":
1008                 return ADD_READS;
1009             case "jdk.module.patch.":
1010                 return PATCH_MODULE;
1011             case "jdk.module.addmods.":
1012                 return ADD_MODULES;
1013             default:
1014                 throw new IllegalArgumentException(prefix);
1015         }
1016     }
1017 
1018     /**
1019      * Wraps a (potentially not thread safe) ModuleFinder created during startup
1020      * for use after startup.
1021      */
1022     static class SafeModuleFinder implements ModuleFinder {
1023         private final Set<ModuleReference> mrefs;
1024         private volatile Map<String, ModuleReference> nameToModule;
1025 
1026         SafeModuleFinder(ModuleFinder finder) {
1027             this.mrefs = Collections.unmodifiableSet(finder.findAll());
1028         }
1029         @Override
1030         public Optional<ModuleReference> find(String name) {
1031             Objects.requireNonNull(name);
1032             Map<String, ModuleReference> nameToModule = this.nameToModule;
1033             if (nameToModule == null) {
1034                 this.nameToModule = nameToModule = mrefs.stream()
1035                         .collect(Collectors.toMap(m -> m.descriptor().name(),
1036                                                   Function.identity()));
1037             }
1038             return Optional.ofNullable(nameToModule.get(name));
1039         }
1040         @Override
1041         public Set<ModuleReference> findAll() {
1042             return mrefs;
1043         }
1044     }
1045 
1046     /**
1047      * Counters for startup performance analysis.
1048      */
1049     static class Counters {
1050         private static final boolean PUBLISH_COUNTERS;
1051         private static final boolean PRINT_COUNTERS;
1052         private static Map<String, Long> counters;
1053         private static long startTime;
1054         private static long previousTime;
1055 
1056         static {
1057             String s = System.getProperty("jdk.module.boot.usePerfData");
1058             if (s == null) {
1059                 PUBLISH_COUNTERS = false;
1060                 PRINT_COUNTERS = false;
1061             } else {
1062                 PUBLISH_COUNTERS = true;
1063                 PRINT_COUNTERS = s.equals("debug");
1064                 counters = new LinkedHashMap<>();  // preserve insert order
1065             }
1066         }
1067 
1068         /**
1069          * Start counting time.
1070          */
1071         static void start() {
1072             if (PUBLISH_COUNTERS) {
1073                 startTime = previousTime = System.nanoTime();
1074             }
1075         }
1076 
1077         /**
1078          * Add a counter - storing the time difference between now and the
1079          * previous add or the start.
1080          */
1081         static void add(String name) {
1082             if (PUBLISH_COUNTERS) {
1083                 long current = System.nanoTime();
1084                 long elapsed = current - previousTime;
1085                 previousTime = current;
1086                 counters.put(name, elapsed);
1087             }
1088         }
1089 
1090         /**
1091          * Publish the counters to the instrumentation buffer or stdout.
1092          */
1093         static void publish(String totalTimeName) {
1094             if (PUBLISH_COUNTERS) {
1095                 long currentTime = System.nanoTime();
1096                 for (Map.Entry<String, Long> e : counters.entrySet()) {
1097                     String name = e.getKey();
1098                     long value = e.getValue();
1099                     PerfCounter.newPerfCounter(name).set(value);
1100                     if (PRINT_COUNTERS)
1101                         System.out.println(name + " = " + value);
1102                 }
1103                 long elapsedTotal = currentTime - startTime;
1104                 PerfCounter.newPerfCounter(totalTimeName).set(elapsedTotal);
1105                 if (PRINT_COUNTERS)
1106                     System.out.println(totalTimeName + " = " + elapsedTotal);
1107             }
1108         }
1109     }
1110 }
1111