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