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.isEmpty()) 554 modules.add(s); 555 } 556 index++; 557 value = getAndRemoveProperty(prefix + index); 558 } 559 return modules; 560 } 561 } 562 563 /** 564 * Returns the set of module names specified by --limit-modules. 565 */ 566 private static Set<String> limitModules() { 567 String value = getAndRemoveProperty("jdk.module.limitmods"); 568 if (value == null) { 569 return Collections.emptySet(); 570 } else { 571 Set<String> names = new HashSet<>(); 572 for (String name : value.split(",")) { 573 if (name.length() > 0) names.add(name); 574 } 575 return names; 576 } 577 } 578 579 /** 580 * Process the --add-reads options to add any additional read edges that 581 * are specified on the command-line. 582 */ 583 private static void addExtraReads(ModuleLayer bootLayer) { 584 585 // decode the command line options 586 Map<String, List<String>> map = decode("jdk.module.addreads."); 587 if (map.isEmpty()) 588 return; 589 590 for (Map.Entry<String, List<String>> e : map.entrySet()) { 591 592 // the key is $MODULE 593 String mn = e.getKey(); 594 Optional<Module> om = bootLayer.findModule(mn); 595 if (!om.isPresent()) { 596 warnUnknownModule(ADD_READS, mn); 597 continue; 598 } 599 Module m = om.get(); 600 601 // the value is the set of other modules (by name) 602 for (String name : e.getValue()) { 603 if (ALL_UNNAMED.equals(name)) { 604 Modules.addReadsAllUnnamed(m); 605 } else { 606 om = bootLayer.findModule(name); 607 if (om.isPresent()) { 608 Modules.addReads(m, om.get()); 609 } else { 610 warnUnknownModule(ADD_READS, name); 611 } 612 } 613 } 614 } 615 } 616 617 /** 618 * Process the --add-exports and --add-opens options to export/open 619 * additional packages specified on the command-line. 620 */ 621 private static boolean addExtraExportsAndOpens(ModuleLayer bootLayer) { 622 boolean extraExportsOrOpens = false; 623 624 // --add-exports 625 String prefix = "jdk.module.addexports."; 626 Map<String, List<String>> extraExports = decode(prefix); 627 if (!extraExports.isEmpty()) { 628 addExtraExportsOrOpens(bootLayer, extraExports, false); 629 extraExportsOrOpens = true; 630 } 631 632 633 // --add-opens 634 prefix = "jdk.module.addopens."; 635 Map<String, List<String>> extraOpens = decode(prefix); 636 if (!extraOpens.isEmpty()) { 637 addExtraExportsOrOpens(bootLayer, extraOpens, true); 638 extraExportsOrOpens = true; 639 } 640 641 return extraExportsOrOpens; 642 } 643 644 private static void addExtraExportsOrOpens(ModuleLayer bootLayer, 645 Map<String, List<String>> map, 646 boolean opens) 647 { 648 String option = opens ? ADD_OPENS : ADD_EXPORTS; 649 for (Map.Entry<String, List<String>> e : map.entrySet()) { 650 651 // the key is $MODULE/$PACKAGE 652 String key = e.getKey(); 653 String[] s = key.split("/"); 654 if (s.length != 2) 655 fail(unableToParse(option, "<module>/<package>", key)); 656 657 String mn = s[0]; 658 String pn = s[1]; 659 if (mn.isEmpty() || pn.isEmpty()) 660 fail(unableToParse(option, "<module>/<package>", key)); 661 662 // The exporting module is in the boot layer 663 Module m; 664 Optional<Module> om = bootLayer.findModule(mn); 665 if (!om.isPresent()) { 666 warnUnknownModule(option, mn); 667 continue; 668 } 669 670 m = om.get(); 671 672 if (!m.getDescriptor().packages().contains(pn)) { 673 warn("package " + pn + " not in " + mn); 674 continue; 675 } 676 677 // the value is the set of modules to export to (by name) 678 for (String name : e.getValue()) { 679 boolean allUnnamed = false; 680 Module other = null; 681 if (ALL_UNNAMED.equals(name)) { 682 allUnnamed = true; 683 } else { 684 om = bootLayer.findModule(name); 685 if (om.isPresent()) { 686 other = om.get(); 687 } else { 688 warnUnknownModule(option, name); 689 continue; 690 } 691 } 692 if (allUnnamed) { 693 if (opens) { 694 Modules.addOpensToAllUnnamed(m, pn); 695 } else { 696 Modules.addExportsToAllUnnamed(m, pn); 697 } 698 } else { 699 if (opens) { 700 Modules.addOpens(m, pn, other); 701 } else { 702 Modules.addExports(m, pn, other); 703 } 704 } 705 706 } 707 } 708 } 709 710 /** 711 * Process the --illegal-access option (and its default) to open packages 712 * of system modules in the boot layer to code in unnamed modules. 713 */ 714 private static void addIllegalAccess(ModuleFinder upgradeModulePath, 715 SystemModules systemModules, 716 ModuleLayer bootLayer, 717 boolean extraExportsOrOpens) { 718 String value = getAndRemoveProperty("jdk.module.illegalAccess"); 719 IllegalAccessLogger.Mode mode = IllegalAccessLogger.Mode.ONESHOT; 720 if (value != null) { 721 switch (value) { 722 case "deny": 723 return; 724 case "permit": 725 break; 726 case "warn": 727 mode = IllegalAccessLogger.Mode.WARN; 728 break; 729 case "debug": 730 mode = IllegalAccessLogger.Mode.DEBUG; 731 break; 732 default: 733 fail("Value specified to --illegal-access not recognized:" 734 + " '" + value + "'"); 735 return; 736 } 737 } 738 IllegalAccessLogger.Builder builder 739 = new IllegalAccessLogger.Builder(mode, System.err); 740 741 Map<String, Set<String>> map1 = systemModules.concealedPackagesToOpen(); 742 Map<String, Set<String>> map2 = systemModules.exportedPackagesToOpen(); 743 if (map1.isEmpty() && map2.isEmpty()) { 744 // need to generate (exploded build) 745 IllegalAccessMaps maps = IllegalAccessMaps.generate(limitedFinder()); 746 map1 = maps.concealedPackagesToOpen(); 747 map2 = maps.exportedPackagesToOpen(); 748 } 749 750 // open specific packages in the system modules 751 for (Module m : bootLayer.modules()) { 752 ModuleDescriptor descriptor = m.getDescriptor(); 753 String name = m.getName(); 754 755 // skip open modules 756 if (descriptor.isOpen()) { 757 continue; 758 } 759 760 // skip modules loaded from the upgrade module path 761 if (upgradeModulePath != null 762 && upgradeModulePath.find(name).isPresent()) { 763 continue; 764 } 765 766 Set<String> concealedPackages = map1.getOrDefault(name, Set.of()); 767 Set<String> exportedPackages = map2.getOrDefault(name, Set.of()); 768 769 // refresh the set of concealed and exported packages if needed 770 if (extraExportsOrOpens) { 771 concealedPackages = new HashSet<>(concealedPackages); 772 exportedPackages = new HashSet<>(exportedPackages); 773 Iterator<String> iterator = concealedPackages.iterator(); 774 while (iterator.hasNext()) { 775 String pn = iterator.next(); 776 if (m.isExported(pn, BootLoader.getUnnamedModule())) { 777 // concealed package is exported to ALL-UNNAMED 778 iterator.remove(); 779 exportedPackages.add(pn); 780 } 781 } 782 iterator = exportedPackages.iterator(); 783 while (iterator.hasNext()) { 784 String pn = iterator.next(); 785 if (m.isOpen(pn, BootLoader.getUnnamedModule())) { 786 // exported package is opened to ALL-UNNAMED 787 iterator.remove(); 788 } 789 } 790 } 791 792 // log reflective access to all types in concealed packages 793 builder.logAccessToConcealedPackages(m, concealedPackages); 794 795 // log reflective access to non-public members/types in exported packages 796 builder.logAccessToExportedPackages(m, exportedPackages); 797 798 // open the packages to unnamed modules 799 JavaLangAccess jla = SharedSecrets.getJavaLangAccess(); 800 jla.addOpensToAllUnnamed(m, concat(concealedPackages.iterator(), 801 exportedPackages.iterator())); 802 } 803 804 builder.complete(); 805 } 806 807 /** 808 * Decodes the values of --add-reads, -add-exports, --add-opens or 809 * --patch-modules options that are encoded in system properties. 810 * 811 * @param prefix the system property prefix 812 * @praam regex the regex for splitting the RHS of the option value 813 */ 814 private static Map<String, List<String>> decode(String prefix, 815 String regex, 816 boolean allowDuplicates) { 817 int index = 0; 818 // the system property is removed after decoding 819 String value = getAndRemoveProperty(prefix + index); 820 if (value == null) 821 return Collections.emptyMap(); 822 823 Map<String, List<String>> map = new HashMap<>(); 824 825 while (value != null) { 826 827 int pos = value.indexOf('='); 828 if (pos == -1) 829 fail(unableToParse(option(prefix), "<module>=<value>", value)); 830 if (pos == 0) 831 fail(unableToParse(option(prefix), "<module>=<value>", value)); 832 833 // key is <module> or <module>/<package> 834 String key = value.substring(0, pos); 835 836 String rhs = value.substring(pos+1); 837 if (rhs.isEmpty()) 838 fail(unableToParse(option(prefix), "<module>=<value>", value)); 839 840 // value is <module>(,<module>)* or <file>(<pathsep><file>)* 841 if (!allowDuplicates && map.containsKey(key)) 842 fail(key + " specified more than once to " + option(prefix)); 843 List<String> values = map.computeIfAbsent(key, k -> new ArrayList<>()); 844 int ntargets = 0; 845 for (String s : rhs.split(regex)) { 846 if (!s.isEmpty()) { 847 values.add(s); 848 ntargets++; 849 } 850 } 851 if (ntargets == 0) 852 fail("Target must be specified: " + option(prefix) + " " + value); 853 854 index++; 855 value = getAndRemoveProperty(prefix + index); 856 } 857 858 return map; 859 } 860 861 /** 862 * Decodes the values of --add-reads, -add-exports or --add-opens 863 * which use the "," to separate the RHS of the option value. 864 */ 865 private static Map<String, List<String>> decode(String prefix) { 866 return decode(prefix, ",", true); 867 } 868 869 /** 870 * Gets and remove the named system property 871 */ 872 private static String getAndRemoveProperty(String key) { 873 return (String)System.getProperties().remove(key); 874 } 875 876 /** 877 * Checks incubating status of modules in the configuration 878 */ 879 private static void checkIncubatingStatus(Configuration cf) { 880 String incubating = null; 881 for (ResolvedModule resolvedModule : cf.modules()) { 882 ModuleReference mref = resolvedModule.reference(); 883 884 // emit warning if the WARN_INCUBATING module resolution bit set 885 if (ModuleResolution.hasIncubatingWarning(mref)) { 886 String mn = mref.descriptor().name(); 887 if (incubating == null) { 888 incubating = mn; 889 } else { 890 incubating += ", " + mn; 891 } 892 } 893 } 894 if (incubating != null) 895 warn("Using incubator modules: " + incubating); 896 } 897 898 /** 899 * Throws a RuntimeException with the given message 900 */ 901 static void fail(String m) { 902 throw new RuntimeException(m); 903 } 904 905 static void warn(String m) { 906 System.err.println("WARNING: " + m); 907 } 908 909 static void warnUnknownModule(String option, String mn) { 910 warn("Unknown module: " + mn + " specified to " + option); 911 } 912 913 static String unableToParse(String option, String text, String value) { 914 return "Unable to parse " + option + " " + text + ": " + value; 915 } 916 917 private static final String ADD_MODULES = "--add-modules"; 918 private static final String ADD_EXPORTS = "--add-exports"; 919 private static final String ADD_OPENS = "--add-opens"; 920 private static final String ADD_READS = "--add-reads"; 921 private static final String PATCH_MODULE = "--patch-module"; 922 923 924 /* 925 * Returns the command-line option name corresponds to the specified 926 * system property prefix. 927 */ 928 static String option(String prefix) { 929 switch (prefix) { 930 case "jdk.module.addexports.": 931 return ADD_EXPORTS; 932 case "jdk.module.addopens.": 933 return ADD_OPENS; 934 case "jdk.module.addreads.": 935 return ADD_READS; 936 case "jdk.module.patch.": 937 return PATCH_MODULE; 938 case "jdk.module.addmods.": 939 return ADD_MODULES; 940 default: 941 throw new IllegalArgumentException(prefix); 942 } 943 } 944 945 /** 946 * Returns an iterator that yields all elements of the first iterator 947 * followed by all the elements of the second iterator. 948 */ 949 static <T> Iterator<T> concat(Iterator<T> iterator1, Iterator<T> iterator2) { 950 return new Iterator<T>() { 951 @Override 952 public boolean hasNext() { 953 return iterator1.hasNext() || iterator2.hasNext(); 954 } 955 @Override 956 public T next() { 957 if (iterator1.hasNext()) return iterator1.next(); 958 if (iterator2.hasNext()) return iterator2.next(); 959 throw new NoSuchElementException(); 960 } 961 }; 962 } 963 964 /** 965 * Wraps a (potentially not thread safe) ModuleFinder created during startup 966 * for use after startup. 967 */ 968 static class SafeModuleFinder implements ModuleFinder { 969 private final Set<ModuleReference> mrefs; 970 private volatile Map<String, ModuleReference> nameToModule; 971 972 SafeModuleFinder(ModuleFinder finder) { 973 this.mrefs = Collections.unmodifiableSet(finder.findAll()); 974 } 975 @Override 976 public Optional<ModuleReference> find(String name) { 977 Objects.requireNonNull(name); 978 Map<String, ModuleReference> nameToModule = this.nameToModule; 979 if (nameToModule == null) { 980 this.nameToModule = nameToModule = mrefs.stream() 981 .collect(Collectors.toMap(m -> m.descriptor().name(), 982 Function.identity())); 983 } 984 return Optional.ofNullable(nameToModule.get(name)); 985 } 986 @Override 987 public Set<ModuleReference> findAll() { 988 return mrefs; 989 } 990 } 991 992 /** 993 * Counters for startup performance analysis. 994 */ 995 static class Counters { 996 private static final boolean PUBLISH_COUNTERS; 997 private static final boolean PRINT_COUNTERS; 998 private static Map<String, Long> counters; 999 static { 1000 String s = System.getProperty("jdk.module.boot.usePerfData"); 1001 if (s == null) { 1002 PUBLISH_COUNTERS = false; 1003 PRINT_COUNTERS = false; 1004 } else { 1005 PUBLISH_COUNTERS = true; 1006 PRINT_COUNTERS = s.equals("debug"); 1007 counters = new LinkedHashMap<>(); // preserve insert order 1008 } 1009 } 1010 1011 /** 1012 * Add a counter 1013 */ 1014 static void add(String name, long start) { 1015 if (PUBLISH_COUNTERS || PRINT_COUNTERS) { 1016 counters.put(name, (System.nanoTime() - start)); 1017 } 1018 } 1019 1020 /** 1021 * Publish the counters to the instrumentation buffer or stdout. 1022 */ 1023 static void publish() { 1024 if (PUBLISH_COUNTERS || PRINT_COUNTERS) { 1025 for (Map.Entry<String, Long> e : counters.entrySet()) { 1026 String name = e.getKey(); 1027 long value = e.getValue(); 1028 if (PUBLISH_COUNTERS) 1029 PerfCounter.newPerfCounter(name).set(value); 1030 if (PRINT_COUNTERS) 1031 System.out.println(name + " = " + value); 1032 } 1033 } 1034 } 1035 } 1036 }