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