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