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