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