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.FileOutputStream; 30 import java.io.IOException; 31 import java.io.InputStream; 32 import java.io.OutputStream; 33 import java.io.OutputStreamWriter; 34 import java.io.UncheckedIOException; 35 import java.io.Writer; 36 import java.io.BufferedWriter; 37 import java.io.FileWriter; 38 import java.nio.file.Files; 39 import java.nio.file.Path; 40 import java.nio.file.StandardCopyOption; 41 import java.nio.file.attribute.PosixFilePermission; 42 import java.text.MessageFormat; 43 import java.util.HashMap; 44 import java.util.List; 45 import java.util.Map; 46 import java.util.Objects; 47 import java.util.ResourceBundle; 48 import java.util.Set; 49 import java.util.concurrent.atomic.AtomicReference; 50 import java.util.regex.Pattern; 51 import java.util.stream.Stream; 52 53 import static jdk.jpackage.internal.StandardBundlerParam.*; 54 55 public class WindowsAppImageBuilder extends AbstractAppImageBuilder { 56 57 static { 58 System.loadLibrary("jpackage"); 59 } 60 61 private static final ResourceBundle I18N = ResourceBundle.getBundle( 62 "jdk.jpackage.internal.resources.WinResources"); 63 64 private final static String LIBRARY_NAME = "applauncher.dll"; 65 private final static String REDIST_MSVCR = "vcruntimeVS_VER.dll"; 66 private final static String REDIST_MSVCP = "msvcpVS_VER.dll"; 67 68 private final static String TEMPLATE_APP_ICON ="javalogo_white_48.ico"; 69 70 private static final String EXECUTABLE_PROPERTIES_TEMPLATE = 71 "WinLauncher.template"; 72 73 private final Path root; 74 private final Path appDir; 75 private final Path appModsDir; 76 private final Path runtimeDir; 77 private final Path mdir; 78 79 private final Map<String, ? super Object> params; 80 81 public static final BundlerParamInfo<Boolean> REBRAND_EXECUTABLE = 82 new WindowsBundlerParam<>( 83 "win.launcher.rebrand", 84 Boolean.class, 85 params -> Boolean.TRUE, 86 (s, p) -> Boolean.valueOf(s)); 87 88 public static final BundlerParamInfo<File> ICON_ICO = 89 new StandardBundlerParam<>( 90 "icon.ico", 91 File.class, 92 params -> { 93 File f = ICON.fetchFrom(params); 94 if (f != null && !f.getName().toLowerCase().endsWith(".ico")) { 95 Log.error(MessageFormat.format( 96 I18N.getString("message.icon-not-ico"), f)); 97 return null; 98 } 99 return f; 100 }, 101 (s, p) -> new File(s)); 102 103 public static final StandardBundlerParam<Boolean> CONSOLE_HINT = 104 new WindowsBundlerParam<>( 105 Arguments.CLIOptions.WIN_CONSOLE_HINT.getId(), 106 Boolean.class, 107 params -> false, 108 // valueOf(null) is false, 109 // and we actually do want null in some cases 110 (s, p) -> (s == null 111 || "null".equalsIgnoreCase(s)) ? true : Boolean.valueOf(s)); 112 113 public WindowsAppImageBuilder(Map<String, Object> config, Path imageOutDir) 114 throws IOException { 115 super(config, 116 imageOutDir.resolve(APP_NAME.fetchFrom(config) + "/runtime")); 117 118 Objects.requireNonNull(imageOutDir); 119 120 this.params = config; 121 122 this.root = imageOutDir.resolve(APP_NAME.fetchFrom(params)); 123 this.appDir = root.resolve("app"); 124 this.appModsDir = appDir.resolve("mods"); 125 this.runtimeDir = root.resolve("runtime"); 126 this.mdir = runtimeDir.resolve("lib"); 127 Files.createDirectories(appDir); 128 Files.createDirectories(runtimeDir); 129 } 130 131 public WindowsAppImageBuilder(String jreName, Path imageOutDir) 132 throws IOException { 133 super(null, imageOutDir.resolve(jreName)); 134 135 Objects.requireNonNull(imageOutDir); 136 137 this.params = null; 138 this.root = imageOutDir.resolve(jreName); 139 this.appDir = null; 140 this.appModsDir = null; 141 this.runtimeDir = root; 142 this.mdir = runtimeDir.resolve("lib"); 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 = 166 Files.getPosixFilePermissions(file); 167 perms.add(PosixFilePermission.OWNER_EXECUTE); 168 perms.add(PosixFilePermission.GROUP_EXECUTE); 169 perms.add(PosixFilePermission.OTHERS_EXECUTE); 170 Files.setPosixFilePermissions(file, perms); 171 } catch (IOException ioe) { 172 throw new UncheckedIOException(ioe); 173 } 174 } 175 176 private static void createUtf8File(File file, String content) 177 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 public static String getLauncherName(Map<String, ? super Object> p) { 185 return APP_NAME.fetchFrom(p) + ".exe"; 186 } 187 188 // Returns launcher resource name for launcher we need to use. 189 public static String getLauncherResourceName( 190 Map<String, ? super Object> p) { 191 if (CONSOLE_HINT.fetchFrom(p)) { 192 return "jpackageapplauncher.exe"; 193 } else { 194 return "jpackageapplauncherw.exe"; 195 } 196 } 197 198 public static String getLauncherCfgName(Map<String, ? super Object> p) { 199 return "app/" + APP_NAME.fetchFrom(p) +".cfg"; 200 } 201 202 private File getConfig_AppIcon(Map<String, ? super Object> params) { 203 return new File(getConfigRoot(params), 204 APP_NAME.fetchFrom(params) + ".ico"); 205 } 206 207 private File getConfig_ExecutableProperties( 208 Map<String, ? super Object> params) { 209 return new File(getConfigRoot(params), 210 APP_NAME.fetchFrom(params) + ".properties"); 211 } 212 213 File getConfigRoot(Map<String, ? super Object> params) { 214 return CONFIG_ROOT.fetchFrom(params); 215 } 216 217 @Override 218 public Path getAppDir() { 219 return appDir; 220 } 221 222 @Override 223 public Path getAppModsDir() { 224 return appModsDir; 225 } 226 227 @Override 228 public void prepareApplicationFiles() throws IOException { 229 Map<String, ? super Object> originalParams = new HashMap<>(params); 230 File rootFile = root.toFile(); 231 if (!rootFile.isDirectory() && !rootFile.mkdirs()) { 232 throw new RuntimeException(MessageFormat.format(I18N.getString( 233 "error.cannot-create-output-dir"), rootFile.getAbsolutePath())); 234 } 235 if (!rootFile.canWrite()) { 236 throw new RuntimeException(MessageFormat.format( 237 I18N.getString("error.cannot-write-to-output-dir"), 238 rootFile.getAbsolutePath())); 239 } 240 // create the .exe launchers 241 createLauncherForEntryPoint(params); 242 243 // copy the jars 244 copyApplication(params); 245 246 // copy in the needed libraries 247 try (InputStream is_lib = getResourceAsStream(LIBRARY_NAME)) { 248 Files.copy(is_lib, root.resolve(LIBRARY_NAME)); 249 } 250 251 copyMSVCDLLs(); 252 253 // create the additional launcher(s), if any 254 List<Map<String, ? super Object>> entryPoints = 255 StandardBundlerParam.ADD_LAUNCHERS.fetchFrom(params); 256 for (Map<String, ? super Object> entryPoint : entryPoints) { 257 createLauncherForEntryPoint( 258 AddLauncherArguments.merge(originalParams, entryPoint)); 259 } 260 } 261 262 @Override 263 public void prepareJreFiles() throws IOException {} 264 265 private void copyMSVCDLLs() throws IOException { 266 AtomicReference<IOException> ioe = new AtomicReference<>(); 267 try (Stream<Path> files = Files.list(runtimeDir.resolve("bin"))) { 268 files.filter(p -> Pattern.matches( 269 "^(vcruntime|msvcp|msvcr|ucrtbase|api-ms-win-).*\\.dll$", 270 p.toFile().getName().toLowerCase())) 271 .forEach(p -> { 272 try { 273 Files.copy(p, root.resolve((p.toFile().getName()))); 274 } catch (IOException e) { 275 ioe.set(e); 276 } 277 }); 278 } 279 280 IOException e = ioe.get(); 281 if (e != null) { 282 throw e; 283 } 284 } 285 286 // TODO: do we still need this? 287 private boolean copyMSVCDLLs(String VS_VER) throws IOException { 288 final InputStream REDIST_MSVCR_URL = getResourceAsStream( 289 REDIST_MSVCR.replaceAll("VS_VER", VS_VER)); 290 final InputStream REDIST_MSVCP_URL = getResourceAsStream( 291 REDIST_MSVCP.replaceAll("VS_VER", VS_VER)); 292 293 if (REDIST_MSVCR_URL != null && REDIST_MSVCP_URL != null) { 294 Files.copy( 295 REDIST_MSVCR_URL, 296 root.resolve(REDIST_MSVCR.replaceAll("VS_VER", VS_VER))); 297 Files.copy( 298 REDIST_MSVCP_URL, 299 root.resolve(REDIST_MSVCP.replaceAll("VS_VER", VS_VER))); 300 return true; 301 } 302 303 return false; 304 } 305 306 private void validateValueAndPut( 307 Map<String, String> data, String key, 308 BundlerParamInfo<String> param, 309 Map<String, ? super Object> params) { 310 String value = param.fetchFrom(params); 311 if (value.contains("\r") || value.contains("\n")) { 312 Log.error("Configuration Parameter " + param.getID() 313 + " contains multiple lines of text, ignore it"); 314 data.put(key, ""); 315 return; 316 } 317 data.put(key, value); 318 } 319 320 protected void prepareExecutableProperties( 321 Map<String, ? super Object> params) throws IOException { 322 Map<String, String> data = new HashMap<>(); 323 324 // mapping Java parameters in strings for version resource 325 validateValueAndPut(data, "COMPANY_NAME", VENDOR, params); 326 validateValueAndPut(data, "FILE_DESCRIPTION", DESCRIPTION, params); 327 validateValueAndPut(data, "FILE_VERSION", VERSION, params); 328 data.put("INTERNAL_NAME", getLauncherName(params)); 329 validateValueAndPut(data, "LEGAL_COPYRIGHT", COPYRIGHT, params); 330 data.put("ORIGINAL_FILENAME", getLauncherName(params)); 331 validateValueAndPut(data, "PRODUCT_NAME", APP_NAME, params); 332 validateValueAndPut(data, "PRODUCT_VERSION", VERSION, params); 333 334 try (Writer w = new BufferedWriter( 335 new FileWriter(getConfig_ExecutableProperties(params)))) { 336 String content = preprocessTextResource( 337 getConfig_ExecutableProperties(params).getName(), 338 I18N.getString("resource.executable-properties-template"), 339 EXECUTABLE_PROPERTIES_TEMPLATE, data, 340 VERBOSE.fetchFrom(params), 341 RESOURCE_DIR.fetchFrom(params)); 342 w.write(content); 343 } 344 } 345 346 private void createLauncherForEntryPoint( 347 Map<String, ? super Object> p) throws IOException { 348 349 File launcherIcon = ICON_ICO.fetchFrom(p); 350 File icon = launcherIcon != null ? 351 launcherIcon : ICON_ICO.fetchFrom(params); 352 File iconTarget = getConfig_AppIcon(p); 353 354 InputStream in = locateResource( 355 APP_NAME.fetchFrom(params) + ".ico", 356 "icon", 357 TEMPLATE_APP_ICON, 358 icon, 359 VERBOSE.fetchFrom(params), 360 RESOURCE_DIR.fetchFrom(params)); 361 362 Files.copy(in, iconTarget.toPath(), 363 StandardCopyOption.REPLACE_EXISTING); 364 365 writeCfgFile(p, root.resolve( 366 getLauncherCfgName(p)).toFile(), "$APPDIR\\runtime"); 367 368 prepareExecutableProperties(p); 369 370 // Copy executable root folder 371 Path executableFile = root.resolve(getLauncherName(p)); 372 try (InputStream is_launcher = 373 getResourceAsStream(getLauncherResourceName(p))) { 374 writeEntry(is_launcher, executableFile); 375 } 376 377 File launcher = executableFile.toFile(); 378 launcher.setWritable(true, true); 379 380 // Update branding of EXE file 381 if (REBRAND_EXECUTABLE.fetchFrom(p)) { 382 try { 383 String tempDirectory = WindowsDefender.getUserTempDirectory(); 384 if (Arguments.CLIOptions.context().userProvidedBuildRoot) { 385 tempDirectory = TEMP_ROOT.fetchFrom(p).getAbsolutePath(); 386 } 387 if (WindowsDefender.isThereAPotentialWindowsDefenderIssue( 388 tempDirectory)) { 389 Log.error(MessageFormat.format(I18N.getString( 390 "message.potential.windows.defender.issue"), 391 tempDirectory)); 392 } 393 394 launcher.setWritable(true); 395 396 if (iconTarget.exists()) { 397 iconSwap(iconTarget.getAbsolutePath(), 398 launcher.getAbsolutePath()); 399 } 400 401 File executableProperties = getConfig_ExecutableProperties(p); 402 403 if (executableProperties.exists()) { 404 if (versionSwap(executableProperties.getAbsolutePath(), 405 launcher.getAbsolutePath()) != 0) { 406 throw new RuntimeException(MessageFormat.format( 407 I18N.getString("error.version-swap"), 408 executableProperties.getAbsolutePath())); 409 } 410 } 411 } finally { 412 executableFile.toFile().setReadOnly(); 413 } 414 } 415 416 Files.copy(iconTarget.toPath(), 417 root.resolve(APP_NAME.fetchFrom(p) + ".ico")); 418 } 419 420 private void copyApplication(Map<String, ? super Object> params) 421 throws IOException { 422 List<RelativeFileSet> appResourcesList = 423 APP_RESOURCES_LIST.fetchFrom(params); 424 if (appResourcesList == null) { 425 throw new RuntimeException("Null app resources?"); 426 } 427 for (RelativeFileSet appResources : appResourcesList) { 428 if (appResources == null) { 429 throw new RuntimeException("Null app resources?"); 430 } 431 File srcdir = appResources.getBaseDirectory(); 432 for (String fname : appResources.getIncludedFiles()) { 433 copyEntry(appDir, srcdir, fname); 434 } 435 } 436 } 437 438 private static native int iconSwap(String iconTarget, String launcher); 439 440 private static native int versionSwap(String executableProperties, String launcher); 441 442 }