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