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