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     private static final boolean DEBUG = Boolean.getBoolean("jlink.debug");
  74 
  75     private static <T extends Throwable> void fail(Class<T> type,
  76             String format,
  77             Object... args) throws T {
  78         String msg = new Formatter().format(format, args).toString();
  79         try {
  80             T t = type.getConstructor(String.class).newInstance(msg);
  81             throw t;
  82         } catch (InstantiationException |
  83                 InvocationTargetException |
  84                 NoSuchMethodException |
  85                 IllegalAccessException e) {
  86             throw new InternalError("Unable to create an instance of " + type, e);
  87         }
  88     }
  89 
  90     private static final TaskHelper taskHelper
  91             = new TaskHelper(JLINK_BUNDLE);
  92 
  93     static Option<?>[] recognizedOptions = {
  94         new Option<JlinkTask>(false, (task, opt, arg) -> {
  95             task.options.help = true;
  96         }, "--help"),
  97         new Option<JlinkTask>(true, (task, opt, arg) -> {
  98             String[] dirs = arg.split(File.pathSeparator);
  99             task.options.modulePath = new Path[dirs.length];
 100             int i = 0;
 101             for (String dir : dirs) {
 102                 task.options.modulePath[i++] = Paths.get(dir);
 103             }
 104         }, "--modulepath", "--mp"),
 105         new Option<JlinkTask>(true, (task, opt, arg) -> {
 106             for (String mn : arg.split(",")) {
 107                 if (mn.isEmpty()) {
 108                     throw taskHelper.newBadArgs("err.mods.must.be.specified",
 109                             "--limitmods");
 110                 }
 111                 task.options.limitMods.add(mn);
 112             }
 113         }, "--limitmods"),
 114         new Option<JlinkTask>(true, (task, opt, arg) -> {
 115             for (String mn : arg.split(",")) {
 116                 if (mn.isEmpty()) {
 117                     throw taskHelper.newBadArgs("err.mods.must.be.specified",
 118                             "--addmods");
 119                 }
 120                 task.options.addMods.add(mn);
 121             }
 122         }, "--addmods"),
 123         new Option<JlinkTask>(true, (task, opt, arg) -> {
 124             Path path = Paths.get(arg);
 125             task.options.output = path;
 126         }, "--output"),
 127         new Option<JlinkTask>(true, (task, opt, arg) -> {
 128             if ("little".equals(arg)) {
 129                 task.options.endian = ByteOrder.LITTLE_ENDIAN;
 130             } else if ("big".equals(arg)) {
 131                 task.options.endian = ByteOrder.BIG_ENDIAN;
 132             } else {
 133                 throw taskHelper.newBadArgs("err.unknown.byte.order", arg);
 134             }
 135         }, "--endian"),
 136         new Option<JlinkTask>(false, (task, opt, arg) -> {
 137             task.options.version = true;
 138         }, "--version"),
 139         new Option<JlinkTask>(true, (task, opt, arg) -> {
 140             Path path = Paths.get(arg);
 141             if (Files.exists(path)) {
 142                 throw taskHelper.newBadArgs("err.dir.exists", path);
 143             }
 144             task.options.packagedModulesPath = path;
 145         }, true, "--keep-packaged-modules"),
 146         new Option<JlinkTask>(true, (task, opt, arg) -> {
 147             task.options.saveoptsfile = arg;
 148         }, "--saveopts"),
 149         new Option<JlinkTask>(false, (task, opt, arg) -> {
 150             task.options.fullVersion = true;
 151         }, true, "--fullversion"),};
 152 
 153     private static final String PROGNAME = "jlink";
 154     private final OptionsValues options = new OptionsValues();
 155 
 156     private static final OptionsHelper<JlinkTask> optionsHelper
 157             = taskHelper.newOptionsHelper(JlinkTask.class, recognizedOptions);
 158     private PrintWriter log;
 159 
 160     void setLog(PrintWriter out) {
 161         log = out;
 162         taskHelper.setLog(log);
 163     }
 164 
 165     /**
 166      * Result codes.
 167      */
 168     static final int EXIT_OK = 0, // Completed with no errors.
 169             EXIT_ERROR = 1, // Completed but reported errors.
 170             EXIT_CMDERR = 2, // Bad command-line arguments
 171             EXIT_SYSERR = 3, // System error or resource exhaustion.
 172             EXIT_ABNORMAL = 4;// terminated abnormally
 173 
 174     static class OptionsValues {
 175         boolean help;
 176         String  saveoptsfile;
 177         boolean version;
 178         boolean fullVersion;
 179         Path[] modulePath;
 180         Set<String> limitMods = new HashSet<>();
 181         Set<String> addMods = new HashSet<>();
 182         Path output;
 183         Path packagedModulesPath;
 184         ByteOrder endian = ByteOrder.nativeOrder();
 185     }
 186 
 187     int run(String[] args) {
 188         if (log == null) {
 189             setLog(new PrintWriter(System.err));
 190         }
 191         try {
 192             optionsHelper.handleOptions(this, args);
 193             if (options.help) {
 194                 optionsHelper.showHelp(PROGNAME);
 195                 return EXIT_OK;
 196             }
 197             if (optionsHelper.listPlugins()) {
 198                 optionsHelper.listPlugins(true);
 199                 return EXIT_OK;
 200             }
 201             if (options.version || options.fullVersion) {
 202                 taskHelper.showVersion(options.fullVersion);
 203                 return EXIT_OK;
 204             }
 205             if (taskHelper.getExistingImage() == null) {
 206                 if (options.modulePath == null || options.modulePath.length == 0) {





 207                     throw taskHelper.newBadArgs("err.modulepath.must.be.specified").showUsage(true);

 208                 }
 209                 createImage();
 210             } else {
 211                 postProcessOnly(taskHelper.getExistingImage());
 212             }
 213 
 214             if (options.saveoptsfile != null) {
 215                 Files.write(Paths.get(options.saveoptsfile), getSaveOpts().getBytes());
 216             }
 217 
 218             return EXIT_OK;
 219         } catch (UncheckedIOException | PluginException | IllegalArgumentException |
 220                  IOException | ResolutionException e) {
 221             log.println(taskHelper.getMessage("error.prefix") + " " + e.getMessage());
 222             if (DEBUG) {
 223                 e.printStackTrace(log);
 224             }
 225             return EXIT_ERROR;
 226         } catch (BadArgs e) {
 227             taskHelper.reportError(e.key, e.args);
 228             if (e.showUsage) {
 229                 log.println(taskHelper.getMessage("main.usage.summary", PROGNAME));
 230             }
 231             if (DEBUG) {
 232                 e.printStackTrace(log);
 233             }
 234             return EXIT_CMDERR;
 235         } catch (Throwable x) {
 236             log.println(taskHelper.getMessage("error.prefix") + " " + x.getMessage());
 237             x.printStackTrace(log);
 238             return EXIT_ABNORMAL;
 239         } finally {
 240             log.flush();
 241         }
 242     }
 243 
 244     /*
 245      * Jlink API entry point.
 246      */
 247     public static void createImage(JlinkConfiguration config,
 248             PluginsConfiguration plugins)
 249             throws Exception {
 250         Objects.requireNonNull(config);
 251         Objects.requireNonNull(config.getOutput());
 252         plugins = plugins == null ? new PluginsConfiguration() : plugins;
 253 
 254         if (config.getModulepaths().isEmpty()) {
 255             throw new Exception("Empty module paths");
 256         }
 257         Path[] arr = new Path[config.getModulepaths().size()];
 258         arr = config.getModulepaths().toArray(arr);
 259         ModuleFinder finder
 260                 = newModuleFinder(arr, config.getLimitmods(), config.getModules());
 261 
 262         // First create the image provider
 263         ImageProvider imageProvider
 264                 = createImageProvider(finder,
 265                                       checkAddMods(config.getModules()),
 266                                       config.getLimitmods(),
 267                                       config.getByteOrder(),
 268                                       null);
 269 
 270         // Then create the Plugin Stack
 271         ImagePluginStack stack = ImagePluginConfiguration.parseConfiguration(plugins);
 272 
 273         //Ask the stack to proceed;
 274         stack.operate(imageProvider);
 275     }
 276 
 277     /*
 278      * Jlink API entry point.
 279      */
 280     public static void postProcessImage(ExecutableImage image, List<Plugin> postProcessorPlugins)
 281             throws Exception {
 282         Objects.requireNonNull(image);
 283         Objects.requireNonNull(postProcessorPlugins);
 284         PluginsConfiguration config = new PluginsConfiguration(postProcessorPlugins);
 285         ImagePluginStack stack = ImagePluginConfiguration.
 286                 parseConfiguration(config);
 287 
 288         stack.operate((ImagePluginStack stack1) -> image);
 289     }
 290 
 291     private void postProcessOnly(Path existingImage) throws Exception {
 292         PluginsConfiguration config = taskHelper.getPluginsConfig(null);
 293         ExecutableImage img = DefaultImageBuilder.getExecutableImage(existingImage);
 294         if (img == null) {
 295             throw taskHelper.newBadArgs("err.existing.image.invalid");
 296         }
 297         postProcessImage(img, config.getPlugins());
 298     }
 299 
 300     private void createImage() throws Exception {
 301         if (options.output == null) {
 302             throw taskHelper.newBadArgs("err.output.must.be.specified").showUsage(true);
 303         }
 304         ModuleFinder finder
 305                 = newModuleFinder(options.modulePath, options.limitMods, options.addMods);
 306         try {
 307             options.addMods = checkAddMods(options.addMods);
 308         } catch (IllegalArgumentException ex) {
 309             throw taskHelper.newBadArgs("err.mods.must.be.specified", "--addmods")
 310                     .showUsage(true);
 311         }
 312         // First create the image provider
 313         ImageProvider imageProvider
 314                 = createImageProvider(finder,
 315                         options.addMods,
 316                         options.limitMods,
 317                         options.endian,
 318                         options.packagedModulesPath);
 319 
 320         // Then create the Plugin Stack
 321         ImagePluginStack stack = ImagePluginConfiguration.
 322                 parseConfiguration(taskHelper.getPluginsConfig(options.output));
 323 
 324         //Ask the stack to proceed
 325         stack.operate(imageProvider);
 326     }
 327 
 328     private static Set<String> checkAddMods(Set<String> addMods) {
 329         if (addMods.isEmpty()) {
 330             throw new IllegalArgumentException("no modules to add");
 331         }
 332         return addMods;
 333     }
 334 
 335     private static ModuleFinder newModuleFinder(Path[] paths,
 336             Set<String> limitMods,
 337             Set<String> addMods) {
 338         ModuleFinder finder = ModuleFinder.of(paths);
 339 
 340         // jmods are located at link-time
 341         if (finder instanceof ConfigurableModuleFinder) {
 342             ((ConfigurableModuleFinder) finder).configurePhase(Phase.LINK_TIME);
 343         }
 344 
 345         // if limitmods is specified then limit the universe
 346         if (!limitMods.isEmpty()) {
 347             finder = limitFinder(finder, limitMods, addMods);
 348         }
 349         return finder;
 350     }
 351 
 352 
 353     private static Path toPathLocation(ResolvedModule m) {
 354         Optional<URI> ouri = m.reference().location();
 355         if (!ouri.isPresent())
 356             throw new InternalError(m + " does not have a location");
 357         URI uri = ouri.get();
 358         return Paths.get(uri);
 359     }
 360 
 361     private static ImageProvider createImageProvider(ModuleFinder finder,
 362                                                      Set<String> addMods,
 363                                                      Set<String> limitMods,
 364                                                      ByteOrder order,
 365                                                      Path retainModulesPath)
 366             throws IOException
 367     {
 368         if (addMods.isEmpty()) {
 369             throw new IllegalArgumentException("empty modules and limitmods");
 370         }
 371 
 372         Configuration cf = Configuration.empty()
 373                 .resolveRequires(finder,
 374                                  ModuleFinder.of(),
 375                                  addMods);
 376 
 377         Map<String, Path> mods = cf.modules().stream()
 378             .collect(Collectors.toMap(ResolvedModule::name, JlinkTask::toPathLocation));
 379         return new ImageHelper(cf, mods, order, retainModulesPath);
 380     }
 381 
 382     /**
 383      * Returns a ModuleFinder that limits observability to the given root
 384      * modules, their transitive dependences, plus a set of other modules.
 385      */
 386     private static ModuleFinder limitFinder(ModuleFinder finder,
 387             Set<String> roots,
 388             Set<String> otherMods) {
 389 
 390         // resolve all root modules
 391         Configuration cf = Configuration.empty()
 392                 .resolveRequires(finder,
 393                                  ModuleFinder.of(),
 394                                  roots);
 395 
 396         // module name -> reference
 397         Map<String, ModuleReference> map = new HashMap<>();
 398         cf.modules().forEach(m -> {
 399             ModuleReference mref = m.reference();
 400             map.put(mref.descriptor().name(), mref);
 401         });
 402 
 403         // add the other modules
 404         otherMods.stream()
 405             .map(finder::find)
 406             .flatMap(Optional::stream)
 407             .forEach(mref -> map.putIfAbsent(mref.descriptor().name(), mref));
 408 
 409         // set of modules that are observable
 410         Set<ModuleReference> mrefs = new HashSet<>(map.values());
 411 
 412         return new ModuleFinder() {
 413             @Override
 414             public Optional<ModuleReference> find(String name) {
 415                 return Optional.ofNullable(map.get(name));
 416             }
 417 
 418             @Override
 419             public Set<ModuleReference> findAll() {
 420                 return mrefs;
 421             }
 422         };
 423     }
 424 
 425     private String getSaveOpts() {
 426         StringBuilder sb = new StringBuilder();
 427         sb.append('#').append(new Date()).append("\n");
 428         for (String c : optionsHelper.getInputCommand()) {
 429             sb.append(c).append(" ");
 430         }
 431 
 432         return sb.toString();
 433     }
 434 
 435     private static String getBomHeader() {
 436         StringBuilder sb = new StringBuilder();
 437         sb.append("#").append(new Date()).append("\n");
 438         sb.append("#Please DO NOT Modify this file").append("\n");
 439         return sb.toString();
 440     }
 441 
 442     private String genBOMContent() throws IOException {
 443         StringBuilder sb = new StringBuilder();
 444         sb.append(getBomHeader());
 445         StringBuilder command = new StringBuilder();
 446         for (String c : optionsHelper.getInputCommand()) {
 447             command.append(c).append(" ");
 448         }
 449         sb.append("command").append(" = ").append(command);
 450         sb.append("\n");
 451 
 452         return sb.toString();
 453     }
 454 
 455     private static String genBOMContent(JlinkConfiguration config,
 456             PluginsConfiguration plugins)
 457             throws IOException {
 458         StringBuilder sb = new StringBuilder();
 459         sb.append(getBomHeader());
 460         sb.append(config);
 461         sb.append(plugins);
 462         return sb.toString();
 463     }
 464 
 465     private static class ImageHelper implements ImageProvider {
 466 
 467         final Set<Archive> archives;
 468         final ByteOrder order;
 469         final Path packagedModulesPath;
 470 
 471         ImageHelper(Configuration cf,
 472                     Map<String, Path> modsPaths,
 473                     ByteOrder order,
 474                     Path packagedModulesPath) throws IOException {
 475             archives = modsPaths.entrySet().stream()
 476                                 .map(e -> newArchive(e.getKey(), e.getValue()))
 477                                 .collect(Collectors.toSet());
 478             this.order = order;
 479             this.packagedModulesPath = packagedModulesPath;
 480         }
 481 
 482         private Archive newArchive(String module, Path path) {
 483             if (path.toString().endsWith(".jmod")) {
 484                 return new JmodArchive(module, path);
 485             } else if (path.toString().endsWith(".jar")) {
 486                 return new ModularJarArchive(module, path);
 487             } else if (Files.isDirectory(path)) {
 488                 return new DirArchive(path);
 489             } else {
 490                 fail(RuntimeException.class,
 491                         "Selected module %s (%s) not in jmod or modular jar format",
 492                         module,
 493                         path);
 494             }
 495             return null;
 496         }
 497 
 498         @Override
 499         public ExecutableImage retrieve(ImagePluginStack stack) throws IOException {
 500             ExecutableImage image = ImageFileCreator.create(archives, order, stack);
 501             if (packagedModulesPath != null) {
 502                 // copy the packaged modules to the given path
 503                 Files.createDirectories(packagedModulesPath);
 504                 for (Archive a : archives) {
 505                     Path file = a.getPath();
 506                     Path dest = packagedModulesPath.resolve(file.getFileName());
 507                     Files.copy(file, dest);
 508                 }
 509             }
 510             return image;
 511         }
 512     }
 513 
 514     private static enum Section {
 515         NATIVE_LIBS("native", nativeDir()),
 516         NATIVE_CMDS("bin", "bin"),
 517         CLASSES("classes", "classes"),
 518         CONFIG("conf", "conf"),
 519         UNKNOWN("unknown", "unknown");
 520 
 521         private static String nativeDir() {
 522             if (System.getProperty("os.name").startsWith("Windows")) {
 523                 return "bin";
 524             } else {
 525                 return "lib";
 526             }
 527         }
 528 
 529         private final String jmodDir;
 530         private final String imageDir;
 531 
 532         Section(String jmodDir, String imageDir) {
 533             this.jmodDir = jmodDir;
 534             this.imageDir = imageDir;
 535         }
 536 
 537         String imageDir() {
 538             return imageDir;
 539         }
 540 
 541         String jmodDir() {
 542             return jmodDir;
 543         }
 544 
 545         boolean matches(String path) {
 546             return path.startsWith(jmodDir);
 547         }
 548 
 549         static Section getSectionFromName(String dir) {
 550             if (Section.NATIVE_LIBS.matches(dir)) {
 551                 return Section.NATIVE_LIBS;
 552             } else if (Section.NATIVE_CMDS.matches(dir)) {
 553                 return Section.NATIVE_CMDS;
 554             } else if (Section.CLASSES.matches(dir)) {
 555                 return Section.CLASSES;
 556             } else if (Section.CONFIG.matches(dir)) {
 557                 return Section.CONFIG;
 558             } else {
 559                 return Section.UNKNOWN;
 560             }
 561         }
 562     }
 563 }
--- EOF ---