1 /*
   2  * Copyright (c) 2015, 2019, 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.jpackage.internal;
  27 
  28 import java.io.File;
  29 import java.io.IOException;
  30 import java.io.StringReader;
  31 import java.nio.file.Files;
  32 import java.nio.file.Path;
  33 import java.text.MessageFormat;
  34 import java.util.Collection;
  35 import java.util.Collections;
  36 import java.util.EnumSet;
  37 import java.util.HashMap;
  38 import java.util.HashSet;
  39 import java.util.Iterator;
  40 import java.util.LinkedHashMap;
  41 import java.util.LinkedHashSet;
  42 import java.util.List;
  43 import java.util.Map;
  44 import java.util.Properties;
  45 import java.util.ResourceBundle;
  46 import java.util.Set;
  47 import java.util.Optional;
  48 import java.lang.module.ModuleDescriptor;
  49 import java.lang.module.ModuleFinder;
  50 import java.lang.module.ModuleReference;
  51 
  52 import jdk.tools.jlink.internal.packager.AppRuntimeImageBuilder;
  53 
  54 final class JLinkBundlerHelper {
  55 
  56     private static final ResourceBundle I18N = ResourceBundle.getBundle(
  57             "jdk.jpackage.internal.resources.MainResources");
  58     private static final String JRE_MODULES_FILENAME =
  59             "jdk/jpackage/internal/resources/jre.list";
  60     private static final String SERVER_JRE_MODULES_FILENAME =
  61             "jdk/jpackage/internal/resources/jre.module.list";
  62 
  63     private JLinkBundlerHelper() {}
  64 
  65     @SuppressWarnings("unchecked")
  66     static final BundlerParamInfo<String> JLINK_BUILDER =
  67             new StandardBundlerParam<>(
  68                     I18N.getString("param.jlink-builder.name"),
  69                     I18N.getString("param.jlink-builder.description"),
  70                     "jlink.builder",
  71                     String.class,
  72                     null,
  73                     (s, p) -> s);
  74 
  75     @SuppressWarnings("unchecked")
  76     static final BundlerParamInfo<Integer> DEBUG =
  77             new StandardBundlerParam<>(
  78                     "",
  79                     "",
  80                     "-J-Xdebug",
  81                     Integer.class,
  82                     p -> null,
  83                     (s, p) -> {
  84                         return Integer.valueOf(s);
  85                     });
  86 
  87     static String listOfPathToString(List<Path> value) {
  88         String result = "";
  89 
  90         for (Path path : value) {
  91             if (result.length() > 0) {
  92                 result += File.pathSeparator;
  93             }
  94 
  95             result += path.toString();
  96         }
  97 
  98         return result;
  99     }
 100 
 101     static String setOfStringToString(Set<String> value) {
 102         String result = "";
 103 
 104         for (String element : value) {
 105             if (result.length() > 0) {
 106                 result += ",";
 107             }
 108 
 109             result += element;
 110         }
 111 
 112         return result;
 113     }
 114 
 115     static File getMainJar(Map<String, ? super Object> params) {
 116         File result = null;
 117         RelativeFileSet fileset =
 118                 StandardBundlerParam.MAIN_JAR.fetchFrom(params);
 119 
 120         if (fileset != null) {
 121             String filename = fileset.getIncludedFiles().iterator().next();
 122             result = fileset.getBaseDirectory().toPath().
 123                     resolve(filename).toFile();
 124 
 125             if (result == null || !result.exists()) {
 126                 String srcdir =
 127                     StandardBundlerParam.SOURCE_DIR.fetchFrom(params);
 128 
 129                 if (srcdir != null) {
 130                     result = new File(srcdir + File.separator + filename);
 131                 }
 132             }
 133         }
 134 
 135         return result;
 136     }
 137 
 138     static String getMainClass(Map<String, ? super Object> params) {
 139         String result = "";
 140         String mainModule = StandardBundlerParam.MODULE.fetchFrom(params);
 141         if (mainModule != null)  {
 142             int index = mainModule.indexOf("/");
 143             if (index > 0) {
 144                 result = mainModule.substring(index + 1);
 145             }
 146         } else {
 147             RelativeFileSet fileset =
 148                     StandardBundlerParam.MAIN_JAR.fetchFrom(params);
 149             if (fileset != null) {
 150                 result = StandardBundlerParam.MAIN_CLASS.fetchFrom(params);
 151             } else {
 152                 // possibly app-image
 153             }
 154         }
 155 
 156         return result;
 157     }
 158 
 159     static String getMainModule(Map<String, ? super Object> params) {
 160         String result = "";
 161         String mainModule = StandardBundlerParam.MODULE.fetchFrom(params);
 162 
 163         if (mainModule != null) {
 164             int index = mainModule.indexOf("/");
 165 
 166             if (index > 0) {
 167                 result = mainModule.substring(0, index);
 168             } else {
 169                 result = mainModule;
 170             }
 171         }
 172 
 173         return result;
 174     }
 175 
 176     static String getJDKVersion(Map<String, ? super Object> params) {
 177         String result = "";
 178         List<Path> modulePath =
 179                 StandardBundlerParam.MODULE_PATH.fetchFrom(params);
 180         Set<String> limitModules =
 181                 StandardBundlerParam.LIMIT_MODULES.fetchFrom(params);
 182         Path javaBasePath = findPathOfModule(modulePath, "java.base.jmod");
 183         Set<String> addModules = getValidModules(modulePath,
 184                 StandardBundlerParam.ADD_MODULES.fetchFrom(params),
 185                 limitModules, true);
 186 
 187 
 188         if (javaBasePath != null && javaBasePath.toFile().exists()) {
 189             result = getModuleVersion(javaBasePath.toFile(),
 190                     modulePath, addModules, limitModules);
 191         }
 192 
 193         return result;
 194     }
 195 
 196     static Path getJDKHome(Map<String, ? super Object> params) {
 197         Path result = null;
 198         List<Path> modulePath =
 199                 StandardBundlerParam.MODULE_PATH.fetchFrom(params);
 200         Path javaBasePath = findPathOfModule(modulePath, "java.base.jmod");
 201 
 202         if (javaBasePath != null && javaBasePath.toFile().exists()) {
 203             result = javaBasePath.getParent();
 204 
 205             // On a developer build the JDK Home isn't where we expect it
 206             // relative to the jmods directory. Do some extra
 207             // processing to find it.
 208             if (result != null) {
 209                 boolean found = false;
 210                 Path bin = result.resolve("bin");
 211 
 212                 if (Files.exists(bin)) {
 213                     final String exe =
 214                             (Platform.getPlatform() == Platform.WINDOWS) ?
 215                             ".exe" : "";
 216                     Path javaExe = bin.resolve("java" + exe);
 217 
 218                     if (Files.exists(javaExe)) {
 219                         found = true;
 220                     }
 221                 }
 222 
 223                 if (!found) {
 224                     result = result.resolve(".." + File.separator + "jdk");
 225                 }
 226             }
 227         }
 228 
 229         return result;
 230     }
 231 
 232     private static Set<String> getValidModules(List<Path> modulePath,
 233             Set<String> addModules, Set<String> limitModules,
 234             boolean forJRE) {
 235         ModuleHelper moduleHelper = new ModuleHelper(
 236                 modulePath, addModules, limitModules, forJRE);
 237         return removeInvalidModules(modulePath, moduleHelper.modules());
 238     }
 239 
 240     static void execute(Map<String, ? super Object> params,
 241             AbstractAppImageBuilder imageBuilder)
 242             throws IOException, Exception {
 243         List<Path> modulePath =
 244                 StandardBundlerParam.MODULE_PATH.fetchFrom(params);
 245         Set<String> addModules =
 246                 StandardBundlerParam.ADD_MODULES.fetchFrom(params);
 247         Set<String> limitModules =
 248                 StandardBundlerParam.LIMIT_MODULES.fetchFrom(params);
 249         boolean stripNativeCommands =
 250                 StandardBundlerParam.STRIP_NATIVE_COMMANDS.fetchFrom(params);
 251         Path outputDir = imageBuilder.getRoot();
 252         String excludeFileList = imageBuilder.getExcludeFileList();
 253         File mainJar = getMainJar(params);
 254         ModFile.ModType mainJarType = ModFile.ModType.Unknown;
 255 
 256         if (mainJar != null) {
 257             mainJarType = new ModFile(mainJar).getModType();
 258         } else if (StandardBundlerParam.MODULE.fetchFrom(params) == null) {
 259             // user specified only main class, all jars will be on the classpath
 260             mainJarType = ModFile.ModType.UnnamedJar;
 261         }
 262 
 263         // Modules
 264 
 265         // The default for an unnamed jar is ALL_DEFAULT with the
 266         // non-valid modules removed.
 267         if (mainJarType == ModFile.ModType.UnnamedJar) {
 268             addModules.add(ModuleHelper.ALL_RUNTIME);
 269         } else if (mainJarType == ModFile.ModType.Unknown ||
 270                 mainJarType == ModFile.ModType.ModularJar) {
 271             String mainModule = getMainModule(params);
 272             addModules.add(mainModule);
 273         }
 274         addModules.addAll(getValidModules(
 275                 modulePath, addModules, limitModules, false));
 276 
 277         Log.verbose(MessageFormat.format(
 278                 I18N.getString("message.modules"), addModules.toString()));
 279 
 280         AppRuntimeImageBuilder appRuntimeBuilder = new AppRuntimeImageBuilder();
 281         appRuntimeBuilder.setOutputDir(outputDir);
 282         appRuntimeBuilder.setModulePath(modulePath);
 283         appRuntimeBuilder.setAddModules(addModules);
 284         appRuntimeBuilder.setLimitModules(limitModules);
 285         appRuntimeBuilder.setExcludeFileList(excludeFileList);
 286         appRuntimeBuilder.setStripNativeCommands(stripNativeCommands);
 287         appRuntimeBuilder.setUserArguments(new HashMap<String,String>());
 288 
 289         appRuntimeBuilder.build();
 290         imageBuilder.prepareApplicationFiles();
 291     }
 292 
 293     static void generateJre(Map<String, ? super Object> params,
 294             AbstractAppImageBuilder imageBuilder)
 295             throws IOException, Exception {
 296         List<Path> modulePath =
 297                 StandardBundlerParam.MODULE_PATH.fetchFrom(params);
 298         Set<String> addModules =
 299                 StandardBundlerParam.ADD_MODULES.fetchFrom(params);
 300         Set<String> limitModules =
 301                 StandardBundlerParam.LIMIT_MODULES.fetchFrom(params);
 302         boolean stripNativeCommands =
 303                 StandardBundlerParam.STRIP_NATIVE_COMMANDS.fetchFrom(params);
 304         Path outputDir = imageBuilder.getRoot();
 305         addModules.add(ModuleHelper.ALL_RUNTIME);
 306         Set<String> redistModules = getValidModules(modulePath,
 307                 addModules, limitModules, true);
 308         addModules.addAll(redistModules);
 309 
 310         Log.verbose(MessageFormat.format(
 311                 I18N.getString("message.modules"), addModules.toString()));
 312 
 313         AppRuntimeImageBuilder appRuntimeBuilder = new AppRuntimeImageBuilder();
 314         appRuntimeBuilder.setOutputDir(outputDir);
 315         appRuntimeBuilder.setModulePath(modulePath);
 316         appRuntimeBuilder.setAddModules(addModules);
 317         appRuntimeBuilder.setLimitModules(limitModules);
 318         appRuntimeBuilder.setStripNativeCommands(stripNativeCommands);
 319         appRuntimeBuilder.setExcludeFileList("");
 320         appRuntimeBuilder.setUserArguments(new HashMap<String,String>());
 321 
 322         appRuntimeBuilder.build();
 323         imageBuilder.prepareJreFiles();
 324     }
 325 
 326     // Returns the path to the JDK modules in the user defined module path.
 327     static Path findPathOfModule(
 328             List<Path> modulePath, String moduleName) {
 329         Path result = null;
 330 
 331         for (Path path : modulePath) {
 332             Path moduleNamePath = path.resolve(moduleName);
 333 
 334             if (Files.exists(moduleNamePath)) {
 335                 result = path;
 336                 break;
 337             }
 338         }
 339 
 340         return result;
 341     }
 342 
 343     private static Set<String> removeInvalidModules(
 344             List<Path> modulePath, Set<String> modules) {
 345         Set<String> result = new LinkedHashSet<String>();
 346         ModuleManager mm = new ModuleManager(modulePath);
 347         List<ModFile> lmodfiles =
 348                 mm.getModules(EnumSet.of(ModuleManager.SearchType.ModularJar,
 349                         ModuleManager.SearchType.Jmod,
 350                         ModuleManager.SearchType.ExplodedModule));
 351 
 352         HashMap<String, ModFile> validModules = new HashMap<>();
 353 
 354         for (ModFile modFile : lmodfiles) {
 355             validModules.put(modFile.getModName(), modFile);
 356         }
 357 
 358         for (String name : modules) {
 359             if (validModules.containsKey(name)) {
 360                 result.add(name);
 361             } else {
 362                 Log.error(MessageFormat.format(
 363                         I18N.getString("warning.module.does.not.exist"), name));
 364             }
 365         }
 366 
 367         return result;
 368     }
 369 
 370     private static String getModuleVersion(File moduleFile,
 371             List<Path> modulePath, Set<String> addModules,
 372             Set<String> limitModules) {
 373         String result = "";
 374 
 375         ModFile modFile = new ModFile(moduleFile);
 376         ModuleFinder finder = AppRuntimeImageBuilder.moduleFinder(modulePath,
 377                 addModules, limitModules);
 378         Optional<ModuleReference> mref = finder.find(modFile.getModName());
 379 
 380         if (mref.isPresent()) {
 381             ModuleDescriptor descriptor = mref.get().descriptor();
 382 
 383             if (descriptor != null) {
 384                 Optional<ModuleDescriptor.Version> version =
 385                         descriptor.version();
 386 
 387                 if (version.isPresent()) {
 388                     result = version.get().toString();
 389                 }
 390             }
 391         }
 392 
 393         return result;
 394     }
 395 
 396     private static class ModuleHelper {
 397         // The token for "all modules on the module path".
 398         private static final String ALL_MODULE_PATH = "ALL-MODULE-PATH";
 399 
 400         // The token for "all valid runtime modules".
 401         static final String ALL_RUNTIME = "ALL-RUNTIME";
 402 
 403         private final Set<String> modules = new HashSet<>();
 404         private enum Macros {None, AllModulePath, AllRuntime}
 405 
 406         ModuleHelper(List<Path> paths, Set<String> roots,
 407                 Set<String> limitMods, boolean forJRE) {
 408             Macros macro = Macros.None;
 409 
 410             for (Iterator<String> iterator = roots.iterator();
 411                     iterator.hasNext();) {
 412                 String module = iterator.next();
 413 
 414                 switch (module) {
 415                     case ALL_MODULE_PATH:
 416                         iterator.remove();
 417                         macro = Macros.AllModulePath;
 418                         break;
 419                     case ALL_RUNTIME:
 420                         iterator.remove();
 421                         macro = Macros.AllRuntime;
 422                         break;
 423                     default:
 424                         this.modules.add(module);
 425                 }
 426             }
 427 
 428             switch (macro) {
 429                 case AllModulePath:
 430                     this.modules.addAll(getModuleNamesFromPath(paths));
 431                     break;
 432                 case AllRuntime:
 433                     Set<Module> runtimeModules =
 434                             ModuleLayer.boot().modules();
 435                     for (Module m : runtimeModules) {
 436                         String name = m.getName();
 437                         if (forJRE && isModuleExcludedFromJRE(name)) {
 438                             continue;  // JRE does not include this module
 439                         }
 440                         this.modules.add(name);
 441                     }
 442                     break;
 443             }
 444         }
 445 
 446         Set<String> modules() {
 447             return modules;
 448         }
 449 
 450         private boolean isModuleExcludedFromJRE(String name) {
 451             return false;  // not excluding any modules from JRE at this time
 452         }
 453 
 454         private static Set<String> getModuleNamesFromPath(List<Path> Value) {
 455                 Set<String> result = new LinkedHashSet<String>();
 456                 ModuleManager mm = new ModuleManager(Value);
 457                 List<ModFile> modFiles =
 458                         mm.getModules(
 459                                 EnumSet.of(ModuleManager.SearchType.ModularJar,
 460                                 ModuleManager.SearchType.Jmod,
 461                                 ModuleManager.SearchType.ExplodedModule));
 462 
 463                 for (ModFile modFile : modFiles) {
 464                     result.add(modFile.getModName());
 465                 }
 466 
 467                 return result;
 468         }
 469     }
 470 }