1 /*
   2  * Copyright (c) 2015, 2016, 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.tools.jlink.internal;
  26 
  27 import java.io.File;
  28 import java.io.IOException;
  29 import java.io.PrintWriter;
  30 import java.io.UncheckedIOException;
  31 import java.lang.module.Configuration;
  32 import java.lang.module.ModuleFinder;
  33 import java.lang.module.ModuleReference;
  34 import java.lang.module.ResolutionException;
  35 import java.lang.module.ResolvedModule;
  36 import java.lang.reflect.InvocationTargetException;
  37 import java.net.URI;
  38 import java.nio.ByteOrder;
  39 import java.nio.file.Files;
  40 import java.nio.file.Path;
  41 import java.nio.file.Paths;
  42 import java.util.Date;
  43 import java.util.Formatter;
  44 import java.util.HashMap;
  45 import java.util.HashSet;
  46 import java.util.List;
  47 import java.util.Map;
  48 import java.util.Objects;
  49 import java.util.Optional;
  50 import java.util.Set;
  51 import java.util.stream.Collectors;
  52 
  53 import jdk.internal.module.ConfigurableModuleFinder;
  54 import jdk.internal.module.ConfigurableModuleFinder.Phase;
  55 import jdk.tools.jlink.internal.TaskHelper.BadArgs;
  56 import static jdk.tools.jlink.internal.TaskHelper.JLINK_BUNDLE;
  57 import jdk.tools.jlink.internal.TaskHelper.Option;
  58 import jdk.tools.jlink.internal.TaskHelper.OptionsHelper;
  59 import jdk.tools.jlink.internal.ImagePluginStack.ImageProvider;
  60 import jdk.tools.jlink.plugin.ExecutableImage;
  61 import jdk.tools.jlink.Jlink.JlinkConfiguration;
  62 import jdk.tools.jlink.Jlink.PluginsConfiguration;
  63 import jdk.tools.jlink.plugin.PluginException;
  64 import jdk.tools.jlink.builder.DefaultImageBuilder;
  65 import jdk.tools.jlink.plugin.Plugin;
  66 
  67 /**
  68  * Implementation for the jlink tool.
  69  *
  70  * ## Should use jdk.joptsimple some day.
  71  */
  72 public class JlinkTask {
  73 
  74     private static <T extends Throwable> void fail(Class<T> type,
  75             String format,
  76             Object... args) throws T {
  77         String msg = new Formatter().format(format, args).toString();
  78         try {
  79             T t = type.getConstructor(String.class).newInstance(msg);
  80             throw t;
  81         } catch (InstantiationException |
  82                 InvocationTargetException |
  83                 NoSuchMethodException |
  84                 IllegalAccessException e) {
  85             throw new InternalError("Unable to create an instance of " + type, e);
  86         }
  87     }
  88 
  89     private static final TaskHelper taskHelper
  90             = new TaskHelper(JLINK_BUNDLE);
  91 
  92     static Option<?>[] recognizedOptions = {
  93         new Option<JlinkTask>(false, (task, opt, arg) -> {
  94             task.options.help = true;
  95         }, "--help"),
  96         new Option<JlinkTask>(true, (task, opt, arg) -> {
  97             String[] dirs = arg.split(File.pathSeparator);
  98             task.options.modulePath = new Path[dirs.length];
  99             int i = 0;
 100             for (String dir : dirs) {
 101                 task.options.modulePath[i++] = Paths.get(dir);
 102             }
 103         }, "--modulepath", "--mp"),
 104         new Option<JlinkTask>(true, (task, opt, arg) -> {
 105             for (String mn : arg.split(",")) {
 106                 if (mn.isEmpty()) {
 107                     throw taskHelper.newBadArgs("err.mods.must.be.specified",
 108                             "--limitmods");
 109                 }
 110                 task.options.limitMods.add(mn);
 111             }
 112         }, "--limitmods"),
 113         new Option<JlinkTask>(true, (task, opt, arg) -> {
 114             for (String mn : arg.split(",")) {
 115                 if (mn.isEmpty()) {
 116                     throw taskHelper.newBadArgs("err.mods.must.be.specified",
 117                             "--addmods");
 118                 }
 119                 task.options.addMods.add(mn);
 120             }
 121         }, "--addmods"),
 122         new Option<JlinkTask>(true, (task, opt, arg) -> {
 123             Path path = Paths.get(arg);
 124             task.options.output = path;
 125         }, "--output"),
 126         new Option<JlinkTask>(true, (task, opt, arg) -> {
 127             if ("little".equals(arg)) {
 128                 task.options.endian = ByteOrder.LITTLE_ENDIAN;
 129             } else if ("big".equals(arg)) {
 130                 task.options.endian = ByteOrder.BIG_ENDIAN;
 131             } else {
 132                 throw taskHelper.newBadArgs("err.unknown.byte.order", arg);
 133             }
 134         }, "--endian"),
 135         new Option<JlinkTask>(false, (task, opt, arg) -> {
 136             task.options.version = true;
 137         }, "--version"),
 138         new Option<JlinkTask>(true, (task, opt, arg) -> {
 139             Path path = Paths.get(arg);
 140             if (Files.exists(path)) {
 141                 throw taskHelper.newBadArgs("err.dir.exists", path);
 142             }
 143             task.options.packagedModulesPath = path;
 144         }, true, "--keep-packaged-modules"),
 145         new Option<JlinkTask>(true, (task, opt, arg) -> {
 146             task.options.saveoptsfile = arg;
 147         }, "--saveopts"),
 148         new Option<JlinkTask>(false, (task, opt, arg) -> {
 149             task.options.fullVersion = true;
 150         }, true, "--fullversion"),};
 151 
 152     private static final String PROGNAME = "jlink";
 153     private final OptionsValues options = new OptionsValues();
 154 
 155     private static final OptionsHelper<JlinkTask> optionsHelper
 156             = taskHelper.newOptionsHelper(JlinkTask.class, recognizedOptions);
 157     private PrintWriter log;
 158 
 159     void setLog(PrintWriter out) {
 160         log = out;
 161         taskHelper.setLog(log);
 162     }
 163 
 164     /**
 165      * Result codes.
 166      */
 167     static final int EXIT_OK = 0, // Completed with no errors.
 168             EXIT_ERROR = 1, // Completed but reported errors.
 169             EXIT_CMDERR = 2, // Bad command-line arguments
 170             EXIT_SYSERR = 3, // System error or resource exhaustion.
 171             EXIT_ABNORMAL = 4;// terminated abnormally
 172 
 173     static class OptionsValues {
 174         boolean help;
 175         String  saveoptsfile;
 176         boolean version;
 177         boolean fullVersion;
 178         Path[] modulePath;
 179         Set<String> limitMods = new HashSet<>();
 180         Set<String> addMods = new HashSet<>();
 181         Path output;
 182         Path packagedModulesPath;
 183         ByteOrder endian = ByteOrder.nativeOrder();
 184     }
 185 
 186     int run(String[] args) {
 187         if (log == null) {
 188             setLog(new PrintWriter(System.err));
 189         }
 190         try {
 191             optionsHelper.handleOptions(this, args);
 192             if (options.help) {
 193                 optionsHelper.showHelp(PROGNAME);
 194                 return EXIT_OK;
 195             }
 196             if (optionsHelper.listPlugins()) {
 197                 optionsHelper.listPlugins(true);
 198                 return EXIT_OK;
 199             }
 200             if (options.version || options.fullVersion) {
 201                 taskHelper.showVersion(options.fullVersion);
 202                 return EXIT_OK;
 203             }
 204             if (taskHelper.getExistingImage() == null) {
 205                 if (options.modulePath == null || options.modulePath.length == 0) {
 206                     throw taskHelper.newBadArgs("err.modulepath.must.be.specified").showUsage(true);
 207                 }
 208                 createImage();
 209             } else {
 210                 postProcessOnly(taskHelper.getExistingImage());
 211             }
 212 
 213             if (options.saveoptsfile != null) {
 214                 Files.write(Paths.get(options.saveoptsfile), getSaveOpts().getBytes());
 215             }
 216 
 217             return EXIT_OK;
 218         } catch (UncheckedIOException | PluginException | IOException | ResolutionException e) {
 219             log.println(taskHelper.getMessage("error.prefix") + " " + e.getMessage());
 220             log.println(taskHelper.getMessage("main.usage.summary", PROGNAME));
 221             return EXIT_ERROR;
 222         } catch (BadArgs e) {
 223             taskHelper.reportError(e.key, e.args);
 224             if (e.showUsage) {
 225                 log.println(taskHelper.getMessage("main.usage.summary", PROGNAME));
 226             }
 227             return EXIT_CMDERR;
 228         } catch (Throwable x) {
 229             log.println(taskHelper.getMessage("main.msg.bug"));
 230             x.printStackTrace(log);
 231             return EXIT_ABNORMAL;
 232         } finally {
 233             log.flush();
 234         }
 235     }
 236 
 237     private static Map<String, Path> modulesToPath(Configuration cf) {
 238         Map<String, Path> modPaths = new HashMap<>();
 239         for (ResolvedModule resolvedModule : cf.modules()) {
 240             ModuleReference mref = resolvedModule.reference();
 241             URI uri = mref.location().get();
 242             modPaths.put(mref.descriptor().name(), Paths.get(uri));
 243         }
 244         return modPaths;
 245     }
 246 
 247     /*
 248      * Jlink API entry point.
 249      */
 250     public static void createImage(JlinkConfiguration config,
 251             PluginsConfiguration plugins)
 252             throws Exception {
 253         Objects.requireNonNull(config);
 254         Objects.requireNonNull(config.getOutput());
 255         plugins = plugins == null ? new PluginsConfiguration() : plugins;
 256 
 257         if (config.getModulepaths().isEmpty()) {
 258             throw new Exception("Empty module paths");
 259         }
 260         Path[] arr = new Path[config.getModulepaths().size()];
 261         arr = config.getModulepaths().toArray(arr);
 262         ModuleFinder finder
 263                 = newModuleFinder(arr, config.getLimitmods(), config.getModules());
 264 
 265         // First create the image provider
 266         ImageProvider imageProvider
 267                 = createImageProvider(finder,
 268                                       checkAddMods(config.getModules()),
 269                                       config.getLimitmods(),
 270                                       config.getByteOrder(),
 271                                       null);
 272 
 273         // Then create the Plugin Stack
 274         ImagePluginStack stack = ImagePluginConfiguration.parseConfiguration(plugins);
 275 
 276         //Ask the stack to proceed;
 277         stack.operate(imageProvider);
 278     }
 279 
 280     /*
 281      * Jlink API entry point.
 282      */
 283     public static void postProcessImage(ExecutableImage image, List<Plugin> postProcessorPlugins)
 284             throws Exception {
 285         Objects.requireNonNull(image);
 286         Objects.requireNonNull(postProcessorPlugins);
 287         PluginsConfiguration config = new PluginsConfiguration(postProcessorPlugins);
 288         ImagePluginStack stack = ImagePluginConfiguration.
 289                 parseConfiguration(config);
 290 
 291         stack.operate((ImagePluginStack stack1) -> image);
 292     }
 293 
 294     private void postProcessOnly(Path existingImage) throws Exception {
 295         PluginsConfiguration config = taskHelper.getPluginsConfig(null);
 296         ExecutableImage img = DefaultImageBuilder.getExecutableImage(existingImage);
 297         if (img == null) {
 298             throw taskHelper.newBadArgs("err.existing.image.invalid");
 299         }
 300         postProcessImage(img, config.getPlugins());
 301     }
 302 
 303     private void createImage() throws Exception {
 304         if (options.output == null) {
 305             throw taskHelper.newBadArgs("err.output.must.be.specified").showUsage(true);
 306         }
 307         ModuleFinder finder
 308                 = newModuleFinder(options.modulePath, options.limitMods, options.addMods);
 309         try {
 310             options.addMods = checkAddMods(options.addMods);
 311         } catch (IllegalArgumentException ex) {
 312             throw taskHelper.newBadArgs("err.mods.must.be.specified", "--addmods")
 313                     .showUsage(true);
 314         }
 315         // First create the image provider
 316         ImageProvider imageProvider
 317                 = createImageProvider(finder,
 318                         options.addMods,
 319                         options.limitMods,
 320                         options.endian,
 321                         options.packagedModulesPath);
 322 
 323         // Then create the Plugin Stack
 324         ImagePluginStack stack = ImagePluginConfiguration.
 325                 parseConfiguration(taskHelper.getPluginsConfig(options.output));
 326 
 327         //Ask the stack to proceed
 328         stack.operate(imageProvider);
 329     }
 330 
 331     private static Set<String> checkAddMods(Set<String> addMods) {
 332         if (addMods.isEmpty()) {
 333             throw new IllegalArgumentException("no modules to add");
 334         }
 335         return addMods;
 336     }
 337 
 338     private static ModuleFinder newModuleFinder(Path[] paths,
 339             Set<String> limitMods,
 340             Set<String> addMods) {
 341         ModuleFinder finder = ModuleFinder.of(paths);
 342 
 343         // jmods are located at link-time
 344         if (finder instanceof ConfigurableModuleFinder) {
 345             ((ConfigurableModuleFinder) finder).configurePhase(Phase.LINK_TIME);
 346         }
 347 
 348         // if limitmods is specified then limit the universe
 349         if (!limitMods.isEmpty()) {
 350             finder = limitFinder(finder, limitMods, addMods);
 351         }
 352         return finder;
 353     }
 354 
 355     private static ImageProvider createImageProvider(ModuleFinder finder,
 356                                                      Set<String> addMods,
 357                                                      Set<String> limitMods,
 358                                                      ByteOrder order,
 359                                                      Path retainModulesPath)
 360             throws IOException
 361     {
 362         if (addMods.isEmpty()) {
 363             throw new IllegalArgumentException("empty modules and limitmods");
 364         }
 365 
 366         Configuration cf = Configuration.empty()
 367                 .resolveRequires(finder,
 368                                  ModuleFinder.empty(),
 369                                  addMods);
 370 
 371         Map<String, Path> mods = modulesToPath(cf);
 372         return new ImageHelper(cf, mods, order, retainModulesPath);
 373     }
 374 
 375     /**
 376      * Returns a ModuleFinder that limits observability to the given root
 377      * modules, their transitive dependences, plus a set of other modules.
 378      */
 379     private static ModuleFinder limitFinder(ModuleFinder finder,
 380             Set<String> roots,
 381             Set<String> otherMods) {
 382 
 383         // resolve all root modules
 384         Configuration cf = Configuration.empty()
 385                 .resolveRequires(finder,
 386                                  ModuleFinder.empty(),
 387                                  roots);
 388 
 389         // module name -> reference
 390         Map<String, ModuleReference> map = new HashMap<>();
 391         cf.modules().forEach(m -> {
 392             ModuleReference mref = m.reference();
 393             map.put(mref.descriptor().name(), mref);
 394         });
 395 
 396         // set of modules that are observable
 397         Set<ModuleReference> mrefs = new HashSet<>(map.values());
 398 
 399         // add the other modules
 400         for (String mod : otherMods) {
 401             Optional<ModuleReference> omref = finder.find(mod);
 402             if (omref.isPresent()) {
 403                 ModuleReference mref = omref.get();
 404                 map.putIfAbsent(mod, mref);
 405                 mrefs.add(mref);
 406             } else {
 407                 // no need to fail
 408             }
 409         }
 410 
 411         return new ModuleFinder() {
 412             @Override
 413             public Optional<ModuleReference> find(String name) {
 414                 return Optional.ofNullable(map.get(name));
 415             }
 416 
 417             @Override
 418             public Set<ModuleReference> findAll() {
 419                 return mrefs;
 420             }
 421         };
 422     }
 423 
 424     private String getSaveOpts() {
 425         StringBuilder sb = new StringBuilder();
 426         sb.append('#').append(new Date()).append("\n");
 427         for (String c : optionsHelper.getInputCommand()) {
 428             sb.append(c).append(" ");
 429         }
 430 
 431         return sb.toString();
 432     }
 433 
 434     private static String getBomHeader() {
 435         StringBuilder sb = new StringBuilder();
 436         sb.append("#").append(new Date()).append("\n");
 437         sb.append("#Please DO NOT Modify this file").append("\n");
 438         return sb.toString();
 439     }
 440 
 441     private String genBOMContent() throws IOException {
 442         StringBuilder sb = new StringBuilder();
 443         sb.append(getBomHeader());
 444         StringBuilder command = new StringBuilder();
 445         for (String c : optionsHelper.getInputCommand()) {
 446             command.append(c).append(" ");
 447         }
 448         sb.append("command").append(" = ").append(command);
 449         sb.append("\n");
 450 
 451         return sb.toString();
 452     }
 453 
 454     private static String genBOMContent(JlinkConfiguration config,
 455             PluginsConfiguration plugins)
 456             throws IOException {
 457         StringBuilder sb = new StringBuilder();
 458         sb.append(getBomHeader());
 459         sb.append(config);
 460         sb.append(plugins);
 461         return sb.toString();
 462     }
 463 
 464     private static class ImageHelper implements ImageProvider {
 465 
 466         final Set<Archive> archives;
 467         final ByteOrder order;
 468         final Path packagedModulesPath;
 469 
 470         ImageHelper(Configuration cf,
 471                     Map<String, Path> modsPaths,
 472                     ByteOrder order,
 473                     Path packagedModulesPath) throws IOException {
 474             archives = modsPaths.entrySet().stream()
 475                                 .map(e -> newArchive(e.getKey(), e.getValue()))
 476                                 .collect(Collectors.toSet());
 477             this.order = order;
 478             this.packagedModulesPath = packagedModulesPath;
 479         }
 480 
 481         private Archive newArchive(String module, Path path) {
 482             if (path.toString().endsWith(".jmod")) {
 483                 return new JmodArchive(module, path);
 484             } else if (path.toString().endsWith(".jar")) {
 485                 return new ModularJarArchive(module, path);
 486             } else if (Files.isDirectory(path)) {
 487                 return new DirArchive(path);
 488             } else {
 489                 fail(RuntimeException.class,
 490                         "Selected module %s (%s) not in jmod or modular jar format",
 491                         module,
 492                         path);
 493             }
 494             return null;
 495         }
 496 
 497         @Override
 498         public ExecutableImage retrieve(ImagePluginStack stack) throws IOException {
 499             ExecutableImage image = ImageFileCreator.create(archives, order, stack);
 500             if (packagedModulesPath != null) {
 501                 // copy the packaged modules to the given path
 502                 Files.createDirectories(packagedModulesPath);
 503                 for (Archive a : archives) {
 504                     Path file = a.getPath();
 505                     Path dest = packagedModulesPath.resolve(file.getFileName());
 506                     Files.copy(file, dest);
 507                 }
 508             }
 509             return image;
 510         }
 511     }
 512 
 513     private static enum Section {
 514         NATIVE_LIBS("native", nativeDir()),
 515         NATIVE_CMDS("bin", "bin"),
 516         CLASSES("classes", "classes"),
 517         CONFIG("conf", "conf"),
 518         UNKNOWN("unknown", "unknown");
 519 
 520         private static String nativeDir() {
 521             if (System.getProperty("os.name").startsWith("Windows")) {
 522                 return "bin";
 523             } else {
 524                 return "lib";
 525             }
 526         }
 527 
 528         private final String jmodDir;
 529         private final String imageDir;
 530 
 531         Section(String jmodDir, String imageDir) {
 532             this.jmodDir = jmodDir;
 533             this.imageDir = imageDir;
 534         }
 535 
 536         String imageDir() {
 537             return imageDir;
 538         }
 539 
 540         String jmodDir() {
 541             return jmodDir;
 542         }
 543 
 544         boolean matches(String path) {
 545             return path.startsWith(jmodDir);
 546         }
 547 
 548         static Section getSectionFromName(String dir) {
 549             if (Section.NATIVE_LIBS.matches(dir)) {
 550                 return Section.NATIVE_LIBS;
 551             } else if (Section.NATIVE_CMDS.matches(dir)) {
 552                 return Section.NATIVE_CMDS;
 553             } else if (Section.CLASSES.matches(dir)) {
 554                 return Section.CLASSES;
 555             } else if (Section.CONFIG.matches(dir)) {
 556                 return Section.CONFIG;
 557             } else {
 558                 return Section.UNKNOWN;
 559             }
 560         }
 561     }
 562 }