1 /* 2 * Copyright (c) 2015, 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 package jdk.packager.builders.windows; 26 27 import com.oracle.tools.packager.BundlerParamInfo; 28 import com.oracle.tools.packager.Log; 29 import com.oracle.tools.packager.RelativeFileSet; 30 import com.oracle.tools.packager.IOUtils; 31 import com.oracle.tools.packager.StandardBundlerParam; 32 import com.oracle.tools.packager.windows.WinResources; 33 import com.oracle.tools.packager.windows.WindowsBundlerParam; 34 import jdk.packager.builders.AbstractAppImageBuilder; 35 36 import jdk.tools.jlink.plugin.Pool; 37 38 import java.io.File; 39 import java.io.FileOutputStream; 40 import java.io.IOException; 41 import java.io.InputStream; 42 import java.io.OutputStream; 43 import java.io.OutputStreamWriter; 44 import java.io.UncheckedIOException; 45 import java.io.Writer; 46 import java.io.BufferedWriter; 47 import java.io.FileWriter; 48 import java.nio.file.Files; 49 import java.nio.file.Path; 50 import java.nio.file.attribute.PosixFilePermission; 51 import java.text.MessageFormat; 52 import java.util.HashMap; 53 import java.util.List; 54 import java.util.Map; 55 import java.util.Objects; 56 import java.util.ResourceBundle; 57 import java.util.Set; 58 import java.util.concurrent.atomic.AtomicReference; 59 import java.util.regex.Pattern; 60 61 import static com.oracle.tools.packager.StandardBundlerParam.*; 62 63 /** 64 * 65 */ 66 public class WindowsAppImageBuilder extends AbstractAppImageBuilder { 67 68 private static final ResourceBundle I18N = 69 ResourceBundle.getBundle(WindowsAppImageBuilder.class.getName()); 70 71 protected static final String WINDOWS_BUNDLER_PREFIX = 72 BUNDLER_PREFIX + "windows" + File.separator; 73 74 private final static String EXECUTABLE_NAME = "WinLauncher.exe"; 75 private final static String LIBRARY_NAME = "packager.dll"; 76 77 private final static String[] VS_VERS = {"100", "110", "120"}; 78 private final static String REDIST_MSVCR = "msvcrVS_VER.dll"; 79 private final static String REDIST_MSVCP = "msvcpVS_VER.dll"; 80 81 private final static String TEMPLATE_APP_ICON ="javalogo_white_48.ico"; 82 private static final String TOOL_ICON_SWAP="IconSwap.exe"; 83 private static final String TOOL_VERSION_INFO_SWAP="VersionInfoSwap.exe"; 84 85 private static final String EXECUTABLE_PROPERTIES_TEMPLATE = "WinLauncher.properties"; 86 87 private final Path root; 88 private final Path appDir; 89 private final Path runtimeRoot; 90 private final Path mdir; 91 92 private final Map<String, ? super Object> params; 93 94 public static final BundlerParamInfo<File> CONFIG_ROOT = new WindowsBundlerParam<>( 95 I18N.getString("param.config-root.name"), 96 I18N.getString("param.config-root.description"), 97 "configRoot", 98 File.class, 99 params -> { 100 File imagesRoot = new File(BUILD_ROOT.fetchFrom(params), "windows"); 101 imagesRoot.mkdirs(); 102 return imagesRoot; 103 }, 104 (s, p) -> null); 105 106 public static final BundlerParamInfo<Boolean> REBRAND_EXECUTABLE = new WindowsBundlerParam<>( 107 I18N.getString("param.rebrand-executable.name"), 108 I18N.getString("param.rebrand-executable.description"), 109 "win.launcher.rebrand", 110 Boolean.class, 111 params -> Boolean.TRUE, 112 (s, p) -> Boolean.valueOf(s)); 113 114 public static final BundlerParamInfo<File> ICON_ICO = new StandardBundlerParam<>( 115 I18N.getString("param.icon-ico.name"), 116 I18N.getString("param.icon-ico.description"), 117 "icon.ico", 118 File.class, 119 params -> { 120 File f = ICON.fetchFrom(params); 121 if (f != null && !f.getName().toLowerCase().endsWith(".ico")) { 122 Log.info(MessageFormat.format(I18N.getString("message.icon-not-ico"), f)); 123 return null; 124 } 125 return f; 126 }, 127 (s, p) -> new File(s)); 128 129 130 131 public WindowsAppImageBuilder(Map<String, Object> config, Path imageOutDir) throws IOException { 132 super(config, imageOutDir.resolve(APP_NAME.fetchFrom(config) + "/runtime")); 133 134 Objects.requireNonNull(imageOutDir); 135 136 //@SuppressWarnings("unchecked") 137 //String img = (String) config.get("jimage.name"); // FIXME constant 138 139 this.params = config; 140 141 this.root = imageOutDir.resolve(APP_NAME.fetchFrom(params)); 142 this.appDir = root.resolve("app"); 143 this.runtimeRoot = root.resolve("runtime"); 144 this.mdir = runtimeRoot.resolve("lib"); 145 Files.createDirectories(appDir); 146 } 147 148 private Path destFile(String dir, String filename) { 149 return runtimeRoot.resolve(dir).resolve(filename); 150 } 151 152 private void writeEntry(InputStream in, Path dstFile) throws IOException { 153 Files.createDirectories(dstFile.getParent()); 154 Files.copy(in, dstFile); 155 } 156 157 private void writeSymEntry(Path dstFile, Path target) throws IOException { 158 Files.createDirectories(dstFile.getParent()); 159 Files.createLink(dstFile, target); 160 } 161 162 /** 163 * chmod ugo+x file 164 */ 165 private void setExecutable(Path file) { 166 try { 167 Set<PosixFilePermission> perms = Files.getPosixFilePermissions(file); 168 perms.add(PosixFilePermission.OWNER_EXECUTE); 169 perms.add(PosixFilePermission.GROUP_EXECUTE); 170 perms.add(PosixFilePermission.OTHERS_EXECUTE); 171 Files.setPosixFilePermissions(file, perms); 172 } catch (IOException ioe) { 173 throw new UncheckedIOException(ioe); 174 } 175 } 176 177 private static void createUtf8File(File file, String content) throws IOException { 178 try (OutputStream fout = new FileOutputStream(file); 179 Writer output = new OutputStreamWriter(fout, "UTF-8")) { 180 output.write(content); 181 } 182 } 183 184 185 186 //it is static for the sake of sharing with "installer" bundlers 187 // that may skip calls to validate/bundle in this class! 188 public static File getRootDir(File outDir, Map<String, ? super Object> p) { 189 return new File(outDir, APP_FS_NAME.fetchFrom(p)); 190 } 191 192 public static String getLauncherName(Map<String, ? super Object> p) { 193 return APP_FS_NAME.fetchFrom(p) + ".exe"; 194 } 195 196 public static String getLauncherCfgName(Map<String, ? super Object> p) { 197 return "app/" + APP_FS_NAME.fetchFrom(p) +".cfg"; 198 } 199 200 private File getConfig_AppIcon(Map<String, ? super Object> params) { 201 return new File(getConfigRoot(params), APP_FS_NAME.fetchFrom(params) + ".ico"); 202 } 203 204 private File getConfig_ExecutableProperties(Map<String, ? super Object> params) { 205 return new File(getConfigRoot(params), APP_FS_NAME.fetchFrom(params) + ".properties"); 206 } 207 208 File getConfigRoot(Map<String, ? super Object> params) { 209 return CONFIG_ROOT.fetchFrom(params); 210 } 211 212 protected void cleanupConfigFiles(Map<String, ? super Object> params) { 213 getConfig_AppIcon(params).delete(); 214 getConfig_ExecutableProperties(params).delete(); 215 } 216 217 @Override 218 protected InputStream getResourceAsStream(String name) { 219 return WinResources.class.getResourceAsStream(name); 220 } 221 222 @Override 223 protected void prepareApplicationFiles(Pool files, Set<String> modules) throws IOException { 224 Map<String, ? super Object> originalParams = new HashMap<>(params); 225 File rootFile = root.toFile(); 226 if (!rootFile.isDirectory() && !rootFile.mkdirs()) { 227 throw new RuntimeException(MessageFormat.format(I18N.getString("error.cannot-create-output-dir"), rootFile.getAbsolutePath())); 228 } 229 if (!rootFile.canWrite()) { 230 throw new RuntimeException(MessageFormat.format(I18N.getString("error.cannot-write-to-output-dir"), rootFile.getAbsolutePath())); 231 } 232 try { 233 // if (!dependentTask) { 234 // Log.info(MessageFormat.format(I18N.getString("message.creating-app-bundle"), APP_NAME.fetchFrom(p), outputDirectory.getAbsolutePath())); 235 // } 236 237 // Create directory structure 238 // IOUtils.deleteRecursive(rootDirectory); 239 // rootDirectory.mkdirs(); 240 241 242 // create the .exe launchers 243 createLauncherForEntryPoint(params); 244 245 // copy the jars 246 copyApplication(params); 247 248 // copy in the needed libraries 249 Files.copy(WinResources.class.getResourceAsStream(LIBRARY_NAME), 250 root.resolve(LIBRARY_NAME)); 251 252 copyMSVCDLLs(); 253 254 // create the secondary launchers, if any 255 List<Map<String, ? super Object>> entryPoints = StandardBundlerParam.SECONDARY_LAUNCHERS.fetchFrom(params); 256 for (Map<String, ? super Object> entryPoint : entryPoints) { 257 Map<String, ? super Object> tmp = new HashMap<>(originalParams); 258 tmp.putAll(entryPoint); 259 createLauncherForEntryPoint(tmp); 260 } 261 262 } catch (IOException ex) { 263 Log.info("Exception: "+ex); 264 Log.debug(ex); 265 } finally { 266 267 if (VERBOSE.fetchFrom(params)) { 268 Log.info(MessageFormat.format(I18N.getString("message.config-save-location"), getConfigRoot(params).getAbsolutePath())); 269 } else { 270 cleanupConfigFiles(params); 271 } 272 } 273 274 } 275 276 private void copyMSVCDLLs() throws IOException { 277 String vsVer = null; 278 279 // first copy the ones needed for the launcher 280 for (String thisVer : VS_VERS) { 281 if (copyMSVCDLLs(thisVer)) { 282 vsVer = thisVer; 283 break; 284 } 285 } 286 if (vsVer == null) { 287 throw new RuntimeException("Not found MSVC dlls"); 288 } 289 290 AtomicReference<IOException> ioe = new AtomicReference<>(); 291 final String finalVsVer = vsVer; 292 Files.list(runtimeRoot.resolve("bin")) 293 .filter(p -> Pattern.matches("msvc(r|p)\\d\\d\\d.dll", p.toFile().getName().toLowerCase())) 294 .filter(p -> !p.toString().toLowerCase().endsWith(finalVsVer + ".dll")) 295 .forEach(p -> { 296 try { 297 Files.copy(p, root.resolve((p.toFile().getName()))); 298 } catch (IOException e) { 299 ioe.set(e); 300 } 301 }); 302 303 IOException e = ioe.get(); 304 if (e != null) { 305 throw e; 306 } 307 } 308 309 private boolean copyMSVCDLLs(String VS_VER) throws IOException { 310 final InputStream REDIST_MSVCR_URL = WinResources.class.getResourceAsStream( 311 REDIST_MSVCR.replaceAll("VS_VER", VS_VER)); 312 final InputStream REDIST_MSVCP_URL = WinResources.class.getResourceAsStream( 313 REDIST_MSVCP.replaceAll("VS_VER", VS_VER)); 314 315 if (REDIST_MSVCR_URL != null && REDIST_MSVCP_URL != null) { 316 Files.copy( 317 REDIST_MSVCR_URL, 318 root.resolve(REDIST_MSVCR.replaceAll("VS_VER", VS_VER))); 319 Files.copy( 320 REDIST_MSVCP_URL, 321 root.resolve(REDIST_MSVCP.replaceAll("VS_VER", VS_VER))); 322 return true; 323 } 324 325 return false; // not found 326 } 327 328 private void validateValueAndPut(Map<String, String> data, String key, 329 BundlerParamInfo<String> param, Map<String, ? super Object> params) 330 { 331 String value = param.fetchFrom(params); 332 if (value.contains("\r") || value.contains("\n")) { 333 Log.info("Configuration Parameter " + param.getID() + " contains multiple lines of text, ignore it"); 334 data.put(key, ""); 335 return; 336 } 337 data.put(key, value); 338 } 339 340 protected void prepareExecutableProperties(Map<String, ? super Object> params) 341 throws IOException 342 { 343 Map<String, String> data = new HashMap<>(); 344 345 // mapping Java parameters in strings for version resource 346 data.put("COMMENTS", ""); 347 validateValueAndPut(data, "COMPANY_NAME", VENDOR, params); 348 validateValueAndPut(data, "FILE_DESCRIPTION", DESCRIPTION, params); 349 validateValueAndPut(data, "FILE_VERSION", VERSION, params); 350 data.put("INTERNAL_NAME", getLauncherName(params)); 351 validateValueAndPut(data, "LEGAL_COPYRIGHT", COPYRIGHT, params); 352 data.put("LEGAL_TRADEMARK", ""); 353 data.put("ORIGINAL_FILENAME", getLauncherName(params)); 354 data.put("PRIVATE_BUILD", ""); 355 validateValueAndPut(data, "PRODUCT_NAME", APP_NAME, params); 356 validateValueAndPut(data, "PRODUCT_VERSION", VERSION, params); 357 data.put("SPECIAL_BUILD", ""); 358 359 Writer w = new BufferedWriter(new FileWriter(getConfig_ExecutableProperties(params))); 360 String content = preprocessTextResource( 361 WINDOWS_BUNDLER_PREFIX + getConfig_ExecutableProperties(params).getName(), 362 I18N.getString("resource.executable-properties-template"), EXECUTABLE_PROPERTIES_TEMPLATE, data, 363 VERBOSE.fetchFrom(params), 364 DROP_IN_RESOURCES_ROOT.fetchFrom(params)); 365 w.write(content); 366 w.close(); 367 } 368 369 private void createLauncherForEntryPoint(Map<String, ? super Object> p) throws IOException { 370 371 File icon = ICON_ICO.fetchFrom(params); 372 File iconTarget = getConfig_AppIcon(params); 373 374 InputStream in = locateResource("package/windows/" + APP_NAME.fetchFrom(params) + ".ico", 375 "icon", 376 TEMPLATE_APP_ICON, 377 icon, 378 VERBOSE.fetchFrom(params), 379 DROP_IN_RESOURCES_ROOT.fetchFrom(params)); 380 Files.copy(in, iconTarget.toPath()); 381 382 writeCfgFile(p, root.resolve(getLauncherCfgName(p)).toFile(), "$APPDIR\\runtime"); 383 384 prepareExecutableProperties(p); 385 386 // Copy executable root folder 387 Path executableFile = root.resolve(getLauncherName(p)); 388 writeEntry(WinResources.class.getResourceAsStream(EXECUTABLE_NAME), executableFile); 389 executableFile.toFile().setWritable(true, true); 390 391 //Update branding of exe file 392 if (REBRAND_EXECUTABLE.fetchFrom(p) && iconTarget.exists()) { 393 //extract IconSwap helper tool 394 File iconSwapTool = File.createTempFile("iconswap", ".exe"); 395 IOUtils.copyFromURL( 396 WinResources.class.getResource(TOOL_ICON_SWAP), 397 iconSwapTool, 398 true); 399 iconSwapTool.setExecutable(true, false); 400 iconSwapTool.deleteOnExit(); 401 402 //run it on launcher file 403 executableFile.toFile().setWritable(true); 404 ProcessBuilder pb = new ProcessBuilder( 405 iconSwapTool.getAbsolutePath(), 406 getConfig_AppIcon(p).getAbsolutePath(), 407 executableFile.toFile().getAbsolutePath()); 408 IOUtils.exec(pb, VERBOSE.fetchFrom(p)); 409 executableFile.toFile().setReadOnly(); 410 iconSwapTool.delete(); 411 } 412 413 Files.copy(iconTarget.toPath(), root.resolve(APP_NAME.fetchFrom(p) + ".ico")); 414 415 if (REBRAND_EXECUTABLE.fetchFrom(p) && getConfig_ExecutableProperties(p).exists()) { 416 // extract VersionInfoHelper tool 417 File versionInfoTool = File.createTempFile("versioninfoswap", ".exe"); 418 IOUtils.copyFromURL( 419 WinResources.class.getResource(TOOL_VERSION_INFO_SWAP), 420 versionInfoTool, 421 true); 422 versionInfoTool.setExecutable(true, false); 423 versionInfoTool.deleteOnExit(); 424 425 // run it on launcher file 426 executableFile.toFile().setWritable(true); 427 ProcessBuilder pb = new ProcessBuilder( 428 versionInfoTool.getAbsolutePath(), 429 getConfig_ExecutableProperties(p).getAbsolutePath(), 430 executableFile.toFile().getAbsolutePath()); 431 IOUtils.exec(pb, VERBOSE.fetchFrom(p)); 432 executableFile.toFile().setReadOnly(); 433 versionInfoTool.delete(); 434 } 435 } 436 437 private void copyApplication(Map<String, ? super Object> params) throws IOException { 438 List<RelativeFileSet> appResourcesList = APP_RESOURCES_LIST.fetchFrom(params); 439 if (appResourcesList == null) { 440 throw new RuntimeException("Null app resources?"); 441 } 442 for (RelativeFileSet appResources : appResourcesList) { 443 if (appResources == null) { 444 throw new RuntimeException("Null app resources?"); 445 } 446 File srcdir = appResources.getBaseDirectory(); 447 for (String fname : appResources.getIncludedFiles()) { 448 Files.copy(new File(srcdir, fname).toPath(), new File(appDir.toFile(), fname).toPath()); 449 } 450 } 451 } 452 453 @Override 454 protected String getCacheLocation(Map<String, ? super Object> params) { 455 return "$CACHEDIR/"; 456 } 457 458 }