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 
  26 package jdk.tools.jlink.builder;
  27 
  28 import java.io.BufferedOutputStream;
  29 import java.io.BufferedWriter;
  30 import java.io.ByteArrayInputStream;
  31 import java.io.DataOutputStream;
  32 import java.io.File;
  33 import java.io.FileInputStream;
  34 import java.io.FileOutputStream;
  35 import java.io.IOException;
  36 import java.io.InputStream;
  37 import java.io.OutputStream;
  38 import java.io.OutputStreamWriter;
  39 import java.io.UncheckedIOException;
  40 import java.io.Writer;
  41 import java.lang.module.ModuleDescriptor;
  42 import java.nio.charset.StandardCharsets;
  43 import java.nio.file.FileAlreadyExistsException;
  44 import java.nio.file.Files;
  45 import java.nio.file.Path;
  46 import java.nio.file.Paths;
  47 import java.nio.file.StandardOpenOption;
  48 import java.nio.file.attribute.PosixFilePermission;
  49 import java.util.Collections;
  50 import java.util.HashMap;
  51 import java.util.HashSet;
  52 import java.util.List;
  53 import java.util.Map;
  54 import java.util.Objects;
  55 import java.util.Optional;
  56 import java.util.Properties;
  57 import java.util.Set;
  58 import static java.util.stream.Collectors.*;
  59 
  60 import jdk.tools.jlink.internal.BasicImageWriter;
  61 import jdk.tools.jlink.internal.ExecutableImage;
  62 import jdk.tools.jlink.plugin.ResourcePool;
  63 import jdk.tools.jlink.plugin.ResourcePoolEntry;
  64 import jdk.tools.jlink.plugin.ResourcePoolEntry.Type;
  65 import jdk.tools.jlink.plugin.ResourcePoolModule;
  66 import jdk.tools.jlink.plugin.PluginException;
  67 
  68 /**
  69  *
  70  * Default Image Builder. This builder creates the default runtime image layout.
  71  */
  72 public final class DefaultImageBuilder implements ImageBuilder {
  73     // Top-level directory names in a modular runtime image
  74     public static final String BIN_DIRNAME      = "bin";
  75     public static final String CONF_DIRNAME     = "conf";
  76     public static final String INCLUDE_DIRNAME  = "include";
  77     public static final String LIB_DIRNAME      = "lib";
  78     public static final String LEGAL_DIRNAME    = "legal";
  79     public static final String MAN_DIRNAME      = "man";
  80 
  81     /**
  82      * The default java executable Image.
  83      */
  84     static final class DefaultExecutableImage implements ExecutableImage {
  85 
  86         private final Path home;
  87         private final List<String> args;
  88         private final Set<String> modules;
  89 
  90         DefaultExecutableImage(Path home, Set<String> modules) {
  91             Objects.requireNonNull(home);
  92             if (!Files.exists(home)) {
  93                 throw new IllegalArgumentException("Invalid image home");
  94             }
  95             this.home = home;
  96             this.modules = Collections.unmodifiableSet(modules);
  97             this.args = createArgs(home);
  98         }
  99 
 100         private static List<String> createArgs(Path home) {
 101             Objects.requireNonNull(home);
 102             Path binDir = home.resolve("bin");
 103             String java = Files.exists(binDir.resolve("java"))? "java" : "java.exe";
 104             return List.of(binDir.resolve(java).toString());
 105         }
 106 
 107         @Override
 108         public Path getHome() {
 109             return home;
 110         }
 111 
 112         @Override
 113         public Set<String> getModules() {
 114             return modules;
 115         }
 116 
 117         @Override
 118         public List<String> getExecutionArgs() {
 119             return args;
 120         }
 121 
 122         @Override
 123         public void storeLaunchArgs(List<String> args) {
 124             try {
 125                 patchScripts(this, args);
 126             } catch (IOException ex) {
 127                 throw new UncheckedIOException(ex);
 128             }
 129         }
 130     }
 131 
 132     private final Path root;
 133     private final Map<String, String> launchers;
 134     private final Path mdir;
 135     private final Set<String> modules = new HashSet<>();
 136     private String targetOsName;
 137 
 138     /**
 139      * Default image builder constructor.
 140      *
 141      * @param root The image root directory.
 142      * @throws IOException
 143      */
 144     public DefaultImageBuilder(Path root, Map<String, String> launchers) throws IOException {
 145         this.root = Objects.requireNonNull(root);
 146         this.launchers = Objects.requireNonNull(launchers);
 147         this.mdir = root.resolve("lib");
 148         Files.createDirectories(mdir);
 149     }
 150 
 151     @Override
 152     public void storeFiles(ResourcePool files) {
 153         try {
 154             // populate targetOsName field up-front because it's used elsewhere.
 155             Optional<ResourcePoolModule> javaBase = files.moduleView().findModule("java.base");
 156             javaBase.ifPresent(mod -> {
 157                 // fill release information available from transformed "java.base" module!
 158                 ModuleDescriptor desc = mod.descriptor();
 159                 desc.osName().ifPresent(s -> {
 160                     this.targetOsName = s;
 161                 });
 162             });
 163 
 164             if (this.targetOsName == null) {
 165                 throw new PluginException("TargetPlatform attribute is missing for java.base module");
 166             }
 167 
 168             Path bin = root.resolve(BIN_DIRNAME);
 169 
 170             // check any duplicated resource files
 171             Map<Path, Set<String>> duplicates = new HashMap<>();
 172             files.entries()
 173                 .filter(f -> f.type() != ResourcePoolEntry.Type.CLASS_OR_RESOURCE)
 174                 .collect(groupingBy(this::entryToImagePath,
 175                          mapping(ResourcePoolEntry::moduleName, toSet())))
 176                 .entrySet()
 177                 .stream()
 178                 .filter(e -> e.getValue().size() > 1)
 179                 .forEach(e -> duplicates.put(e.getKey(), e.getValue()));
 180 
 181             // write non-classes resource files to the image
 182             files.entries()
 183                 .filter(f -> f.type() != ResourcePoolEntry.Type.CLASS_OR_RESOURCE)
 184                 .forEach(f -> {
 185                     try {
 186                         accept(f);
 187                     } catch (FileAlreadyExistsException e) {
 188                         // error for duplicated entries
 189                         Path path = entryToImagePath(f);
 190                         UncheckedIOException x =
 191                             new UncheckedIOException(path + " duplicated in " +
 192                                     duplicates.get(path), e);
 193                         x.addSuppressed(e);
 194                         throw x;
 195                     } catch (IOException ioExp) {
 196                         throw new UncheckedIOException(ioExp);
 197                     }
 198                 });
 199 
 200             files.moduleView().modules().forEach(m -> {
 201                 // Only add modules that contain packages
 202                 if (!m.packages().isEmpty()) {
 203                     modules.add(m.name());
 204                 }
 205             });
 206 
 207             if (root.getFileSystem().supportedFileAttributeViews()
 208                     .contains("posix")) {
 209                 // launchers in the bin directory need execute permission.
 210                 // On Windows, "bin" also subdirectories containing jvm.dll.
 211                 if (Files.isDirectory(bin)) {
 212                     Files.find(bin, 2, (path, attrs) -> {
 213                         return attrs.isRegularFile() && !path.toString().endsWith(".diz");
 214                     }).forEach(this::setExecutable);
 215                 }
 216 
 217                 // jspawnhelper is in lib or lib/<arch>
 218                 Path lib = root.resolve(LIB_DIRNAME);
 219                 if (Files.isDirectory(lib)) {
 220                     Files.find(lib, 2, (path, attrs) -> {
 221                         return path.getFileName().toString().equals("jspawnhelper")
 222                                 || path.getFileName().toString().equals("jexec");
 223                     }).forEach(this::setExecutable);
 224                 }
 225 
 226                 // read-only legal notices/license files
 227                 Path legal = root.resolve(LEGAL_DIRNAME);
 228                 if (Files.isDirectory(legal)) {
 229                     Files.find(legal, 2, (path, attrs) -> {
 230                         return attrs.isRegularFile();
 231                     }).forEach(this::setReadOnly);
 232                 }
 233             }
 234 
 235             // If native files are stripped completely, <root>/bin dir won't exist!
 236             // So, don't bother generating launcher scripts.
 237             if (Files.isDirectory(bin)) {
 238                  prepareApplicationFiles(files);
 239             }
 240         } catch (IOException ex) {
 241             throw new PluginException(ex);
 242         }
 243     }
 244 
 245     /**
 246      * Generates launcher scripts.
 247      *
 248      * @param imageContent The image content.
 249      * @throws IOException
 250      */
 251     protected void prepareApplicationFiles(ResourcePool imageContent) throws IOException {
 252         // generate launch scripts for the modules with a main class
 253         for (Map.Entry<String, String> entry : launchers.entrySet()) {
 254             String launcherEntry = entry.getValue();
 255             int slashIdx = launcherEntry.indexOf("/");
 256             String module, mainClassName;
 257             if (slashIdx == -1) {
 258                 module = launcherEntry;
 259                 mainClassName = null;
 260             } else {
 261                 module = launcherEntry.substring(0, slashIdx);
 262                 assert !module.isEmpty();
 263                 mainClassName = launcherEntry.substring(slashIdx + 1);
 264                 assert !mainClassName.isEmpty();
 265             }
 266 
 267             String path = "/" + module + "/module-info.class";
 268             Optional<ResourcePoolEntry> res = imageContent.findEntry(path);
 269             if (!res.isPresent()) {
 270                 throw new IOException("module-info.class not found for " + module + " module");
 271             }
 272             ByteArrayInputStream stream = new ByteArrayInputStream(res.get().contentBytes());
 273             Optional<String> mainClass = ModuleDescriptor.read(stream).mainClass();
 274             if (mainClassName == null && mainClass.isPresent()) {
 275                 mainClassName = mainClass.get();
 276             }
 277 
 278             if (mainClassName != null) {
 279                 // make sure main class exists!
 280                 if (!imageContent.findEntry("/" + module + "/" +
 281                         mainClassName.replace('.', '/') + ".class").isPresent()) {
 282                     throw new IllegalArgumentException(module + " does not have main class: " + mainClassName);
 283                 }
 284 
 285                 String launcherFile = entry.getKey();
 286                 Path cmd = root.resolve("bin").resolve(launcherFile);
 287                 // generate shell script for Unix platforms
 288                 StringBuilder sb = new StringBuilder();
 289                 sb.append("#!/bin/sh")
 290                         .append("\n");
 291                 sb.append("JLINK_VM_OPTIONS=")
 292                         .append("\n");
 293                 sb.append("DIR=`dirname $0`")
 294                         .append("\n");
 295                 sb.append("$DIR/java $JLINK_VM_OPTIONS -m ")
 296                         .append(module).append('/')
 297                         .append(mainClassName)
 298                         .append(" $@\n");
 299 
 300                 try (BufferedWriter writer = Files.newBufferedWriter(cmd,
 301                         StandardCharsets.ISO_8859_1,
 302                         StandardOpenOption.CREATE_NEW)) {
 303                     writer.write(sb.toString());
 304                 }
 305                 if (root.resolve("bin").getFileSystem()
 306                         .supportedFileAttributeViews().contains("posix")) {
 307                     setExecutable(cmd);
 308                 }
 309                 // generate .bat file for Windows
 310                 if (isWindows()) {
 311                     Path bat = root.resolve(BIN_DIRNAME).resolve(launcherFile + ".bat");
 312                     sb = new StringBuilder();
 313                     sb.append("@echo off")
 314                             .append("\r\n");
 315                     sb.append("set JLINK_VM_OPTIONS=")
 316                             .append("\r\n");
 317                     sb.append("set DIR=%~dp0")
 318                             .append("\r\n");
 319                     sb.append("\"%DIR%\\java\" %JLINK_VM_OPTIONS% -m ")
 320                             .append(module).append('/')
 321                             .append(mainClassName)
 322                             .append(" %*\r\n");
 323 
 324                     try (BufferedWriter writer = Files.newBufferedWriter(bat,
 325                             StandardCharsets.ISO_8859_1,
 326                             StandardOpenOption.CREATE_NEW)) {
 327                         writer.write(sb.toString());
 328                     }
 329                 }
 330             } else {
 331                 throw new IllegalArgumentException(module + " doesn't contain main class & main not specified in command line");
 332             }
 333         }
 334     }
 335 
 336     @Override
 337     public DataOutputStream getJImageOutputStream() {
 338         try {
 339             Path jimageFile = mdir.resolve(BasicImageWriter.MODULES_IMAGE_NAME);
 340             OutputStream fos = Files.newOutputStream(jimageFile);
 341             BufferedOutputStream bos = new BufferedOutputStream(fos);
 342             return new DataOutputStream(bos);
 343         } catch (IOException ex) {
 344             throw new UncheckedIOException(ex);
 345         }
 346     }
 347 
 348     /**
 349      * Returns the file name of this entry
 350      */
 351     private String entryToFileName(ResourcePoolEntry entry) {
 352         if (entry.type() == ResourcePoolEntry.Type.CLASS_OR_RESOURCE)
 353             throw new IllegalArgumentException("invalid type: " + entry);
 354 
 355         String module = "/" + entry.moduleName() + "/";
 356         String filename = entry.path().substring(module.length());
 357 
 358         // Remove radical native|config|...
 359         return filename.substring(filename.indexOf('/') + 1);
 360     }
 361 
 362     /**
 363      * Returns the path of the given entry to be written in the image
 364      */
 365     private Path entryToImagePath(ResourcePoolEntry entry) {
 366         switch (entry.type()) {
 367             case NATIVE_LIB:
 368                 String filename = entryToFileName(entry);
 369                 return Paths.get(nativeDir(filename), filename);
 370             case NATIVE_CMD:
 371                 return Paths.get(BIN_DIRNAME, entryToFileName(entry));
 372             case CONFIG:
 373                 return Paths.get(CONF_DIRNAME, entryToFileName(entry));
 374             case HEADER_FILE:
 375                 return Paths.get(INCLUDE_DIRNAME, entryToFileName(entry));
 376             case MAN_PAGE:
 377                 return Paths.get(MAN_DIRNAME, entryToFileName(entry));
 378             case LEGAL_NOTICE:
 379                 return Paths.get(LEGAL_DIRNAME, entryToFileName(entry));
 380             case TOP:
 381                 return Paths.get(entryToFileName(entry));
 382             default:
 383                 throw new IllegalArgumentException("invalid type: " + entry);
 384         }
 385     }
 386 
 387     private void accept(ResourcePoolEntry file) throws IOException {
 388         if (file.linkedTarget() != null && file.type() != Type.LEGAL_NOTICE) {
 389             throw new UnsupportedOperationException("symbolic link not implemented: " + file);
 390         }
 391 
 392         try (InputStream in = file.content()) {
 393             switch (file.type()) {
 394                 case NATIVE_LIB:
 395                     Path dest = root.resolve(entryToImagePath(file));
 396                     writeEntry(in, dest);
 397                     break;
 398                 case NATIVE_CMD:
 399                     Path p = root.resolve(entryToImagePath(file));
 400                     writeEntry(in, p);
 401                     p.toFile().setExecutable(true);
 402                     break;
 403                 case CONFIG:
 404                 case HEADER_FILE:
 405                 case MAN_PAGE:
 406                     writeEntry(in, root.resolve(entryToImagePath(file)));
 407                     break;
 408                 case LEGAL_NOTICE:
 409                     Path source = entryToImagePath(file);
 410                     if (file.linkedTarget() == null) {
 411                         writeEntry(in, root.resolve(source));
 412                     } else {
 413                         Path target = entryToImagePath(file.linkedTarget());
 414                         Path relPath = source.getParent().relativize(target);
 415                         writeSymLinkEntry(root.resolve(source), relPath);
 416                     }
 417                     break;
 418                 case TOP:
 419                     // Copy TOP files of the "java.base" module (only)
 420                     if ("java.base".equals(file.moduleName())) {
 421                         writeEntry(in, root.resolve(entryToImagePath(file)));
 422                     } else {
 423                         throw new InternalError("unexpected TOP entry: " + file.path());
 424                     }
 425                     break;
 426                 default:
 427                     throw new InternalError("unexpected entry: " + file.path());
 428             }
 429         }
 430     }
 431 
 432     private void writeEntry(InputStream in, Path dstFile) throws IOException {
 433         Objects.requireNonNull(in);
 434         Objects.requireNonNull(dstFile);
 435         Files.createDirectories(Objects.requireNonNull(dstFile.getParent()));
 436         Files.copy(in, dstFile);
 437     }
 438 
 439     private void writeSymEntry(Path dstFile, Path target) throws IOException {
 440         Objects.requireNonNull(dstFile);
 441         Objects.requireNonNull(target);
 442         Files.createDirectories(Objects.requireNonNull(dstFile.getParent()));
 443         Files.createLink(dstFile, target);
 444     }
 445 
 446     /*
 447      * Create a symbolic link to the given target if the target platform
 448      * supports symbolic link; otherwise, it will create a tiny file
 449      * to contain the path to the target.
 450      */
 451     private void writeSymLinkEntry(Path dstFile, Path target) throws IOException {
 452         Objects.requireNonNull(dstFile);
 453         Objects.requireNonNull(target);
 454         Files.createDirectories(Objects.requireNonNull(dstFile.getParent()));
 455         if (!isWindows() && root.getFileSystem()
 456                                 .supportedFileAttributeViews()
 457                                 .contains("posix")) {
 458             Files.createSymbolicLink(dstFile, target);
 459         } else {
 460             try (BufferedWriter writer = Files.newBufferedWriter(dstFile)) {
 461                 writer.write(String.format("Please see %s%n", target.toString()));
 462             }
 463         }
 464     }
 465 
 466     private String nativeDir(String filename) {
 467         if (isWindows()) {
 468             if (filename.endsWith(".dll") || filename.endsWith(".diz")
 469                     || filename.endsWith(".pdb") || filename.endsWith(".map")) {
 470                 return BIN_DIRNAME;
 471             } else {
 472                 return LIB_DIRNAME;
 473             }
 474         } else {
 475             return LIB_DIRNAME;
 476         }
 477     }
 478 
 479     private boolean isWindows() {
 480         return targetOsName.startsWith("Windows");
 481     }
 482 
 483     /**
 484      * chmod ugo+x file
 485      */
 486     private void setExecutable(Path file) {
 487         try {
 488             Set<PosixFilePermission> perms = Files.getPosixFilePermissions(file);
 489             perms.add(PosixFilePermission.OWNER_EXECUTE);
 490             perms.add(PosixFilePermission.GROUP_EXECUTE);
 491             perms.add(PosixFilePermission.OTHERS_EXECUTE);
 492             Files.setPosixFilePermissions(file, perms);
 493         } catch (IOException ioe) {
 494             throw new UncheckedIOException(ioe);
 495         }
 496     }
 497 
 498     /**
 499      * chmod ugo-w file
 500      */
 501     private void setReadOnly(Path file) {
 502         try {
 503             Set<PosixFilePermission> perms = Files.getPosixFilePermissions(file);
 504             perms.remove(PosixFilePermission.OWNER_WRITE);
 505             perms.remove(PosixFilePermission.GROUP_WRITE);
 506             perms.remove(PosixFilePermission.OTHERS_WRITE);
 507             Files.setPosixFilePermissions(file, perms);
 508         } catch (IOException ioe) {
 509             throw new UncheckedIOException(ioe);
 510         }
 511     }
 512 
 513     private static void createUtf8File(File file, String content) throws IOException {
 514         try (OutputStream fout = new FileOutputStream(file);
 515                 Writer output = new OutputStreamWriter(fout, "UTF-8")) {
 516             output.write(content);
 517         }
 518     }
 519 
 520     @Override
 521     public ExecutableImage getExecutableImage() {
 522         return new DefaultExecutableImage(root, modules);
 523     }
 524 
 525     // This is experimental, we should get rid-off the scripts in a near future
 526     private static void patchScripts(ExecutableImage img, List<String> args) throws IOException {
 527         Objects.requireNonNull(args);
 528         if (!args.isEmpty()) {
 529             Files.find(img.getHome().resolve(BIN_DIRNAME), 2, (path, attrs) -> {
 530                 return img.getModules().contains(path.getFileName().toString());
 531             }).forEach((p) -> {
 532                 try {
 533                     String pattern = "JLINK_VM_OPTIONS=";
 534                     byte[] content = Files.readAllBytes(p);
 535                     String str = new String(content, StandardCharsets.UTF_8);
 536                     int index = str.indexOf(pattern);
 537                     StringBuilder builder = new StringBuilder();
 538                     if (index != -1) {
 539                         builder.append(str.substring(0, index)).
 540                                 append(pattern);
 541                         for (String s : args) {
 542                             builder.append(s).append(" ");
 543                         }
 544                         String remain = str.substring(index + pattern.length());
 545                         builder.append(remain);
 546                         str = builder.toString();
 547                         try (BufferedWriter writer = Files.newBufferedWriter(p,
 548                                 StandardCharsets.ISO_8859_1,
 549                                 StandardOpenOption.WRITE)) {
 550                             writer.write(str);
 551                         }
 552                     }
 553                 } catch (IOException ex) {
 554                     throw new RuntimeException(ex);
 555                 }
 556             });
 557         }
 558     }
 559 
 560     public static ExecutableImage getExecutableImage(Path root) {
 561         Path binDir = root.resolve(BIN_DIRNAME);
 562         if (Files.exists(binDir.resolve("java")) ||
 563             Files.exists(binDir.resolve("java.exe"))) {
 564             return new DefaultExecutableImage(root, retrieveModules(root));
 565         }
 566         return null;
 567     }
 568 
 569     private static Set<String> retrieveModules(Path root) {
 570         Path releaseFile = root.resolve("release");
 571         Set<String> modules = new HashSet<>();
 572         if (Files.exists(releaseFile)) {
 573             Properties release = new Properties();
 574             try (FileInputStream fi = new FileInputStream(releaseFile.toFile())) {
 575                 release.load(fi);
 576             } catch (IOException ex) {
 577                 System.err.println("Can't read release file " + ex);
 578             }
 579             String mods = release.getProperty("MODULES");
 580             if (mods != null) {
 581                 String[] arr = mods.substring(1, mods.length() - 1).split(" ");
 582                 for (String m : arr) {
 583                     modules.add(m.trim());
 584                 }
 585 
 586             }
 587         }
 588         return modules;
 589     }
 590 }