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