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