1 /*
   2  * Copyright (c) 2015, 2017, 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.FindException;
  33 import java.lang.module.ModuleDescriptor;
  34 import java.lang.module.ModuleFinder;
  35 import java.lang.module.ModuleReference;
  36 import java.lang.module.ResolutionException;
  37 import java.lang.module.ResolvedModule;
  38 import java.net.URI;
  39 import java.nio.ByteOrder;
  40 import java.nio.file.Files;
  41 import java.nio.file.Path;
  42 import java.nio.file.Paths;
  43 import java.util.ArrayList;
  44 import java.util.Arrays;
  45 import java.util.Collection;
  46 import java.util.Collections;
  47 import java.util.Comparator;
  48 import java.util.Date;
  49 import java.util.HashMap;
  50 import java.util.HashSet;
  51 import java.util.List;
  52 import java.util.Locale;
  53 import java.util.Map;
  54 import java.util.Objects;
  55 import java.util.Optional;
  56 import java.util.Set;
  57 import java.util.stream.Collectors;
  58 import java.util.stream.Stream;
  59 
  60 import jdk.tools.jlink.internal.TaskHelper.BadArgs;
  61 import static jdk.tools.jlink.internal.TaskHelper.JLINK_BUNDLE;
  62 import jdk.tools.jlink.internal.Jlink.JlinkConfiguration;
  63 import jdk.tools.jlink.internal.Jlink.PluginsConfiguration;
  64 import jdk.tools.jlink.internal.TaskHelper.Option;
  65 import jdk.tools.jlink.internal.TaskHelper.OptionsHelper;
  66 import jdk.tools.jlink.internal.ImagePluginStack.ImageProvider;
  67 import jdk.tools.jlink.plugin.PluginException;
  68 import jdk.tools.jlink.builder.DefaultImageBuilder;
  69 import jdk.tools.jlink.plugin.Plugin;
  70 import jdk.internal.module.ModulePath;
  71 import jdk.internal.module.ModuleResolution;
  72 
  73 /**
  74  * Implementation for the jlink tool.
  75  *
  76  * ## Should use jdk.joptsimple some day.
  77  */
  78 public class JlinkTask {
  79     static final boolean DEBUG = Boolean.getBoolean("jlink.debug");
  80 
  81     // jlink API ignores by default. Remove when signing is implemented.
  82     static final boolean IGNORE_SIGNING_DEFAULT = true;
  83 
  84     private static final TaskHelper taskHelper
  85             = new TaskHelper(JLINK_BUNDLE);
  86 
  87     private static final Option<?>[] recognizedOptions = {
  88         new Option<JlinkTask>(false, (task, opt, arg) -> {
  89             task.options.help = true;
  90         }, "--help", "-h"),
  91         new Option<JlinkTask>(true, (task, opt, arg) -> {
  92             // if used multiple times, the last one wins!
  93             // So, clear previous values, if any.
  94             task.options.modulePath.clear();
  95             String[] dirs = arg.split(File.pathSeparator);
  96             int i = 0;
  97             Arrays.stream(dirs)
  98                   .map(Paths::get)
  99                   .forEach(task.options.modulePath::add);
 100         }, "--module-path", "-p"),
 101         new Option<JlinkTask>(true, (task, opt, arg) -> {
 102             // if used multiple times, the last one wins!
 103             // So, clear previous values, if any.
 104             task.options.limitMods.clear();
 105             for (String mn : arg.split(",")) {
 106                 if (mn.isEmpty()) {
 107                     throw taskHelper.newBadArgs("err.mods.must.be.specified",
 108                             "--limit-modules");
 109                 }
 110                 task.options.limitMods.add(mn);
 111             }
 112         }, "--limit-modules"),
 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                             "--add-modules");
 118                 }
 119                 task.options.addMods.add(mn);
 120             }
 121         }, "--add-modules"),
 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>(false, (task, opt, arg) -> {
 127             task.options.bindServices = true;
 128         }, "--bind-services"),
 129         new Option<JlinkTask>(false, (task, opt, arg) -> {
 130             task.options.suggestProviders = true;
 131         }, "--suggest-providers", "", true),
 132         new Option<JlinkTask>(true, (task, opt, arg) -> {
 133             String[] values = arg.split("=");
 134             // check values
 135             if (values.length != 2 || values[0].isEmpty() || values[1].isEmpty()) {
 136                 throw taskHelper.newBadArgs("err.launcher.value.format", arg);
 137             } else {
 138                 String commandName = values[0];
 139                 String moduleAndMain = values[1];
 140                 int idx = moduleAndMain.indexOf("/");
 141                 if (idx != -1) {
 142                     if (moduleAndMain.substring(0, idx).isEmpty()) {
 143                         throw taskHelper.newBadArgs("err.launcher.module.name.empty", arg);
 144                     }
 145 
 146                     if (moduleAndMain.substring(idx + 1).isEmpty()) {
 147                         throw taskHelper.newBadArgs("err.launcher.main.class.empty", arg);
 148                     }
 149                 }
 150                 task.options.launchers.put(commandName, moduleAndMain);
 151             }
 152         }, "--launcher"),
 153         new Option<JlinkTask>(true, (task, opt, arg) -> {
 154             if ("little".equals(arg)) {
 155                 task.options.endian = ByteOrder.LITTLE_ENDIAN;
 156             } else if ("big".equals(arg)) {
 157                 task.options.endian = ByteOrder.BIG_ENDIAN;
 158             } else {
 159                 throw taskHelper.newBadArgs("err.unknown.byte.order", arg);
 160             }
 161         }, "--endian"),
 162         new Option<JlinkTask>(false, (task, opt, arg) -> {
 163             task.options.verbose = true;
 164         }, "--verbose", "-v"),
 165         new Option<JlinkTask>(false, (task, opt, arg) -> {
 166             task.options.version = true;
 167         }, "--version"),
 168         new Option<JlinkTask>(true, (task, opt, arg) -> {
 169             Path path = Paths.get(arg);
 170             if (Files.exists(path)) {
 171                 throw taskHelper.newBadArgs("err.dir.exists", path);
 172             }
 173             task.options.packagedModulesPath = path;
 174         }, true, "--keep-packaged-modules"),
 175         new Option<JlinkTask>(true, (task, opt, arg) -> {
 176             task.options.saveoptsfile = arg;
 177         }, "--save-opts"),
 178         new Option<JlinkTask>(false, (task, opt, arg) -> {
 179             task.options.fullVersion = true;
 180         }, true, "--full-version"),
 181         new Option<JlinkTask>(false, (task, opt, arg) -> {
 182             task.options.ignoreSigning = true;
 183         }, "--ignore-signing-information"),};
 184 
 185     private static final String PROGNAME = "jlink";
 186     private final OptionsValues options = new OptionsValues();
 187 
 188     private static final OptionsHelper<JlinkTask> optionsHelper
 189             = taskHelper.newOptionsHelper(JlinkTask.class, recognizedOptions);
 190     private PrintWriter log;
 191 
 192     void setLog(PrintWriter out, PrintWriter err) {
 193         log = out;
 194         taskHelper.setLog(log);
 195     }
 196 
 197     /**
 198      * Result codes.
 199      */
 200     static final int
 201             EXIT_OK = 0, // Completed with no errors.
 202             EXIT_ERROR = 1, // Completed but reported errors.
 203             EXIT_CMDERR = 2, // Bad command-line arguments
 204             EXIT_SYSERR = 3, // System error or resource exhaustion.
 205             EXIT_ABNORMAL = 4;// terminated abnormally
 206 
 207     static class OptionsValues {
 208         boolean help;
 209         String  saveoptsfile;
 210         boolean verbose;
 211         boolean version;
 212         boolean fullVersion;
 213         final List<Path> modulePath = new ArrayList<>();
 214         final Set<String> limitMods = new HashSet<>();
 215         final Set<String> addMods = new HashSet<>();
 216         Path output;
 217         final Map<String, String> launchers = new HashMap<>();
 218         Path packagedModulesPath;
 219         ByteOrder endian = ByteOrder.nativeOrder();
 220         boolean ignoreSigning = false;
 221         boolean bindServices = false;
 222         boolean suggestProviders = false;
 223     }
 224 
 225     int run(String[] args) {
 226         if (log == null) {
 227             setLog(new PrintWriter(System.out, true),
 228                    new PrintWriter(System.err, true));
 229         }
 230         try {
 231             List<String> remaining = optionsHelper.handleOptions(this, args);
 232             if (remaining.size() > 0 && !options.suggestProviders) {
 233                 throw taskHelper.newBadArgs("err.orphan.arguments", toString(remaining))
 234                                 .showUsage(true);
 235             }
 236             if (options.help) {
 237                 optionsHelper.showHelp(PROGNAME);
 238                 return EXIT_OK;
 239             }
 240             if (optionsHelper.shouldListPlugins()) {
 241                 optionsHelper.listPlugins();
 242                 return EXIT_OK;
 243             }
 244             if (options.version || options.fullVersion) {
 245                 taskHelper.showVersion(options.fullVersion);
 246                 return EXIT_OK;
 247             }
 248 
 249             if (taskHelper.getExistingImage() != null) {
 250                 postProcessOnly(taskHelper.getExistingImage());
 251                 return EXIT_OK;
 252             }
 253 
 254             if (options.modulePath.isEmpty()) {
 255                 throw taskHelper.newBadArgs("err.modulepath.must.be.specified")
 256                                 .showUsage(true);
 257             }
 258 
 259             JlinkConfiguration config = initJlinkConfig();
 260             if (options.suggestProviders) {
 261                 suggestProviders(config, remaining);
 262             } else {
 263                 createImage(config);
 264                 if (options.saveoptsfile != null) {
 265                     Files.write(Paths.get(options.saveoptsfile), getSaveOpts().getBytes());
 266                 }
 267             }
 268 
 269             return EXIT_OK;
 270         } catch (PluginException | IllegalArgumentException |
 271                  UncheckedIOException |IOException | FindException | ResolutionException e) {
 272             log.println(taskHelper.getMessage("error.prefix") + " " + e.getMessage());
 273             if (DEBUG) {
 274                 e.printStackTrace(log);
 275             }
 276             return EXIT_ERROR;
 277         } catch (BadArgs e) {
 278             taskHelper.reportError(e.key, e.args);
 279             if (e.showUsage) {
 280                 log.println(taskHelper.getMessage("main.usage.summary", PROGNAME));
 281             }
 282             if (DEBUG) {
 283                 e.printStackTrace(log);
 284             }
 285             return EXIT_CMDERR;
 286         } catch (Throwable x) {
 287             log.println(taskHelper.getMessage("error.prefix") + " " + x.getMessage());
 288             x.printStackTrace(log);
 289             return EXIT_ABNORMAL;
 290         } finally {
 291             log.flush();
 292         }
 293     }
 294 
 295     /*
 296      * Jlink API entry point.
 297      */
 298     public static void createImage(JlinkConfiguration config,
 299                                    PluginsConfiguration plugins)
 300             throws Exception {
 301         Objects.requireNonNull(config);
 302         Objects.requireNonNull(config.getOutput());
 303         plugins = plugins == null ? new PluginsConfiguration() : plugins;
 304 
 305         // First create the image provider
 306         ImageProvider imageProvider =
 307                 createImageProvider(config,
 308                                     null,
 309                                     IGNORE_SIGNING_DEFAULT,
 310                                     false,
 311                                     false,
 312                                     null);
 313 
 314         // Then create the Plugin Stack
 315         ImagePluginStack stack = ImagePluginConfiguration.parseConfiguration(plugins);
 316 
 317         //Ask the stack to proceed;
 318         stack.operate(imageProvider);
 319     }
 320 
 321     /*
 322      * Jlink API entry point.
 323      */
 324     public static void postProcessImage(ExecutableImage image, List<Plugin> postProcessorPlugins)
 325             throws Exception {
 326         Objects.requireNonNull(image);
 327         Objects.requireNonNull(postProcessorPlugins);
 328         PluginsConfiguration config = new PluginsConfiguration(postProcessorPlugins);
 329         ImagePluginStack stack = ImagePluginConfiguration.
 330                 parseConfiguration(config);
 331 
 332         stack.operate((ImagePluginStack stack1) -> image);
 333     }
 334 
 335     private void postProcessOnly(Path existingImage) throws Exception {
 336         PluginsConfiguration config = taskHelper.getPluginsConfig(null, null);
 337         ExecutableImage img = DefaultImageBuilder.getExecutableImage(existingImage);
 338         if (img == null) {
 339             throw taskHelper.newBadArgs("err.existing.image.invalid");
 340         }
 341         postProcessImage(img, config.getPlugins());
 342     }
 343 
 344     // the token for "all modules on the module path"
 345     private static final String ALL_MODULE_PATH = "ALL-MODULE-PATH";
 346     private JlinkConfiguration initJlinkConfig() throws BadArgs {
 347         Set<String> roots = new HashSet<>();
 348         for (String mod : options.addMods) {
 349             if (mod.equals(ALL_MODULE_PATH)) {
 350                 Path[] entries = options.modulePath.toArray(new Path[0]);
 351                 ModuleFinder finder = ModulePath.of(Runtime.version(), true, entries);
 352                 if (!options.limitMods.isEmpty()) {
 353                     // finder for the observable modules specified in
 354                     // the --module-path and --limit-modules options
 355                     finder = limitFinder(finder, options.limitMods, Collections.emptySet());
 356                 }
 357 
 358                 // all observable modules are roots
 359                 finder.findAll()
 360                       .stream()
 361                       .map(ModuleReference::descriptor)
 362                       .map(ModuleDescriptor::name)
 363                       .forEach(mn -> roots.add(mn));
 364             } else {
 365                 roots.add(mod);
 366             }
 367         }
 368 
 369         return new JlinkConfiguration(options.output,
 370                                       options.modulePath,
 371                                       roots,
 372                                       options.limitMods,
 373                                       options.endian);
 374     }
 375 
 376     private void createImage(JlinkConfiguration config) throws Exception {
 377         if (options.output == null) {
 378             throw taskHelper.newBadArgs("err.output.must.be.specified").showUsage(true);
 379         }
 380         if (options.addMods.isEmpty()) {
 381             throw taskHelper.newBadArgs("err.mods.must.be.specified", "--add-modules")
 382                             .showUsage(true);
 383         }
 384 
 385         // First create the image provider
 386         ImageProvider imageProvider = createImageProvider(config,
 387                                                           options.packagedModulesPath,
 388                                                           options.ignoreSigning,
 389                                                           options.bindServices,
 390                                                           options.verbose,
 391                                                           log);
 392 
 393         // Then create the Plugin Stack
 394         ImagePluginStack stack = ImagePluginConfiguration.parseConfiguration(
 395             taskHelper.getPluginsConfig(options.output, options.launchers));
 396 
 397         //Ask the stack to proceed
 398         stack.operate(imageProvider);
 399     }
 400 
 401     /*
 402      * Returns a module finder of the given module path that limits
 403      * the observable modules to those in the transitive closure of
 404      * the modules specified in {@code limitMods} plus other modules
 405      * specified in the {@code roots} set.
 406      */
 407     public static ModuleFinder newModuleFinder(List<Path> paths,
 408                                                Set<String> limitMods,
 409                                                Set<String> roots)
 410     {
 411         Path[] entries = paths.toArray(new Path[0]);
 412         ModuleFinder finder = ModulePath.of(Runtime.version(), true, entries);
 413 
 414         // if limitmods is specified then limit the universe
 415         if (!limitMods.isEmpty()) {
 416             finder = limitFinder(finder, limitMods, roots);
 417         }
 418         return finder;
 419     }
 420 
 421     private static Path toPathLocation(ResolvedModule m) {
 422         Optional<URI> ouri = m.reference().location();
 423         if (!ouri.isPresent())
 424             throw new InternalError(m + " does not have a location");
 425         URI uri = ouri.get();
 426         return Paths.get(uri);
 427     }
 428 
 429 
 430     private static ImageProvider createImageProvider(JlinkConfiguration config,
 431                                                      Path retainModulesPath,
 432                                                      boolean ignoreSigning,
 433                                                      boolean bindService,
 434                                                      boolean verbose,
 435                                                      PrintWriter log)
 436             throws IOException
 437     {
 438         Configuration cf = bindService ? config.resolveAndBind()
 439                                        : config.resolve();
 440 
 441         cf.modules().stream()
 442             .map(ResolvedModule::reference)
 443             .filter(mref -> mref.descriptor().isAutomatic())
 444             .findAny()
 445             .ifPresent(mref -> {
 446                 String loc = mref.location().map(URI::toString).orElse("<unknown>");
 447                 throw new IllegalArgumentException(
 448                     taskHelper.getMessage("err.automatic.module", mref.descriptor().name(), loc));
 449             });
 450 
 451         if (verbose && log != null) {
 452             // print modules to be linked in
 453             cf.modules().stream()
 454               .sorted(Comparator.comparing(ResolvedModule::name))
 455               .forEach(rm -> log.format("%s %s%n",
 456                                         rm.name(), rm.reference().location().get()));
 457 
 458             // print provider info
 459             Set<ModuleReference> references = cf.modules().stream()
 460                 .map(ResolvedModule::reference).collect(Collectors.toSet());
 461 
 462             String msg = String.format("%n%s:", taskHelper.getMessage("providers.header"));
 463             printProviders(log, msg, references);
 464         }
 465 
 466         // emit a warning for any incubating modules in the configuration
 467         if (log != null) {
 468             String im = cf.modules()
 469                           .stream()
 470                           .map(ResolvedModule::reference)
 471                           .filter(ModuleResolution::hasIncubatingWarning)
 472                           .map(ModuleReference::descriptor)
 473                           .map(ModuleDescriptor::name)
 474                           .collect(Collectors.joining(", "));
 475 
 476             if (!"".equals(im))
 477                 log.println("WARNING: Using incubator modules: " + im);
 478         }
 479 
 480         Map<String, Path> mods = cf.modules().stream()
 481             .collect(Collectors.toMap(ResolvedModule::name, JlinkTask::toPathLocation));
 482         return new ImageHelper(cf, mods, config.getByteOrder(), retainModulesPath, ignoreSigning);
 483     }
 484 
 485     /*
 486      * Returns a ModuleFinder that limits observability to the given root
 487      * modules, their transitive dependences, plus a set of other modules.
 488      */
 489     public static ModuleFinder limitFinder(ModuleFinder finder,
 490                                            Set<String> roots,
 491                                            Set<String> otherMods) {
 492 
 493         // resolve all root modules
 494         Configuration cf = Configuration.empty()
 495                 .resolve(finder,
 496                          ModuleFinder.of(),
 497                          roots);
 498 
 499         // module name -> reference
 500         Map<String, ModuleReference> map = new HashMap<>();
 501         cf.modules().forEach(m -> {
 502             ModuleReference mref = m.reference();
 503             map.put(mref.descriptor().name(), mref);
 504         });
 505 
 506         // add the other modules
 507         otherMods.stream()
 508             .map(finder::find)
 509             .flatMap(Optional::stream)
 510             .forEach(mref -> map.putIfAbsent(mref.descriptor().name(), mref));
 511 
 512         // set of modules that are observable
 513         Set<ModuleReference> mrefs = new HashSet<>(map.values());
 514 
 515         return new ModuleFinder() {
 516             @Override
 517             public Optional<ModuleReference> find(String name) {
 518                 return Optional.ofNullable(map.get(name));
 519             }
 520 
 521             @Override
 522             public Set<ModuleReference> findAll() {
 523                 return mrefs;
 524             }
 525         };
 526     }
 527 
 528     /*
 529      * Returns a map of each service type to the modules that use it
 530      * It will include services that are provided by a module but may not used
 531      * by any of the observable modules.
 532      */
 533     private static Map<String, Set<String>> uses(Set<ModuleReference> modules) {
 534         // collects the services used by the modules and print uses
 535         Map<String, Set<String>> services = new HashMap<>();
 536         modules.stream()
 537                .map(ModuleReference::descriptor)
 538                .forEach(md -> {
 539                    // include services that may not be used by any observable modules
 540                    md.provides().forEach(p ->
 541                        services.computeIfAbsent(p.service(), _k -> new HashSet<>()));
 542                    md.uses().forEach(s -> services.computeIfAbsent(s, _k -> new HashSet<>())
 543                                                   .add(md.name()));
 544                });
 545         return services;
 546     }
 547 
 548     private static void printProviders(PrintWriter log,
 549                                        String header,
 550                                        Set<ModuleReference> modules) {
 551         printProviders(log, header, modules, uses(modules));
 552     }
 553 
 554     /*
 555      * Prints the providers that are used by the specified services.
 556      *
 557      * The specified services maps a service type name to the modules
 558      * using the service type which may be empty if no observable module uses
 559      * that service.
 560      */
 561     private static void printProviders(PrintWriter log,
 562                                        String header,
 563                                        Set<ModuleReference> modules,
 564                                        Map<String, Set<String>> serviceToUses) {
 565         if (modules.isEmpty())
 566             return;
 567 
 568         // Build a map of a service type to the provider modules
 569         Map<String, Set<ModuleDescriptor>> providers = new HashMap<>();
 570         modules.stream()
 571             .map(ModuleReference::descriptor)
 572             .forEach(md -> {
 573                 md.provides().stream()
 574                   .filter(p -> serviceToUses.containsKey(p.service()))
 575                   .forEach(p -> providers.computeIfAbsent(p.service(), _k -> new HashSet<>())
 576                                          .add(md));
 577             });
 578 
 579         if (!providers.isEmpty()) {
 580             log.println(header);
 581         }
 582 
 583         // print the providers of the service types used by the specified modules
 584         // sorted by the service type name and then provider's module name
 585         providers.entrySet().stream()
 586             .sorted(Map.Entry.comparingByKey())
 587             .forEach(e -> {
 588                 String service = e.getKey();
 589                 e.getValue().stream()
 590                  .sorted(Comparator.comparing(ModuleDescriptor::name))
 591                  .forEach(md ->
 592                      md.provides().stream()
 593                        .filter(p -> p.service().equals(service))
 594                        .forEach(p -> {
 595                            String usedBy;
 596                            if (serviceToUses.get(p.service()).isEmpty()) {
 597                                usedBy = "not used by any observable module";
 598                            } else {
 599                                usedBy = serviceToUses.get(p.service()).stream()
 600                                             .sorted()
 601                                             .collect(Collectors.joining(",", "used by ", ""));
 602                            }
 603                            log.format("  %s provides %s %s%n",
 604                                       md.name(), p.service(), usedBy);
 605                        })
 606                  );
 607             });
 608     }
 609 
 610     private void suggestProviders(JlinkConfiguration config, List<String> args)
 611         throws BadArgs
 612     {
 613         if (args.size() > 1) {
 614             throw taskHelper.newBadArgs("err.orphan.argument",
 615                                         toString(args.subList(1, args.size())))
 616                             .showUsage(true);
 617         }
 618 
 619         if (options.bindServices) {
 620             log.println(taskHelper.getMessage("no.suggested.providers"));
 621             return;
 622         }
 623 
 624         ModuleFinder finder = config.finder();
 625         if (args.isEmpty()) {
 626             // print providers used by the observable modules without service binding
 627             Set<ModuleReference> mrefs = finder.findAll();
 628             // print uses of the modules that would be linked into the image
 629             mrefs.stream()
 630                  .sorted(Comparator.comparing(mref -> mref.descriptor().name()))
 631                  .forEach(mref -> {
 632                      ModuleDescriptor md = mref.descriptor();
 633                      log.format("%s %s%n", md.name(),
 634                                 mref.location().get());
 635                      md.uses().stream().sorted()
 636                        .forEach(s -> log.format("    uses %s%n", s));
 637                  });
 638 
 639             String msg = String.format("%n%s:", taskHelper.getMessage("suggested.providers.header"));
 640             printProviders(log, msg, mrefs, uses(mrefs));
 641 
 642         } else {
 643             // comma-separated service types, if specified
 644             Set<String> names = Stream.of(args.get(0).split(","))
 645                 .collect(Collectors.toSet());
 646             // find the modules that provide the specified service
 647             Set<ModuleReference> mrefs = finder.findAll().stream()
 648                 .filter(mref -> mref.descriptor().provides().stream()
 649                                     .map(ModuleDescriptor.Provides::service)
 650                                     .anyMatch(names::contains))
 651                 .collect(Collectors.toSet());
 652 
 653             // find the modules that uses the specified services
 654             Map<String, Set<String>> uses = new HashMap<>();
 655             names.forEach(s -> uses.computeIfAbsent(s, _k -> new HashSet<>()));
 656             finder.findAll().stream()
 657                   .map(ModuleReference::descriptor)
 658                   .forEach(md -> md.uses().stream()
 659                                    .filter(names::contains)
 660                                    .forEach(s -> uses.get(s).add(md.name())));
 661 
 662             // check if any name given on the command line are not provided by any module
 663             mrefs.stream()
 664                  .flatMap(mref -> mref.descriptor().provides().stream()
 665                                       .map(ModuleDescriptor.Provides::service))
 666                  .forEach(names::remove);
 667             if (!names.isEmpty()) {
 668                 log.println(taskHelper.getMessage("warn.provider.notfound",
 669                                                   toString(names)));
 670             }
 671 
 672             String msg = String.format("%n%s:", taskHelper.getMessage("suggested.providers.header"));
 673             printProviders(log, msg, mrefs, uses);
 674         }
 675     }
 676 
 677     private static String toString(Collection<String> collection) {
 678         return collection.stream().sorted()
 679                          .collect(Collectors.joining(","));
 680     }
 681 
 682     private String getSaveOpts() {
 683         StringBuilder sb = new StringBuilder();
 684         sb.append('#').append(new Date()).append("\n");
 685         for (String c : optionsHelper.getInputCommand()) {
 686             sb.append(c).append(" ");
 687         }
 688 
 689         return sb.toString();
 690     }
 691 
 692     private static String getBomHeader() {
 693         StringBuilder sb = new StringBuilder();
 694         sb.append("#").append(new Date()).append("\n");
 695         sb.append("#Please DO NOT Modify this file").append("\n");
 696         return sb.toString();
 697     }
 698 
 699     private String genBOMContent() throws IOException {
 700         StringBuilder sb = new StringBuilder();
 701         sb.append(getBomHeader());
 702         StringBuilder command = new StringBuilder();
 703         for (String c : optionsHelper.getInputCommand()) {
 704             command.append(c).append(" ");
 705         }
 706         sb.append("command").append(" = ").append(command);
 707         sb.append("\n");
 708 
 709         return sb.toString();
 710     }
 711 
 712     private static String genBOMContent(JlinkConfiguration config,
 713             PluginsConfiguration plugins)
 714             throws IOException {
 715         StringBuilder sb = new StringBuilder();
 716         sb.append(getBomHeader());
 717         sb.append(config);
 718         sb.append(plugins);
 719         return sb.toString();
 720     }
 721 
 722     private static class ImageHelper implements ImageProvider {
 723         final ByteOrder order;
 724         final Path packagedModulesPath;
 725         final boolean ignoreSigning;
 726         final Set<Archive> archives;
 727 
 728         ImageHelper(Configuration cf,
 729                     Map<String, Path> modsPaths,
 730                     ByteOrder order,
 731                     Path packagedModulesPath,
 732                     boolean ignoreSigning) throws IOException {
 733             this.order = order;
 734             this.packagedModulesPath = packagedModulesPath;
 735             this.ignoreSigning = ignoreSigning;
 736             this.archives = modsPaths.entrySet().stream()
 737                                 .map(e -> newArchive(e.getKey(), e.getValue()))
 738                                 .collect(Collectors.toSet());
 739         }
 740 
 741         private Archive newArchive(String module, Path path) {
 742             if (path.toString().endsWith(".jmod")) {
 743                 return new JmodArchive(module, path);
 744             } else if (path.toString().endsWith(".jar")) {
 745                 ModularJarArchive modularJarArchive = new ModularJarArchive(module, path);
 746 
 747                 Stream<Archive.Entry> signatures = modularJarArchive.entries().filter((entry) -> {
 748                     String name = entry.name().toUpperCase(Locale.ENGLISH);
 749 
 750                     return name.startsWith("META-INF/") && name.indexOf('/', 9) == -1 && (
 751                                 name.endsWith(".SF") ||
 752                                 name.endsWith(".DSA") ||
 753                                 name.endsWith(".RSA") ||
 754                                 name.endsWith(".EC") ||
 755                                 name.startsWith("META-INF/SIG-")
 756                             );
 757                 });
 758 
 759                 if (signatures.count() != 0) {
 760                     if (ignoreSigning) {
 761                         System.err.println(taskHelper.getMessage("warn.signing", path));
 762                     } else {
 763                         throw new IllegalArgumentException(taskHelper.getMessage("err.signing", path));
 764                     }
 765                 }
 766 
 767                 return modularJarArchive;
 768             } else if (Files.isDirectory(path)) {
 769                 return new DirArchive(path);
 770             } else {
 771                 throw new IllegalArgumentException(
 772                     taskHelper.getMessage("err.not.modular.format", module, path));
 773             }
 774         }
 775 
 776         @Override
 777         public ExecutableImage retrieve(ImagePluginStack stack) throws IOException {
 778             ExecutableImage image = ImageFileCreator.create(archives, order, stack);
 779             if (packagedModulesPath != null) {
 780                 // copy the packaged modules to the given path
 781                 Files.createDirectories(packagedModulesPath);
 782                 for (Archive a : archives) {
 783                     Path file = a.getPath();
 784                     Path dest = packagedModulesPath.resolve(file.getFileName());
 785                     Files.copy(file, dest);
 786                 }
 787             }
 788             return image;
 789         }
 790     }
 791 }