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