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