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 // open specific packages in the system modules 804 for (Module m : bootLayer.modules()) { 805 ModuleDescriptor descriptor = m.getDescriptor(); 806 String name = m.getName(); 807 808 // skip open modules 809 if (descriptor.isOpen()) { 810 continue; 811 } 812 813 // skip modules loaded from the upgrade module path 814 if (upgradeModulePath != null 815 && upgradeModulePath.find(name).isPresent()) { 816 continue; 817 } 818 819 Set<String> concealedPackages = concealedPackagesToOpen.getOrDefault(name, Set.of()); 820 Set<String> exportedPackages = exportedPackagesToOpen.getOrDefault(name, Set.of()); 821 822 // refresh the set of concealed and exported packages if needed 823 if (extraExportsOrOpens) { 824 concealedPackages = new HashSet<>(concealedPackages); 825 exportedPackages = new HashSet<>(exportedPackages); 826 Iterator<String> iterator = concealedPackages.iterator(); 827 while (iterator.hasNext()) { 828 String pn = iterator.next(); 829 if (m.isExported(pn, BootLoader.getUnnamedModule())) { 830 // concealed package is exported to ALL-UNNAMED 831 iterator.remove(); 832 exportedPackages.add(pn); 833 } 834 } 835 iterator = exportedPackages.iterator(); 836 while (iterator.hasNext()) { 837 String pn = iterator.next(); 838 if (m.isOpen(pn, BootLoader.getUnnamedModule())) { 839 // exported package is opened to ALL-UNNAMED 840 iterator.remove(); 841 } 842 } 843 } 844 845 // log reflective access to all types in concealed packages 846 builder.logAccessToConcealedPackages(m, concealedPackages); 847 848 // log reflective access to non-public members/types in exported packages 849 builder.logAccessToExportedPackages(m, exportedPackages); 850 851 // open the packages to unnamed modules 852 JavaLangAccess jla = SharedSecrets.getJavaLangAccess(); 853 jla.addOpensToAllUnnamed(m, concat(concealedPackages.iterator(), 854 exportedPackages.iterator())); 855 } 856 857 builder.complete(); 858 } 859 860 /** 861 * Decodes the values of --add-reads, -add-exports, --add-opens or 862 * --patch-modules options that are encoded in system properties. 863 * 864 * @param prefix the system property prefix 865 * @praam regex the regex for splitting the RHS of the option value 866 */ 867 private static Map<String, List<String>> decode(String prefix, 868 String regex, 869 boolean allowDuplicates) { 870 int index = 0; 871 // the system property is removed after decoding 872 String value = getAndRemoveProperty(prefix + index); 873 if (value == null) 874 return Map.of(); 875 876 Map<String, List<String>> map = new HashMap<>(); 877 878 while (value != null) { 879 880 int pos = value.indexOf('='); 881 if (pos == -1) 882 fail(unableToParse(option(prefix), "<module>=<value>", value)); 883 if (pos == 0) 884 fail(unableToParse(option(prefix), "<module>=<value>", value)); 885 886 // key is <module> or <module>/<package> 887 String key = value.substring(0, pos); 888 889 String rhs = value.substring(pos+1); 890 if (rhs.isEmpty()) 891 fail(unableToParse(option(prefix), "<module>=<value>", value)); 892 893 // value is <module>(,<module>)* or <file>(<pathsep><file>)* 894 if (!allowDuplicates && map.containsKey(key)) 895 fail(key + " specified more than once to " + option(prefix)); 896 List<String> values = map.computeIfAbsent(key, k -> new ArrayList<>()); 897 int ntargets = 0; 898 for (String s : rhs.split(regex)) { 899 if (!s.isEmpty()) { 900 values.add(s); 901 ntargets++; 902 } 903 } 904 if (ntargets == 0) 905 fail("Target must be specified: " + option(prefix) + " " + value); 906 907 index++; 908 value = getAndRemoveProperty(prefix + index); 909 } 910 911 return map; 912 } 913 914 /** 915 * Decodes the values of --add-reads, -add-exports or --add-opens 916 * which use the "," to separate the RHS of the option value. 917 */ 918 private static Map<String, List<String>> decode(String prefix) { 919 return decode(prefix, ",", true); 920 } 921 922 /** 923 * Gets and remove the named system property 924 */ 925 private static String getAndRemoveProperty(String key) { 926 return (String)System.getProperties().remove(key); 927 } 928 929 /** 930 * Checks incubating status of modules in the configuration 931 */ 932 private static void checkIncubatingStatus(Configuration cf) { 933 String incubating = null; 934 for (ResolvedModule resolvedModule : cf.modules()) { 935 ModuleReference mref = resolvedModule.reference(); 936 937 // emit warning if the WARN_INCUBATING module resolution bit set 938 if (ModuleResolution.hasIncubatingWarning(mref)) { 939 String mn = mref.descriptor().name(); 940 if (incubating == null) { 941 incubating = mn; 942 } else { 943 incubating += ", " + mn; 944 } 945 } 946 } 947 if (incubating != null) 948 warn("Using incubator modules: " + incubating); 949 } 950 951 /** 952 * Throws a RuntimeException with the given message 953 */ 954 static void fail(String m) { 955 throw new RuntimeException(m); 956 } 957 958 static void warn(String m) { 959 System.err.println("WARNING: " + m); 960 } 961 962 static void warnUnknownModule(String option, String mn) { 963 warn("Unknown module: " + mn + " specified to " + option); 964 } 965 966 static String unableToParse(String option, String text, String value) { 967 return "Unable to parse " + option + " " + text + ": " + value; 968 } 969 970 private static final String ADD_MODULES = "--add-modules"; 971 private static final String ADD_EXPORTS = "--add-exports"; 972 private static final String ADD_OPENS = "--add-opens"; 973 private static final String ADD_READS = "--add-reads"; 974 private static final String PATCH_MODULE = "--patch-module"; 975 976 977 /* 978 * Returns the command-line option name corresponds to the specified 979 * system property prefix. 980 */ 981 static String option(String prefix) { 982 switch (prefix) { 983 case "jdk.module.addexports.": 984 return ADD_EXPORTS; 985 case "jdk.module.addopens.": 986 return ADD_OPENS; 987 case "jdk.module.addreads.": 988 return ADD_READS; 989 case "jdk.module.patch.": 990 return PATCH_MODULE; 991 case "jdk.module.addmods.": 992 return ADD_MODULES; 993 default: 994 throw new IllegalArgumentException(prefix); 995 } 996 } 997 998 /** 999 * Returns an iterator that yields all elements of the first iterator 1000 * followed by all the elements of the second iterator. 1001 */ 1002 static <T> Iterator<T> concat(Iterator<T> iterator1, Iterator<T> iterator2) { 1003 return new Iterator<T>() { 1004 @Override 1005 public boolean hasNext() { 1006 return iterator1.hasNext() || iterator2.hasNext(); 1007 } 1008 @Override 1009 public T next() { 1010 if (iterator1.hasNext()) return iterator1.next(); 1011 if (iterator2.hasNext()) return iterator2.next(); 1012 throw new NoSuchElementException(); 1013 } 1014 }; 1015 } 1016 1017 /** 1018 * Wraps a (potentially not thread safe) ModuleFinder created during startup 1019 * for use after startup. 1020 */ 1021 static class SafeModuleFinder implements ModuleFinder { 1022 private final Set<ModuleReference> mrefs; 1023 private volatile Map<String, ModuleReference> nameToModule; 1024 1025 SafeModuleFinder(ModuleFinder finder) { 1026 this.mrefs = Collections.unmodifiableSet(finder.findAll()); 1027 } 1028 @Override 1029 public Optional<ModuleReference> find(String name) { 1030 Objects.requireNonNull(name); 1031 Map<String, ModuleReference> nameToModule = this.nameToModule; 1032 if (nameToModule == null) { 1033 this.nameToModule = nameToModule = mrefs.stream() 1034 .collect(Collectors.toMap(m -> m.descriptor().name(), 1035 Function.identity())); 1036 } 1037 return Optional.ofNullable(nameToModule.get(name)); 1038 } 1039 @Override 1040 public Set<ModuleReference> findAll() { 1041 return mrefs; 1042 } 1043 } 1044 1045 /** 1046 * Counters for startup performance analysis. 1047 */ 1048 static class Counters { 1049 private static final boolean PUBLISH_COUNTERS; 1050 private static final boolean PRINT_COUNTERS; 1051 private static Map<String, Long> counters; 1052 static { 1053 String s = System.getProperty("jdk.module.boot.usePerfData"); 1054 if (s == null) { 1055 PUBLISH_COUNTERS = false; 1056 PRINT_COUNTERS = false; 1057 } else { 1058 PUBLISH_COUNTERS = true; 1059 PRINT_COUNTERS = s.equals("debug"); 1060 counters = new LinkedHashMap<>(); // preserve insert order 1061 } 1062 } 1063 1064 /** 1065 * Add a counter 1066 */ 1067 static void add(String name, long start) { 1068 if (PUBLISH_COUNTERS || PRINT_COUNTERS) { 1069 counters.put(name, (System.nanoTime() - start)); 1070 } 1071 } 1072 1073 /** 1074 * Publish the counters to the instrumentation buffer or stdout. 1075 */ 1076 static void publish() { 1077 if (PUBLISH_COUNTERS || PRINT_COUNTERS) { 1078 for (Map.Entry<String, Long> e : counters.entrySet()) { 1079 String name = e.getKey(); 1080 long value = e.getValue(); 1081 if (PUBLISH_COUNTERS) 1082 PerfCounter.newPerfCounter(name).set(value); 1083 if (PRINT_COUNTERS) 1084 System.out.println(name + " = " + value); 1085 } 1086 } 1087 } 1088 } 1089 }