1 /*
   2  * Copyright (c) 2014, 2016, 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.lang.reflect.Layer;
  36 import java.lang.reflect.Module;
  37 import java.net.URI;
  38 import java.nio.file.Path;
  39 import java.nio.file.Paths;
  40 import java.util.ArrayList;
  41 import java.util.Collections;
  42 import java.util.HashMap;
  43 import java.util.HashSet;
  44 import java.util.List;
  45 import java.util.Map;
  46 import java.util.Optional;
  47 import java.util.Set;
  48 import java.util.function.Function;
  49 
  50 import jdk.internal.loader.BootLoader;
  51 import jdk.internal.loader.BuiltinClassLoader;
  52 import jdk.internal.misc.SharedSecrets;
  53 import jdk.internal.perf.PerfCounter;
  54 
  55 /**
  56  * Initializes/boots the module system.
  57  *
  58  * The {@link #boot() boot} method is called early in the startup to initialize
  59  * the module system. In summary, the boot method creates a Configuration by
  60  * resolving a set of module names specified via the launcher (or equivalent)
  61  * -m and --add-modules options. The modules are located on a module path that
  62  * is constructed from the upgrade module path, system modules, and application
  63  * module path. The Configuration is instantiated as the boot Layer with each
  64  * module in the the configuration defined to one of the built-in class loaders.
  65  */
  66 
  67 public final class ModuleBootstrap {
  68     private ModuleBootstrap() { }
  69 
  70     private static final String JAVA_BASE = "java.base";
  71 
  72     private static final String JAVA_SE = "java.se";
  73 
  74     // the token for "all default modules"
  75     private static final String ALL_DEFAULT = "ALL-DEFAULT";
  76 
  77     // the token for "all unnamed modules"
  78     private static final String ALL_UNNAMED = "ALL-UNNAMED";
  79 
  80     // the token for "all system modules"
  81     private static final String ALL_SYSTEM = "ALL-SYSTEM";
  82 
  83     // the token for "all modules on the module path"
  84     private static final String ALL_MODULE_PATH = "ALL-MODULE-PATH";
  85 
  86     // The ModulePatcher for the initial configuration
  87     private static final ModulePatcher patcher = initModulePatcher();
  88 
  89     // ModuleFinder for the initial configuration
  90     private static ModuleFinder initialFinder;
  91 
  92     /**
  93      * Returns the ModulePatcher for the initial configuration.
  94      */
  95     public static ModulePatcher patcher() {
  96         return patcher;
  97     }
  98 
  99     /**
 100      * Returns the ModuleFinder for the initial configuration
 101      */
 102     public static ModuleFinder finder() {
 103         assert initialFinder != null;
 104         return initialFinder;
 105     }
 106 
 107     /**
 108      * Initialize the module system, returning the boot Layer.
 109      *
 110      * @see java.lang.System#initPhase2()
 111      */
 112     public static Layer boot() {
 113 
 114         long t0 = System.nanoTime();
 115 
 116         // system modules (may be patched)
 117         ModuleFinder systemModules = ModuleFinder.ofSystem();
 118 
 119         PerfCounters.systemModulesTime.addElapsedTimeFrom(t0);
 120 
 121 
 122         long t1 = System.nanoTime();
 123 
 124         // Once we have the system modules then we define the base module to
 125         // the VM. We do this here so that java.base is defined as early as
 126         // possible and also that resources in the base module can be located
 127         // for error messages that may happen from here on.
 128         ModuleReference base = systemModules.find(JAVA_BASE).orElse(null);
 129         if (base == null)
 130             throw new InternalError(JAVA_BASE + " not found");
 131         URI baseUri = base.location().orElse(null);
 132         if (baseUri == null)
 133             throw new InternalError(JAVA_BASE + " does not have a location");
 134         BootLoader.loadModule(base);
 135         Modules.defineModule(null, base.descriptor(), baseUri);
 136 
 137         PerfCounters.defineBaseTime.addElapsedTimeFrom(t1);
 138 
 139 
 140         long t2 = System.nanoTime();
 141 
 142         // --upgrade-module-path option specified to launcher
 143         ModuleFinder upgradeModulePath
 144             = createModulePathFinder("jdk.module.upgrade.path");
 145         if (upgradeModulePath != null)
 146             systemModules = ModuleFinder.compose(upgradeModulePath, systemModules);
 147 
 148         // --module-path option specified to the launcher
 149         ModuleFinder appModulePath = createModulePathFinder("jdk.module.path");
 150 
 151         // The module finder: [--upgrade-module-path] system [--module-path]
 152         ModuleFinder finder = systemModules;
 153         if (appModulePath != null)
 154             finder = ModuleFinder.compose(finder, appModulePath);
 155 
 156         // The root modules to resolve
 157         Set<String> roots = new HashSet<>();
 158 
 159         // launcher -m option to specify the main/initial module
 160         String mainModule = System.getProperty("jdk.module.main");
 161         if (mainModule != null)
 162             roots.add(mainModule);
 163 
 164         // additional module(s) specified by --add-modules
 165         boolean addAllDefaultModules = false;
 166         boolean addAllSystemModules = false;
 167         boolean addAllApplicationModules = false;
 168         for (String mod: getExtraAddModules()) {
 169             switch (mod) {
 170                 case ALL_DEFAULT:
 171                     addAllDefaultModules = true;
 172                     break;
 173                 case ALL_SYSTEM:
 174                     addAllSystemModules = true;
 175                     break;
 176                 case ALL_MODULE_PATH:
 177                     addAllApplicationModules = true;
 178                     break;
 179                 default :
 180                     roots.add(mod);
 181             }
 182         }
 183 
 184         // --limit-modules
 185         String propValue = getAndRemoveProperty("jdk.module.limitmods");
 186         if (propValue != null) {
 187             Set<String> mods = new HashSet<>();
 188             for (String mod: propValue.split(",")) {
 189                 mods.add(mod);
 190             }
 191             finder = limitFinder(finder, mods, roots);
 192         }
 193 
 194         // If there is no initial module specified then assume that the initial
 195         // module is the unnamed module of the application class loader. This
 196         // is implemented by resolving "java.se" and all (non-java.*) modules
 197         // that export an API. If "java.se" is not observable then all java.*
 198         // modules are resolved.
 199         if (mainModule == null || addAllDefaultModules) {
 200             boolean hasJava = false;
 201             if (systemModules.find(JAVA_SE).isPresent()) {
 202                 // java.se is a system module
 203                 if (finder == systemModules || finder.find(JAVA_SE).isPresent()) {
 204                     // java.se is observable
 205                     hasJava = true;
 206                     roots.add(JAVA_SE);
 207                 }
 208             }
 209 
 210             for (ModuleReference mref : systemModules.findAll()) {
 211                 String mn = mref.descriptor().name();
 212                 if (hasJava && mn.startsWith("java."))
 213                     continue;
 214 
 215                 // add as root if observable and exports at least one package
 216                 if ((finder == systemModules || finder.find(mn).isPresent())) {
 217                     ModuleDescriptor descriptor = mref.descriptor();
 218                     for (ModuleDescriptor.Exports e : descriptor.exports()) {
 219                         if (!e.isQualified()) {
 220                             roots.add(mn);
 221                             break;
 222                         }
 223                     }
 224                 }
 225             }
 226         }
 227 
 228         // If `--add-modules ALL-SYSTEM` is specified then all observable system
 229         // modules will be resolved.
 230         if (addAllSystemModules) {
 231             ModuleFinder f = finder;  // observable modules
 232             systemModules.findAll()
 233                 .stream()
 234                 .map(ModuleReference::descriptor)
 235                 .map(ModuleDescriptor::name)
 236                 .filter(mn -> f.find(mn).isPresent())  // observable
 237                 .forEach(mn -> roots.add(mn));
 238         }
 239 
 240         // If `--add-modules ALL-MODULE-PATH` is specified then all observable
 241         // modules on the application module path will be resolved.
 242         if (appModulePath != null && addAllApplicationModules) {
 243             ModuleFinder f = finder;  // observable modules
 244             appModulePath.findAll()
 245                 .stream()
 246                 .map(ModuleReference::descriptor)
 247                 .map(ModuleDescriptor::name)
 248                 .filter(mn -> f.find(mn).isPresent())  // observable
 249                 .forEach(mn -> roots.add(mn));
 250         }
 251 
 252         PerfCounters.optionsAndRootsTime.addElapsedTimeFrom(t2);
 253 
 254 
 255         long t3 = System.nanoTime();
 256 
 257         // determine if post resolution checks are needed
 258         boolean needPostResolutionChecks = true;
 259         if (baseUri.getScheme().equals("jrt")   // toLowerCase not needed here
 260                 && (upgradeModulePath == null)
 261                 && (appModulePath == null)
 262                 && (patcher.isEmpty())) {
 263             needPostResolutionChecks = false;
 264         }
 265 
 266         PrintStream traceOutput = null;
 267         if (Boolean.getBoolean("jdk.launcher.traceResolver"))
 268             traceOutput = System.out;
 269 
 270         // run the resolver to create the configuration
 271         Configuration cf = SharedSecrets.getJavaLangModuleAccess()
 272                 .resolveRequiresAndUses(finder,
 273                                         roots,
 274                                         needPostResolutionChecks,
 275                                         traceOutput);
 276 
 277         // time to create configuration
 278         PerfCounters.resolveTime.addElapsedTimeFrom(t3);
 279 
 280 
 281         // mapping of modules to class loaders
 282         Function<String, ClassLoader> clf = ModuleLoaderMap.mappingFunction(cf);
 283 
 284         // check that all modules to be mapped to the boot loader will be
 285         // loaded from the runtime image
 286         if (needPostResolutionChecks) {
 287             for (ResolvedModule resolvedModule : cf.modules()) {
 288                 ModuleReference mref = resolvedModule.reference();
 289                 String name = mref.descriptor().name();
 290                 ClassLoader cl = clf.apply(name);
 291                 if (cl == null) {
 292 
 293                     if (upgradeModulePath != null
 294                             && upgradeModulePath.find(name).isPresent())
 295                         fail(name + ": cannot be loaded from upgrade module path");
 296 
 297                     if (!systemModules.find(name).isPresent())
 298                         fail(name + ": cannot be loaded from application module path");
 299                 }
 300             }
 301         }
 302 
 303 
 304         long t4 = System.nanoTime();
 305 
 306         // define modules to VM/runtime
 307         Layer bootLayer = Layer.empty().defineModules(cf, clf);
 308 
 309         PerfCounters.layerCreateTime.addElapsedTimeFrom(t4);
 310 
 311 
 312         long t5 = System.nanoTime();
 313 
 314         // define the module to its class loader, except java.base
 315         for (ResolvedModule resolvedModule : cf.modules()) {
 316             ModuleReference mref = resolvedModule.reference();
 317             String name = mref.descriptor().name();
 318             ClassLoader cl = clf.apply(name);
 319             if (cl == null) {
 320                 if (!name.equals(JAVA_BASE)) BootLoader.loadModule(mref);
 321             } else {
 322                 ((BuiltinClassLoader)cl).loadModule(mref);
 323             }
 324         }
 325 
 326         PerfCounters.loadModulesTime.addElapsedTimeFrom(t5);
 327 
 328 
 329         // --add-reads, -add-exports/-add-opens
 330         addExtraReads(bootLayer);
 331         addExtraExportsAndOpens(bootLayer);
 332 
 333         // total time to initialize
 334         PerfCounters.bootstrapTime.addElapsedTimeFrom(t0);
 335 
 336         // remember the ModuleFinder
 337         initialFinder = finder;
 338 
 339         return bootLayer;
 340     }
 341 
 342     /**
 343      * Returns a ModuleFinder that limits observability to the given root
 344      * modules, their transitive dependences, plus a set of other modules.
 345      */
 346     private static ModuleFinder limitFinder(ModuleFinder finder,
 347                                             Set<String> roots,
 348                                             Set<String> otherMods)
 349     {
 350         // resolve all root modules
 351         Configuration cf = Configuration.empty()
 352                 .resolveRequires(finder,
 353                                  ModuleFinder.of(),
 354                                  roots);
 355 
 356         // module name -> reference
 357         Map<String, ModuleReference> map = new HashMap<>();
 358 
 359         // root modules and their transitive dependences
 360         cf.modules().stream()
 361             .map(ResolvedModule::reference)
 362             .forEach(mref -> map.put(mref.descriptor().name(), mref));
 363 
 364         // additional modules
 365         otherMods.stream()
 366             .map(finder::find)
 367             .flatMap(Optional::stream)
 368             .forEach(mref -> map.putIfAbsent(mref.descriptor().name(), mref));
 369 
 370         // set of modules that are observable
 371         Set<ModuleReference> mrefs = new HashSet<>(map.values());
 372 
 373         return new ModuleFinder() {
 374             @Override
 375             public Optional<ModuleReference> find(String name) {
 376                 return Optional.ofNullable(map.get(name));
 377             }
 378             @Override
 379             public Set<ModuleReference> findAll() {
 380                 return mrefs;
 381             }
 382         };
 383     }
 384 
 385     /**
 386      * Creates a finder from the module path that is the value of the given
 387      * system property.
 388      */
 389     private static ModuleFinder createModulePathFinder(String prop) {
 390         String s = System.getProperty(prop);
 391         if (s == null) {
 392             return null;
 393         } else {
 394             String[] dirs = s.split(File.pathSeparator);
 395             Path[] paths = new Path[dirs.length];
 396             int i = 0;
 397             for (String dir: dirs) {
 398                 paths[i++] = Paths.get(dir);
 399             }
 400             return ModuleFinder.of(paths);
 401         }
 402     }
 403 
 404 
 405     /**
 406      * Initialize the module patcher for the initial configuration passed on the
 407      * value of the --patch-module options.
 408      */
 409     private static ModulePatcher initModulePatcher() {
 410         Map<String, List<String>> map = decode("jdk.module.patch.",
 411                                                File.pathSeparator,
 412                                                false);
 413         return new ModulePatcher(map);
 414     }
 415 
 416     /**
 417      * Returns the set of module names specified via --add-modules options
 418      * on the command line
 419      */
 420     private static Set<String> getExtraAddModules() {
 421         String prefix = "jdk.module.addmods.";
 422         int index = 0;
 423 
 424         // the system property is removed after decoding
 425         String value = getAndRemoveProperty(prefix + index);
 426         if (value == null) {
 427             return Collections.emptySet();
 428         }
 429 
 430         Set<String> modules = new HashSet<>();
 431         while (value != null) {
 432             for (String s : value.split(",")) {
 433                 if (s.length() > 0) modules.add(s);
 434             }
 435             index++;
 436             value = getAndRemoveProperty(prefix + index);
 437         }
 438 
 439         return modules;
 440     }
 441 
 442     /**
 443      * Process the --add-reads options to add any additional read edges that
 444      * are specified on the command-line.
 445      */
 446     private static void addExtraReads(Layer bootLayer) {
 447 
 448         // decode the command line options
 449         Map<String, List<String>> map = decode("jdk.module.addreads.");
 450         if (map.isEmpty())
 451             return;
 452 
 453         for (Map.Entry<String, List<String>> e : map.entrySet()) {
 454 
 455             // the key is $MODULE
 456             String mn = e.getKey();
 457             Optional<Module> om = bootLayer.findModule(mn);
 458             if (!om.isPresent()) {
 459                 warn("Unknown module: " + mn);
 460                 continue;
 461             }
 462             Module m = om.get();
 463 
 464             // the value is the set of other modules (by name)
 465             for (String name : e.getValue()) {
 466                 if (ALL_UNNAMED.equals(name)) {
 467                     Modules.addReadsAllUnnamed(m);
 468                 } else {
 469                     om = bootLayer.findModule(name);
 470                     if (om.isPresent()) {
 471                         Modules.addReads(m, om.get());
 472                     } else {
 473                         warn("Unknown module: " + name);
 474                     }
 475                 }
 476             }
 477         }
 478     }
 479 
 480     /**
 481      * Process the --add-exports and --add-opens options to export/open
 482      * additional packages specified on the command-line.
 483      */
 484     private static void addExtraExportsAndOpens(Layer bootLayer) {
 485 
 486         // --add-exports
 487         String prefix = "jdk.module.addexports.";
 488         Map<String, List<String>> extraExports = decode(prefix);
 489         if (!extraExports.isEmpty()) {
 490             addExtraExportsOrOpens(bootLayer, extraExports, false);
 491         }
 492 
 493         // --add-opens
 494         prefix = "jdk.module.addopens.";
 495         Map<String, List<String>> extraOpens = decode(prefix);
 496         if (!extraOpens.isEmpty()) {
 497             addExtraExportsOrOpens(bootLayer, extraOpens, true);
 498         }
 499     }
 500 
 501     private static void addExtraExportsOrOpens(Layer bootLayer,
 502                                                Map<String, List<String>> map,
 503                                                boolean opens)
 504     {
 505         for (Map.Entry<String, List<String>> e : map.entrySet()) {
 506 
 507             // the key is $MODULE/$PACKAGE
 508             String key = e.getKey();
 509             String[] s = key.split("/");
 510             if (s.length != 2)
 511                 fail("Unable to parse: " + key);
 512 
 513             String mn = s[0];
 514             String pn = s[1];
 515             if (mn.isEmpty() || pn.isEmpty())
 516                 fail("Module and package name must be specified:" + key);
 517 
 518             // The exporting module is in the boot layer
 519             Module m;
 520             Optional<Module> om = bootLayer.findModule(mn);
 521             if (!om.isPresent()) {
 522                 warn("Unknown module: " + mn);
 523                 continue;
 524             }
 525 
 526             m = om.get();
 527 
 528             if (!m.getDescriptor().packages().contains(pn)) {
 529                 warn("package " + pn + " not in " + mn);
 530                 continue;
 531             }
 532 
 533             // the value is the set of modules to export to (by name)
 534             for (String name : e.getValue()) {
 535                 boolean allUnnamed = false;
 536                 Module other = null;
 537                 if (ALL_UNNAMED.equals(name)) {
 538                     allUnnamed = true;
 539                 } else {
 540                     om = bootLayer.findModule(name);
 541                     if (om.isPresent()) {
 542                         other = om.get();
 543                     } else {
 544                         warn("Unknown module: " + name);
 545                         continue;
 546                     }
 547                 }
 548                 if (allUnnamed) {
 549                     if (opens) {
 550                         Modules.addOpensToAllUnnamed(m, pn);
 551                     } else {
 552                         Modules.addExportsToAllUnnamed(m, pn);
 553                     }
 554                 } else {
 555                     if (opens) {
 556                         Modules.addOpens(m, pn, other);
 557                     } else {
 558                         Modules.addExports(m, pn, other);
 559                     }
 560                 }
 561 
 562             }
 563         }
 564     }
 565 
 566     /**
 567      * Decodes the values of --add-reads, -add-exports, --add-opens or
 568      * --patch-modules options that are encoded in system properties.
 569      *
 570      * @param prefix the system property prefix
 571      * @praam regex the regex for splitting the RHS of the option value
 572      */
 573     private static Map<String, List<String>> decode(String prefix,
 574                                                     String regex,
 575                                                     boolean allowDuplicates) {
 576         int index = 0;
 577         // the system property is removed after decoding
 578         String value = getAndRemoveProperty(prefix + index);
 579         if (value == null)
 580             return Collections.emptyMap();
 581 
 582         Map<String, List<String>> map = new HashMap<>();
 583 
 584         while (value != null) {
 585 
 586             int pos = value.indexOf('=');
 587             if (pos == -1)
 588                 fail("Unable to parse: " + value);
 589             if (pos == 0)
 590                 fail("Missing module name in: " + value);
 591 
 592             // key is <module> or <module>/<package>
 593             String key = value.substring(0, pos);
 594 
 595             String rhs = value.substring(pos+1);
 596             if (rhs.isEmpty())
 597                 fail("Unable to parse: " + value);
 598 
 599             // value is <module>(,<module>)* or <file>(<pathsep><file>)*
 600             if (!allowDuplicates && map.containsKey(key))
 601                 fail(key + " specified more than once");
 602             List<String> values = map.computeIfAbsent(key, k -> new ArrayList<>());
 603             for (String s : rhs.split(regex)) {
 604                 if (s.length() > 0) values.add(s);
 605             }
 606 
 607             index++;
 608             value = getAndRemoveProperty(prefix + index);
 609         }
 610 
 611         return map;
 612     }
 613 
 614     /**
 615      * Decodes the values of --add-reads, -add-exports or --add-opens
 616      * which use the "," to separate the RHS of the option value.
 617      */
 618     private static Map<String, List<String>> decode(String prefix) {
 619         return decode(prefix, ",", true);
 620     }
 621 
 622     /**
 623      * Gets and remove the named system property
 624      */
 625     private static String getAndRemoveProperty(String key) {
 626         return (String)System.getProperties().remove(key);
 627     }
 628 
 629     /**
 630      * Throws a RuntimeException with the given message
 631      */
 632     static void fail(String m) {
 633         throw new RuntimeException(m);
 634     }
 635 
 636     static void warn(String m) {
 637         System.err.println("WARNING: " + m);
 638     }
 639 
 640     static class PerfCounters {
 641 
 642         static PerfCounter systemModulesTime
 643             = PerfCounter.newPerfCounter("jdk.module.bootstrap.systemModulesTime");
 644         static PerfCounter defineBaseTime
 645             = PerfCounter.newPerfCounter("jdk.module.bootstrap.defineBaseTime");
 646         static PerfCounter optionsAndRootsTime
 647             = PerfCounter.newPerfCounter("jdk.module.bootstrap.optionsAndRootsTime");
 648         static PerfCounter resolveTime
 649             = PerfCounter.newPerfCounter("jdk.module.bootstrap.resolveTime");
 650         static PerfCounter layerCreateTime
 651             = PerfCounter.newPerfCounter("jdk.module.bootstrap.layerCreateTime");
 652         static PerfCounter loadModulesTime
 653             = PerfCounter.newPerfCounter("jdk.module.bootstrap.loadModulesTime");
 654         static PerfCounter bootstrapTime
 655             = PerfCounter.newPerfCounter("jdk.module.bootstrap.totalTime");
 656     }
 657 }