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