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 
  26 package jdk.tools.jmod;
  27 
  28 import java.io.ByteArrayInputStream;
  29 import java.io.ByteArrayOutputStream;
  30 import java.io.File;
  31 import java.io.IOException;
  32 import java.io.InputStream;
  33 import java.io.OutputStream;
  34 import java.io.PrintWriter;
  35 import java.io.UncheckedIOException;
  36 import java.lang.module.Configuration;
  37 import java.lang.module.ModuleReader;
  38 import java.lang.module.ModuleReference;
  39 import java.lang.module.ModuleFinder;
  40 import java.lang.module.ModuleDescriptor;
  41 import java.lang.module.ModuleDescriptor.Exports;
  42 import java.lang.module.ModuleDescriptor.Opens;
  43 import java.lang.module.ModuleDescriptor.Provides;
  44 import java.lang.module.ModuleDescriptor.Requires;
  45 import java.lang.module.ModuleDescriptor.Version;
  46 import java.lang.module.ResolutionException;
  47 import java.lang.module.ResolvedModule;
  48 import java.net.URI;
  49 import java.nio.file.FileSystems;
  50 import java.nio.file.FileVisitOption;
  51 import java.nio.file.FileVisitResult;
  52 import java.nio.file.Files;
  53 import java.nio.file.InvalidPathException;
  54 import java.nio.file.Path;
  55 import java.nio.file.PathMatcher;
  56 import java.nio.file.Paths;
  57 import java.nio.file.SimpleFileVisitor;
  58 import java.nio.file.StandardCopyOption;
  59 import java.nio.file.attribute.BasicFileAttributes;
  60 import java.text.MessageFormat;
  61 import java.util.ArrayList;
  62 import java.util.Collection;
  63 import java.util.Collections;
  64 import java.util.Comparator;
  65 import java.util.HashSet;
  66 import java.util.LinkedHashMap;
  67 import java.util.List;
  68 import java.util.Locale;
  69 import java.util.Map;
  70 import java.util.MissingResourceException;
  71 import java.util.Optional;
  72 import java.util.ResourceBundle;
  73 import java.util.Set;
  74 import java.util.TreeSet;
  75 import java.util.function.Consumer;
  76 import java.util.function.Function;
  77 import java.util.function.Predicate;
  78 import java.util.function.Supplier;
  79 import java.util.jar.JarEntry;
  80 import java.util.jar.JarFile;
  81 import java.util.jar.JarOutputStream;
  82 import java.util.stream.Collectors;
  83 import java.util.regex.Pattern;
  84 import java.util.regex.PatternSyntaxException;
  85 import java.util.zip.ZipEntry;
  86 import java.util.zip.ZipException;
  87 import java.util.zip.ZipFile;
  88 
  89 import jdk.internal.jmod.JmodFile;
  90 import jdk.internal.jmod.JmodFile.Section;
  91 import jdk.internal.joptsimple.BuiltinHelpFormatter;
  92 import jdk.internal.joptsimple.NonOptionArgumentSpec;
  93 import jdk.internal.joptsimple.OptionDescriptor;
  94 import jdk.internal.joptsimple.OptionException;
  95 import jdk.internal.joptsimple.OptionParser;
  96 import jdk.internal.joptsimple.OptionSet;
  97 import jdk.internal.joptsimple.OptionSpec;
  98 import jdk.internal.joptsimple.ValueConverter;
  99 import jdk.internal.loader.ResourceHelper;
 100 import jdk.internal.module.ModuleHashes;
 101 import jdk.internal.module.ModuleHashesBuilder;
 102 import jdk.internal.module.ModuleInfo;
 103 import jdk.internal.module.ModuleInfoExtender;
 104 import jdk.internal.module.ModulePath;
 105 import jdk.internal.module.ModuleResolution;
 106 import jdk.tools.jlink.internal.Utils;
 107 
 108 import static java.util.stream.Collectors.joining;
 109 
 110 /**
 111  * Implementation for the jmod tool.
 112  */
 113 public class JmodTask {
 114 
 115     static class CommandException extends RuntimeException {
 116         private static final long serialVersionUID = 0L;
 117         boolean showUsage;
 118 
 119         CommandException(String key, Object... args) {
 120             super(getMessageOrKey(key, args));
 121         }
 122 
 123         CommandException showUsage(boolean b) {
 124             showUsage = b;
 125             return this;
 126         }
 127 
 128         private static String getMessageOrKey(String key, Object... args) {
 129             try {
 130                 return MessageFormat.format(ResourceBundleHelper.bundle.getString(key), args);
 131             } catch (MissingResourceException e) {
 132                 return key;
 133             }
 134         }
 135     }
 136 
 137     private static final String PROGNAME = "jmod";
 138     private static final String MODULE_INFO = "module-info.class";
 139 
 140     private static final Path CWD = Paths.get("");
 141 
 142     private Options options;
 143     private PrintWriter out = new PrintWriter(System.out, true);
 144     void setLog(PrintWriter out, PrintWriter err) {
 145         this.out = out;
 146     }
 147 
 148     /* Result codes. */
 149     static final int EXIT_OK = 0, // Completed with no errors.
 150                      EXIT_ERROR = 1, // Completed but reported errors.
 151                      EXIT_CMDERR = 2, // Bad command-line arguments
 152                      EXIT_SYSERR = 3, // System error or resource exhaustion.
 153                      EXIT_ABNORMAL = 4;// terminated abnormally
 154 
 155     enum Mode {
 156         CREATE,
 157         EXTRACT,
 158         LIST,
 159         DESCRIBE,
 160         HASH
 161     };
 162 
 163     static class Options {
 164         Mode mode;
 165         Path jmodFile;
 166         boolean help;
 167         boolean helpExtra;
 168         boolean version;
 169         List<Path> classpath;
 170         List<Path> cmds;
 171         List<Path> configs;
 172         List<Path> libs;
 173         List<Path> headerFiles;
 174         List<Path> manPages;
 175         List<Path> legalNotices;;
 176         ModuleFinder moduleFinder;
 177         Version moduleVersion;
 178         String mainClass;
 179         String osName;
 180         String osArch;
 181         String osVersion;
 182         Pattern modulesToHash;
 183         ModuleResolution moduleResolution;
 184         boolean dryrun;
 185         List<PathMatcher> excludes;
 186         Path extractDir;
 187     }
 188 
 189     public int run(String[] args) {
 190 
 191         try {
 192             handleOptions(args);
 193             if (options == null) {
 194                 showUsageSummary();
 195                 return EXIT_CMDERR;
 196             }
 197             if (options.help || options.helpExtra) {
 198                 showHelp();
 199                 return EXIT_OK;
 200             }
 201             if (options.version) {
 202                 showVersion();
 203                 return EXIT_OK;
 204             }
 205 
 206             boolean ok;
 207             switch (options.mode) {
 208                 case CREATE:
 209                     ok = create();
 210                     break;
 211                 case EXTRACT:
 212                     ok = extract();
 213                     break;
 214                 case LIST:
 215                     ok = list();
 216                     break;
 217                 case DESCRIBE:
 218                     ok = describe();
 219                     break;
 220                 case HASH:
 221                     ok = hashModules();
 222                     break;
 223                 default:
 224                     throw new AssertionError("Unknown mode: " + options.mode.name());
 225             }
 226 
 227             return ok ? EXIT_OK : EXIT_ERROR;
 228         } catch (CommandException e) {
 229             reportError(e.getMessage());
 230             if (e.showUsage)
 231                 showUsageSummary();
 232             return EXIT_CMDERR;
 233         } catch (Exception x) {
 234             reportError(x.getMessage());
 235             x.printStackTrace();
 236             return EXIT_ABNORMAL;
 237         } finally {
 238             out.flush();
 239         }
 240     }
 241 
 242     private boolean list() throws IOException {
 243         ZipFile zip = null;
 244         try {
 245             try {
 246                 zip = new ZipFile(options.jmodFile.toFile());
 247             } catch (IOException x) {
 248                 throw new IOException("error opening jmod file", x);
 249             }
 250 
 251             // Trivially print the archive entries for now, pending a more complete implementation
 252             zip.stream().forEach(e -> out.println(e.getName()));
 253             return true;
 254         } finally {
 255             if (zip != null)
 256                 zip.close();
 257         }
 258     }
 259 
 260     private boolean extract() throws IOException {
 261         Path dir = options.extractDir != null ? options.extractDir : CWD;
 262         try (JmodFile jf = new JmodFile(options.jmodFile)) {
 263             jf.stream().forEach(e -> {
 264                 try {
 265                     ZipEntry entry = e.zipEntry();
 266                     String name = entry.getName();
 267                     int index = name.lastIndexOf("/");
 268                     if (index != -1) {
 269                         Path p = dir.resolve(name.substring(0, index));
 270                         if (Files.notExists(p))
 271                             Files.createDirectories(p);
 272                     }
 273 
 274                     try (OutputStream os = Files.newOutputStream(dir.resolve(name))) {
 275                         jf.getInputStream(e).transferTo(os);
 276                     }
 277                 } catch (IOException x) {
 278                     throw new UncheckedIOException(x);
 279                 }
 280             });
 281 
 282             return true;
 283         }
 284     }
 285 
 286     private boolean hashModules() {
 287         if (options.dryrun) {
 288             out.println("Dry run:");
 289         }
 290 
 291         Hasher hasher = new Hasher(options.moduleFinder);
 292         hasher.computeHashes().forEach((mn, hashes) -> {
 293             if (options.dryrun) {
 294                 out.format("%s%n", mn);
 295                 hashes.names().stream()
 296                     .sorted()
 297                     .forEach(name -> out.format("  hashes %s %s %s%n",
 298                         name, hashes.algorithm(), toHex(hashes.hashFor(name))));
 299             } else {
 300                 try {
 301                     hasher.updateModuleInfo(mn, hashes);
 302                 } catch (IOException ex) {
 303                     throw new UncheckedIOException(ex);
 304                 }
 305             }
 306         });
 307         return true;
 308     }
 309 
 310     private boolean describe() throws IOException {
 311         try (JmodFile jf = new JmodFile(options.jmodFile)) {
 312             try (InputStream in = jf.getInputStream(Section.CLASSES, MODULE_INFO)) {
 313                 ModuleInfo.Attributes attrs = ModuleInfo.read(in, null);
 314                 printModuleDescriptor(attrs.descriptor(), attrs.recordedHashes());
 315                 return true;
 316             } catch (IOException e) {
 317                 throw new CommandException("err.module.descriptor.not.found");
 318             }
 319         }
 320     }
 321 
 322     static <T> String toString(Collection<T> c) {
 323         if (c.isEmpty()) { return ""; }
 324         return c.stream().map(e -> e.toString().toLowerCase(Locale.ROOT))
 325                   .collect(joining(" "));
 326     }
 327 
 328     private void printModuleDescriptor(ModuleDescriptor md, ModuleHashes hashes)
 329         throws IOException
 330     {
 331         StringBuilder sb = new StringBuilder();
 332         sb.append("\n").append(md.toNameAndVersion());
 333 
 334         md.requires().stream()
 335             .sorted(Comparator.comparing(Requires::name))
 336             .forEach(r -> {
 337                 sb.append("\n  requires ");
 338                 if (!r.modifiers().isEmpty())
 339                     sb.append(toString(r.modifiers())).append(" ");
 340                 sb.append(r.name());
 341             });
 342 
 343         md.uses().stream().sorted()
 344             .forEach(s -> sb.append("\n  uses ").append(s));
 345 
 346         md.exports().stream()
 347             .sorted(Comparator.comparing(Exports::source))
 348             .forEach(p -> sb.append("\n  exports ").append(p));
 349 
 350         md.opens().stream()
 351             .sorted(Comparator.comparing(Opens::source))
 352             .forEach(p -> sb.append("\n  opens ").append(p));
 353 
 354         Set<String> concealed = new HashSet<>(md.packages());
 355         md.exports().stream().map(Exports::source).forEach(concealed::remove);
 356         md.opens().stream().map(Opens::source).forEach(concealed::remove);
 357         concealed.stream().sorted()
 358                  .forEach(p -> sb.append("\n  contains ").append(p));
 359 
 360         md.provides().stream()
 361             .sorted(Comparator.comparing(Provides::service))
 362             .forEach(p -> sb.append("\n  provides ").append(p.service())
 363                             .append(" with ")
 364                             .append(toString(p.providers())));
 365 
 366         md.mainClass().ifPresent(v -> sb.append("\n  main-class " + v));
 367 
 368         md.osName().ifPresent(v -> sb.append("\n  operating-system-name " + v));
 369 
 370         md.osArch().ifPresent(v -> sb.append("\n  operating-system-architecture " + v));
 371 
 372         md.osVersion().ifPresent(v -> sb.append("\n  operating-system-version " + v));
 373 
 374         if (hashes != null) {
 375             hashes.names().stream().sorted().forEach(
 376                     mod -> sb.append("\n  hashes ").append(mod).append(" ")
 377                              .append(hashes.algorithm()).append(" ")
 378                              .append(toHex(hashes.hashFor(mod))));
 379         }
 380 
 381         out.println(sb.toString());
 382     }
 383 
 384     private String toHex(byte[] ba) {
 385         StringBuilder sb = new StringBuilder(ba.length);
 386         for (byte b: ba) {
 387             sb.append(String.format("%02x", b & 0xff));
 388         }
 389         return sb.toString();
 390     }
 391 
 392     private boolean create() throws IOException {
 393         JmodFileWriter jmod = new JmodFileWriter();
 394 
 395         // create jmod with temporary name to avoid it being examined
 396         // when scanning the module path
 397         Path target = options.jmodFile;
 398         Path tempTarget = Files.createTempFile(target.getFileName().toString(), ".tmp");
 399         try {
 400             try (JmodOutputStream jos = JmodOutputStream.newOutputStream(tempTarget)) {
 401                 jmod.write(jos);
 402             }
 403             Files.move(tempTarget, target);
 404         } catch (Exception e) {
 405             if (Files.exists(tempTarget)) {
 406                 try {
 407                     Files.delete(tempTarget);
 408                 } catch (IOException ioe) {
 409                     e.addSuppressed(ioe);
 410                 }
 411             }
 412             throw e;
 413         }
 414         return true;
 415     }
 416 
 417     private class JmodFileWriter {
 418         final List<Path> cmds = options.cmds;
 419         final List<Path> libs = options.libs;
 420         final List<Path> configs = options.configs;
 421         final List<Path> classpath = options.classpath;
 422         final List<Path> headerFiles = options.headerFiles;
 423         final List<Path> manPages = options.manPages;
 424         final List<Path> legalNotices = options.legalNotices;
 425 
 426         final Version moduleVersion = options.moduleVersion;
 427         final String mainClass = options.mainClass;
 428         final String osName = options.osName;
 429         final String osArch = options.osArch;
 430         final String osVersion = options.osVersion;
 431         final List<PathMatcher> excludes = options.excludes;
 432         final ModuleResolution moduleResolution = options.moduleResolution;
 433 
 434         JmodFileWriter() { }
 435 
 436         /**
 437          * Writes the jmod to the given output stream.
 438          */
 439         void write(JmodOutputStream out) throws IOException {
 440             // module-info.class
 441             writeModuleInfo(out, findPackages(classpath));
 442 
 443             // classes
 444             processClasses(out, classpath);
 445 
 446             processSection(out, Section.CONFIG, configs);
 447             processSection(out, Section.HEADER_FILES, headerFiles);
 448             processSection(out, Section.LEGAL_NOTICES, legalNotices);
 449             processSection(out, Section.MAN_PAGES, manPages);
 450             processSection(out, Section.NATIVE_CMDS, cmds);
 451             processSection(out, Section.NATIVE_LIBS, libs);
 452 
 453         }
 454 
 455         /**
 456          * Returns a supplier of an input stream to the module-info.class
 457          * on the class path of directories and JAR files.
 458          */
 459         Supplier<InputStream> newModuleInfoSupplier() throws IOException {
 460             ByteArrayOutputStream baos = new ByteArrayOutputStream();
 461             for (Path e: classpath) {
 462                 if (Files.isDirectory(e)) {
 463                     Path mi = e.resolve(MODULE_INFO);
 464                     if (Files.isRegularFile(mi)) {
 465                         Files.copy(mi, baos);
 466                         break;
 467                     }
 468                 } else if (Files.isRegularFile(e) && e.toString().endsWith(".jar")) {
 469                     try (JarFile jf = new JarFile(e.toFile())) {
 470                         ZipEntry entry = jf.getEntry(MODULE_INFO);
 471                         if (entry != null) {
 472                             jf.getInputStream(entry).transferTo(baos);
 473                             break;
 474                         }
 475                     } catch (ZipException x) {
 476                         // Skip. Do nothing. No packages will be added.
 477                     }
 478                 }
 479             }
 480             if (baos.size() == 0) {
 481                 return null;
 482             } else {
 483                 byte[] bytes = baos.toByteArray();
 484                 return () -> new ByteArrayInputStream(bytes);
 485             }
 486         }
 487 
 488         /**
 489          * Writes the updated module-info.class to the ZIP output stream.
 490          *
 491          * The updated module-info.class will have a Packages attribute
 492          * with the set of module-private/non-exported packages.
 493          *
 494          * If --module-version, --main-class, or other options were provided
 495          * then the corresponding class file attributes are added to the
 496          * module-info here.
 497          */
 498         void writeModuleInfo(JmodOutputStream out, Set<String> packages)
 499             throws IOException
 500         {
 501             Supplier<InputStream> miSupplier = newModuleInfoSupplier();
 502             if (miSupplier == null) {
 503                 throw new IOException(MODULE_INFO + " not found");
 504             }
 505 
 506             ModuleDescriptor descriptor;
 507             try (InputStream in = miSupplier.get()) {
 508                 descriptor = ModuleDescriptor.read(in);
 509             }
 510 
 511             // copy the module-info.class into the jmod with the additional
 512             // attributes for the version, main class and other meta data
 513             try (InputStream in = miSupplier.get()) {
 514                 ModuleInfoExtender extender = ModuleInfoExtender.newExtender(in);
 515 
 516                 // Add (or replace) the Packages attribute
 517                 if (packages != null) {
 518                     validatePackages(descriptor, packages);
 519                     extender.packages(packages);
 520                 }
 521 
 522                 // --main-class
 523                 if (mainClass != null)
 524                     extender.mainClass(mainClass);
 525 
 526                 // --os-name, --os-arch, --os-version
 527                 if (osName != null || osArch != null || osVersion != null)
 528                     extender.targetPlatform(osName, osArch, osVersion);
 529 
 530                 // --module-version
 531                 if (moduleVersion != null)
 532                     extender.version(moduleVersion);
 533 
 534                 // --hash-modules
 535                 if (options.modulesToHash != null) {
 536                     // To compute hashes, it creates a Configuration to resolve
 537                     // a module graph.  The post-resolution check requires
 538                     // the packages in ModuleDescriptor be available for validation.
 539                     ModuleDescriptor md;
 540                     try (InputStream is = miSupplier.get()) {
 541                         md = ModuleDescriptor.read(is, () -> packages);
 542                     }
 543 
 544                     ModuleHashes moduleHashes = computeHashes(md);
 545                     if (moduleHashes != null) {
 546                         extender.hashes(moduleHashes);
 547                     } else {
 548                         warning("warn.no.module.hashes", descriptor.name());
 549                     }
 550                 }
 551 
 552                 if (moduleResolution != null && moduleResolution.value() != 0) {
 553                     extender.moduleResolution(moduleResolution);
 554                 }
 555 
 556                 // write the (possibly extended or modified) module-info.class
 557                 out.writeEntry(extender.toByteArray(), Section.CLASSES, MODULE_INFO);
 558             }
 559         }
 560 
 561         private void validatePackages(ModuleDescriptor descriptor, Set<String> packages) {
 562             Set<String> nonExistPackages = new TreeSet<>();
 563             descriptor.exports().stream()
 564                 .map(Exports::source)
 565                 .filter(pn -> !packages.contains(pn))
 566                 .forEach(nonExistPackages::add);
 567 
 568             descriptor.opens().stream()
 569                 .map(Opens::source)
 570                 .filter(pn -> !packages.contains(pn))
 571                 .forEach(nonExistPackages::add);
 572 
 573             if (!nonExistPackages.isEmpty()) {
 574                 throw new CommandException("err.missing.export.or.open.packages",
 575                     descriptor.name(), nonExistPackages);
 576             }
 577         }
 578 
 579         /*
 580          * Hasher resolves a module graph using the --hash-modules PATTERN
 581          * as the roots.
 582          *
 583          * The jmod file is being created and does not exist in the
 584          * given modulepath.
 585          */
 586         private ModuleHashes computeHashes(ModuleDescriptor descriptor) {
 587             String mn = descriptor.name();
 588             URI uri = options.jmodFile.toUri();
 589             ModuleReference mref = new ModuleReference(descriptor, uri) {
 590                 @Override
 591                 public ModuleReader open() {
 592                     throw new UnsupportedOperationException("opening " + mn);
 593                 }
 594             };
 595 
 596             // compose a module finder with the module path and also
 597             // a module finder that can find the jmod file being created
 598             ModuleFinder finder = ModuleFinder.compose(options.moduleFinder,
 599                 new ModuleFinder() {
 600                     @Override
 601                     public Optional<ModuleReference> find(String name) {
 602                         if (descriptor.name().equals(name))
 603                             return Optional.of(mref);
 604                         else return Optional.empty();
 605                     }
 606 
 607                     @Override
 608                     public Set<ModuleReference> findAll() {
 609                         return Collections.singleton(mref);
 610                     }
 611                 });
 612 
 613             return new Hasher(mn, finder).computeHashes().get(mn);
 614         }
 615 
 616         /**
 617          * Returns the set of all packages on the given class path.
 618          */
 619         Set<String> findPackages(List<Path> classpath) {
 620             Set<String> packages = new HashSet<>();
 621             for (Path path : classpath) {
 622                 if (Files.isDirectory(path)) {
 623                     packages.addAll(findPackages(path));
 624                 } else if (Files.isRegularFile(path) && path.toString().endsWith(".jar")) {
 625                     try (JarFile jf = new JarFile(path.toString())) {
 626                         packages.addAll(findPackages(jf));
 627                     } catch (ZipException x) {
 628                         // Skip. Do nothing. No packages will be added.
 629                     } catch (IOException ioe) {
 630                         throw new UncheckedIOException(ioe);
 631                     }
 632                 }
 633             }
 634             return packages;
 635         }
 636 
 637         /**
 638          * Returns the set of packages in the given directory tree.
 639          */
 640         Set<String> findPackages(Path dir) {
 641             try {
 642                 return Files.find(dir, Integer.MAX_VALUE,
 643                                   ((path, attrs) -> attrs.isRegularFile()))
 644                         .map(dir::relativize)
 645                         .filter(path -> isResource(path.toString()))
 646                         .map(path -> toPackageName(path))
 647                         .filter(pkg -> pkg.length() > 0)
 648                         .distinct()
 649                         .collect(Collectors.toSet());
 650             } catch (IOException ioe) {
 651                 throw new UncheckedIOException(ioe);
 652             }
 653         }
 654 
 655         /**
 656          * Returns the set of packages in the given JAR file.
 657          */
 658         Set<String> findPackages(JarFile jf) {
 659             return jf.stream()
 660                      .filter(e -> !e.isDirectory() && isResource(e.getName()))
 661                      .map(e -> toPackageName(e))
 662                      .filter(pkg -> pkg.length() > 0)
 663                      .distinct()
 664                      .collect(Collectors.toSet());
 665         }
 666 
 667         /**
 668          * Returns true if it's a .class or a resource with an effective
 669          * package name.
 670          */
 671         boolean isResource(String name) {
 672             name = name.replace(File.separatorChar, '/');
 673             return name.endsWith(".class") || !ResourceHelper.isSimpleResource(name);
 674         }
 675 
 676 
 677         String toPackageName(Path path) {
 678             String name = path.toString();
 679             int index = name.lastIndexOf(File.separatorChar);
 680             if (index != -1)
 681                 return name.substring(0, index).replace(File.separatorChar, '.');
 682 
 683             if (name.endsWith(".class") && !name.equals(MODULE_INFO)) {
 684                 IOException e = new IOException(name  + " in the unnamed package");
 685                 throw new UncheckedIOException(e);
 686             }
 687             return "";
 688         }
 689 
 690         String toPackageName(ZipEntry entry) {
 691             String name = entry.getName();
 692             int index = name.lastIndexOf("/");
 693             if (index != -1)
 694                 return name.substring(0, index).replace('/', '.');
 695 
 696             if (name.endsWith(".class") && !name.equals(MODULE_INFO)) {
 697                 IOException e = new IOException(name  + " in the unnamed package");
 698                 throw new UncheckedIOException(e);
 699             }
 700             return "";
 701         }
 702 
 703         void processClasses(JmodOutputStream out, List<Path> classpaths)
 704             throws IOException
 705         {
 706             if (classpaths == null)
 707                 return;
 708 
 709             for (Path p : classpaths) {
 710                 if (Files.isDirectory(p)) {
 711                     processSection(out, Section.CLASSES, p);
 712                 } else if (Files.isRegularFile(p) && p.toString().endsWith(".jar")) {
 713                     try (JarFile jf = new JarFile(p.toFile())) {
 714                         JarEntryConsumer jec = new JarEntryConsumer(out, jf);
 715                         jf.stream().filter(jec).forEach(jec);
 716                     }
 717                 }
 718             }
 719         }
 720 
 721         void processSection(JmodOutputStream out, Section section, List<Path> paths)
 722             throws IOException
 723         {
 724             if (paths == null)
 725                 return;
 726 
 727             for (Path p : paths) {
 728                 processSection(out, section, p);
 729             }
 730         }
 731 
 732         void processSection(JmodOutputStream out, Section section, Path path)
 733             throws IOException
 734         {
 735             Files.walkFileTree(path, Set.of(FileVisitOption.FOLLOW_LINKS),
 736                 Integer.MAX_VALUE, new SimpleFileVisitor<Path>() {
 737                     @Override
 738                     public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
 739                         throws IOException
 740                     {
 741                         Path relPath = path.relativize(file);
 742                         if (relPath.toString().equals(MODULE_INFO)
 743                                 && !Section.CLASSES.equals(section))
 744                             warning("warn.ignore.entry", MODULE_INFO, section);
 745 
 746                         if (!relPath.toString().equals(MODULE_INFO)
 747                                 && !matches(relPath, excludes)) {
 748                             try (InputStream in = Files.newInputStream(file)) {
 749                                 out.writeEntry(in, section, relPath.toString());
 750                             } catch (IOException x) {
 751                                 if (x.getMessage().contains("duplicate entry")) {
 752                                     warning("warn.ignore.duplicate.entry",
 753                                             relPath.toString(), section);
 754                                     return FileVisitResult.CONTINUE;
 755                                 }
 756                                 throw x;
 757                             }
 758                         }
 759                         return FileVisitResult.CONTINUE;
 760                     }
 761                 });
 762         }
 763 
 764         boolean matches(Path path, List<PathMatcher> matchers) {
 765             if (matchers != null) {
 766                 for (PathMatcher pm : matchers) {
 767                     if (pm.matches(path))
 768                         return true;
 769                 }
 770             }
 771             return false;
 772         }
 773 
 774         class JarEntryConsumer implements Consumer<JarEntry>, Predicate<JarEntry> {
 775             final JmodOutputStream out;
 776             final JarFile jarfile;
 777             JarEntryConsumer(JmodOutputStream out, JarFile jarfile) {
 778                 this.out = out;
 779                 this.jarfile = jarfile;
 780             }
 781             @Override
 782             public void accept(JarEntry je) {
 783                 try (InputStream in = jarfile.getInputStream(je)) {
 784                     out.writeEntry(in, Section.CLASSES, je.getName());
 785                 } catch (IOException e) {
 786                     throw new UncheckedIOException(e);
 787                 }
 788             }
 789             @Override
 790             public boolean test(JarEntry je) {
 791                 String name = je.getName();
 792                 // ## no support for excludes. Is it really needed?
 793                 return !name.endsWith(MODULE_INFO) && !je.isDirectory();
 794             }
 795         }
 796     }
 797 
 798     /**
 799      * Compute and record hashes
 800      */
 801     private class Hasher {
 802         final Configuration configuration;
 803         final ModuleHashesBuilder hashesBuilder;
 804         final Set<String> modules;
 805         final String moduleName;  // a specific module to record hashes, if set
 806 
 807         /**
 808          * This constructor is for jmod hash command.
 809          *
 810          * This Hasher will determine which modules to record hashes, i.e.
 811          * the module in a subgraph of modules to be hashed and that
 812          * has no outgoing edges.  It will record in each of these modules,
 813          * say `M`, with the the hashes of modules that depend upon M
 814          * directly or indirectly matching the specified --hash-modules pattern.
 815          */
 816         Hasher(ModuleFinder finder) {
 817             this(null, finder);
 818         }
 819 
 820         /**
 821          * Constructs a Hasher to compute hashes.
 822          *
 823          * If a module name `M` is specified, it will compute the hashes of
 824          * modules that depend upon M directly or indirectly matching the
 825          * specified --hash-modules pattern and record in the ModuleHashes
 826          * attribute in M's module-info.class.
 827          *
 828          * @param name    name of the module to record hashes
 829          * @param finder  module finder for the specified --module-path
 830          */
 831         Hasher(String name, ModuleFinder finder) {
 832             // Determine the modules that matches the pattern {@code modulesToHash}
 833             Set<String> roots = finder.findAll().stream()
 834                 .map(mref -> mref.descriptor().name())
 835                 .filter(mn -> options.modulesToHash.matcher(mn).find())
 836                 .collect(Collectors.toSet());
 837 
 838             // use system module path unless it creates a JMOD file for
 839             // a module that is present in the system image e.g. upgradeable
 840             // module
 841             ModuleFinder system;
 842             if (name != null && ModuleFinder.ofSystem().find(name).isPresent()) {
 843                 system = ModuleFinder.of();
 844             } else {
 845                 system = ModuleFinder.ofSystem();
 846             }
 847             // get a resolved module graph
 848             Configuration config = null;
 849             try {
 850                 config = Configuration.empty().resolveRequires(system, finder, roots);
 851             } catch (ResolutionException e) {
 852                 throw new CommandException("err.module.resolution.fail", e.getMessage());
 853             }
 854 
 855             this.moduleName = name;
 856             this.configuration = config;
 857 
 858             // filter modules resolved from the system module finder
 859             this.modules = config.modules().stream()
 860                 .map(ResolvedModule::name)
 861                 .filter(mn -> roots.contains(mn) && !system.find(mn).isPresent())
 862                 .collect(Collectors.toSet());
 863 
 864             this.hashesBuilder = new ModuleHashesBuilder(config, modules);
 865         }
 866 
 867         /**
 868          * Returns a map of a module M to record hashes of the modules
 869          * that depend upon M directly or indirectly.
 870          *
 871          * For jmod hash command, the returned map contains one entry
 872          * for each module M that has no outgoing edges to any of the
 873          * modules matching the specified --hash-modules pattern.
 874          *
 875          * Each entry represents a leaf node in a connected subgraph containing
 876          * M and other candidate modules from the module graph where M's outgoing
 877          * edges to any module other than the ones matching the specified
 878          * --hash-modules pattern are excluded.
 879          */
 880         Map<String, ModuleHashes> computeHashes() {
 881             if (hashesBuilder == null)
 882                 return null;
 883 
 884             if (moduleName != null) {
 885                 return hashesBuilder.computeHashes(Set.of(moduleName));
 886             } else {
 887                 return hashesBuilder.computeHashes(modules);
 888             }
 889         }
 890 
 891         /**
 892          * Reads the given input stream of module-info.class and write
 893          * the extended module-info.class with the given ModuleHashes
 894          *
 895          * @param in       InputStream of module-info.class
 896          * @param out      OutputStream to write the extended module-info.class
 897          * @param hashes   ModuleHashes
 898          */
 899         private void recordHashes(InputStream in, OutputStream out, ModuleHashes hashes)
 900             throws IOException
 901         {
 902             ModuleInfoExtender extender = ModuleInfoExtender.newExtender(in);
 903             extender.hashes(hashes);
 904             extender.write(out);
 905         }
 906 
 907         void updateModuleInfo(String name, ModuleHashes moduleHashes)
 908             throws IOException
 909         {
 910             Path target = moduleToPath(name);
 911             Path tempTarget = Files.createTempFile(target.getFileName().toString(), ".tmp");
 912             try {
 913                 if (target.getFileName().toString().endsWith(".jmod")) {
 914                     updateJmodFile(target, tempTarget, moduleHashes);
 915                 } else {
 916                     updateModularJar(target, tempTarget, moduleHashes);
 917                 }
 918             } catch (IOException|RuntimeException e) {
 919                 if (Files.exists(tempTarget)) {
 920                     try {
 921                         Files.delete(tempTarget);
 922                     } catch (IOException ioe) {
 923                         e.addSuppressed(ioe);
 924                     }
 925                 }
 926                 throw e;
 927             }
 928 
 929             out.println(getMessage("module.hashes.recorded", name));
 930             Files.move(tempTarget, target, StandardCopyOption.REPLACE_EXISTING);
 931         }
 932 
 933         private void updateModularJar(Path target, Path tempTarget,
 934                                       ModuleHashes moduleHashes)
 935             throws IOException
 936         {
 937             try (JarFile jf = new JarFile(target.toFile());
 938                  OutputStream out = Files.newOutputStream(tempTarget);
 939                  JarOutputStream jos = new JarOutputStream(out))
 940             {
 941                 jf.stream().forEach(e -> {
 942                     try (InputStream in = jf.getInputStream(e)) {
 943                         if (e.getName().equals(MODULE_INFO)) {
 944                             // what about module-info.class in versioned entries?
 945                             ZipEntry ze = new ZipEntry(e.getName());
 946                             ze.setTime(System.currentTimeMillis());
 947                             jos.putNextEntry(ze);
 948                             recordHashes(in, jos, moduleHashes);
 949                             jos.closeEntry();
 950                         } else {
 951                             jos.putNextEntry(e);
 952                             jos.write(in.readAllBytes());
 953                             jos.closeEntry();
 954                         }
 955                     } catch (IOException x) {
 956                         throw new UncheckedIOException(x);
 957                     }
 958                 });
 959             }
 960         }
 961 
 962         private void updateJmodFile(Path target, Path tempTarget,
 963                                     ModuleHashes moduleHashes)
 964             throws IOException
 965         {
 966 
 967             try (JmodFile jf = new JmodFile(target);
 968                  JmodOutputStream jos = JmodOutputStream.newOutputStream(tempTarget))
 969             {
 970                 jf.stream().forEach(e -> {
 971                     try (InputStream in = jf.getInputStream(e.section(), e.name())) {
 972                         if (e.name().equals(MODULE_INFO)) {
 973                             // replace module-info.class
 974                             ModuleInfoExtender extender =
 975                                 ModuleInfoExtender.newExtender(in);
 976                             extender.hashes(moduleHashes);
 977                             jos.writeEntry(extender.toByteArray(), e.section(), e.name());
 978                         } else {
 979                             jos.writeEntry(in, e);
 980                         }
 981                     } catch (IOException x) {
 982                         throw new UncheckedIOException(x);
 983                     }
 984                 });
 985             }
 986         }
 987 
 988         private Path moduleToPath(String name) {
 989             ResolvedModule rm = configuration.findModule(name).orElseThrow(
 990                 () -> new InternalError("Selected module " + name + " not on module path"));
 991 
 992             URI uri = rm.reference().location().get();
 993             Path path = Paths.get(uri);
 994             String fn = path.getFileName().toString();
 995             if (!fn.endsWith(".jar") && !fn.endsWith(".jmod")) {
 996                 throw new InternalError(path + " is not a modular JAR or jmod file");
 997             }
 998             return path;
 999         }
1000     }
1001 
1002     /**
1003      * An abstract converter that given a string representing a list of paths,
1004      * separated by the File.pathSeparator, returns a List of java.nio.Path's.
1005      * Specific subclasses should do whatever validation is required on the
1006      * individual path elements, if any.
1007      */
1008     static abstract class AbstractPathConverter implements ValueConverter<List<Path>> {
1009         @Override
1010         public List<Path> convert(String value) {
1011             List<Path> paths = new ArrayList<>();
1012             String[] pathElements = value.split(File.pathSeparator);
1013             for (String pathElement : pathElements) {
1014                 paths.add(toPath(pathElement));
1015             }
1016             return paths;
1017         }
1018 
1019         @SuppressWarnings("unchecked")
1020         @Override
1021         public Class<List<Path>> valueType() {
1022             return (Class<List<Path>>)(Object)List.class;
1023         }
1024 
1025         @Override public String valuePattern() { return "path"; }
1026 
1027         abstract Path toPath(String path);
1028     }
1029 
1030     static class ClassPathConverter extends AbstractPathConverter {
1031         static final ValueConverter<List<Path>> INSTANCE = new ClassPathConverter();
1032 
1033         @Override
1034         public Path toPath(String value) {
1035             try {
1036                 Path path = CWD.resolve(value);
1037                 if (Files.notExists(path))
1038                     throw new CommandException("err.path.not.found", path);
1039                 if (!(Files.isDirectory(path) ||
1040                         (Files.isRegularFile(path) && path.toString().endsWith(".jar"))))
1041                     throw new CommandException("err.invalid.class.path.entry", path);
1042                 return path;
1043             } catch (InvalidPathException x) {
1044                 throw new CommandException("err.path.not.valid", value);
1045             }
1046         }
1047     }
1048 
1049     static class DirPathConverter extends AbstractPathConverter {
1050         static final ValueConverter<List<Path>> INSTANCE = new DirPathConverter();
1051 
1052         @Override
1053         public Path toPath(String value) {
1054             try {
1055                 Path path = CWD.resolve(value);
1056                 if (Files.notExists(path))
1057                     throw new CommandException("err.path.not.found", path);
1058                 if (!Files.isDirectory(path))
1059                     throw new CommandException("err.path.not.a.dir", path);
1060                 return path;
1061             } catch (InvalidPathException x) {
1062                 throw new CommandException("err.path.not.valid", value);
1063             }
1064         }
1065     }
1066 
1067     static class ExtractDirPathConverter implements ValueConverter<Path> {
1068 
1069         @Override
1070         public Path convert(String value) {
1071             try {
1072                 Path path = CWD.resolve(value);
1073                 if (Files.exists(path)) {
1074                     if (!Files.isDirectory(path))
1075                         throw new CommandException("err.cannot.create.dir", path);
1076                 }
1077                 return path;
1078             } catch (InvalidPathException x) {
1079                 throw new CommandException("err.path.not.valid", value);
1080             }
1081         }
1082 
1083         @Override  public Class<Path> valueType() { return Path.class; }
1084 
1085         @Override  public String valuePattern() { return "path"; }
1086     }
1087 
1088     static class ModuleVersionConverter implements ValueConverter<Version> {
1089         @Override
1090         public Version convert(String value) {
1091             try {
1092                 return Version.parse(value);
1093             } catch (IllegalArgumentException x) {
1094                 throw new CommandException("err.invalid.version", x.getMessage());
1095             }
1096         }
1097 
1098         @Override public Class<Version> valueType() { return Version.class; }
1099 
1100         @Override public String valuePattern() { return "module-version"; }
1101     }
1102 
1103     static class WarnIfResolvedReasonConverter
1104         implements ValueConverter<ModuleResolution>
1105     {
1106         @Override
1107         public ModuleResolution convert(String value) {
1108             if (value.equals("deprecated"))
1109                 return ModuleResolution.empty().withDeprecated();
1110             else if (value.equals("deprecated-for-removal"))
1111                 return ModuleResolution.empty().withDeprecatedForRemoval();
1112             else if (value.equals("incubating"))
1113                 return ModuleResolution.empty().withIncubating();
1114             else
1115                 throw new CommandException("err.bad.WarnIfResolvedReason", value);
1116         }
1117 
1118         @Override public Class<ModuleResolution> valueType() {
1119             return ModuleResolution.class;
1120         }
1121 
1122         @Override public String valuePattern() { return "reason"; }
1123     }
1124 
1125     static class PatternConverter implements ValueConverter<Pattern> {
1126         @Override
1127         public Pattern convert(String value) {
1128             try {
1129                 if (value.startsWith("regex:")) {
1130                     value = value.substring("regex:".length()).trim();
1131                 }
1132 
1133                 return Pattern.compile(value);
1134             } catch (PatternSyntaxException e) {
1135                 throw new CommandException("err.bad.pattern", value);
1136             }
1137         }
1138 
1139         @Override public Class<Pattern> valueType() { return Pattern.class; }
1140 
1141         @Override public String valuePattern() { return "regex-pattern"; }
1142     }
1143 
1144     static class PathMatcherConverter implements ValueConverter<PathMatcher> {
1145         @Override
1146         public PathMatcher convert(String pattern) {
1147             try {
1148                 return Utils.getPathMatcher(FileSystems.getDefault(), pattern);
1149             } catch (PatternSyntaxException e) {
1150                 throw new CommandException("err.bad.pattern", pattern);
1151             }
1152         }
1153 
1154         @Override public Class<PathMatcher> valueType() { return PathMatcher.class; }
1155 
1156         @Override public String valuePattern() { return "pattern-list"; }
1157     }
1158 
1159     /* Support for @<file> in jmod help */
1160     private static final String CMD_FILENAME = "@<filename>";
1161 
1162     /**
1163      * This formatter is adding the @filename option and does the required
1164      * formatting.
1165      */
1166     private static final class JmodHelpFormatter extends BuiltinHelpFormatter {
1167 
1168         private final Options opts;
1169 
1170         private JmodHelpFormatter(Options opts) {
1171             super(80, 2);
1172             this.opts = opts;
1173         }
1174 
1175         @Override
1176         public String format(Map<String, ? extends OptionDescriptor> options) {
1177             Map<String, OptionDescriptor> all = new LinkedHashMap<>();
1178             all.putAll(options);
1179 
1180             // extra options
1181             if (!opts.helpExtra) {
1182                 all.remove("do-not-resolve-by-default");
1183                 all.remove("warn-if-resolved");
1184             }
1185 
1186             all.put(CMD_FILENAME, new OptionDescriptor() {
1187                 @Override
1188                 public Collection<String> options() {
1189                     List<String> ret = new ArrayList<>();
1190                     ret.add(CMD_FILENAME);
1191                     return ret;
1192                 }
1193                 @Override
1194                 public String description() { return getMessage("main.opt.cmdfile"); }
1195                 @Override
1196                 public List<?> defaultValues() { return Collections.emptyList(); }
1197                 @Override
1198                 public boolean isRequired() { return false; }
1199                 @Override
1200                 public boolean acceptsArguments() { return false; }
1201                 @Override
1202                 public boolean requiresArgument() { return false; }
1203                 @Override
1204                 public String argumentDescription() { return null; }
1205                 @Override
1206                 public String argumentTypeIndicator() { return null; }
1207                 @Override
1208                 public boolean representsNonOptions() { return false; }
1209             });
1210             String content = super.format(all);
1211             StringBuilder builder = new StringBuilder();
1212 
1213             builder.append(getMessage("main.opt.mode")).append("\n  ");
1214             builder.append(getMessage("main.opt.mode.create")).append("\n  ");
1215             builder.append(getMessage("main.opt.mode.extract")).append("\n  ");
1216             builder.append(getMessage("main.opt.mode.list")).append("\n  ");
1217             builder.append(getMessage("main.opt.mode.describe")).append("\n  ");
1218             builder.append(getMessage("main.opt.mode.hash")).append("\n\n");
1219 
1220             String cmdfile = null;
1221             String[] lines = content.split("\n");
1222             for (String line : lines) {
1223                 if (line.startsWith("--@")) {
1224                     cmdfile = line.replace("--" + CMD_FILENAME, CMD_FILENAME + "  ");
1225                 } else if (line.startsWith("Option") || line.startsWith("------")) {
1226                     builder.append(" ").append(line).append("\n");
1227                 } else if (!line.matches("Non-option arguments")){
1228                     builder.append("  ").append(line).append("\n");
1229                 }
1230             }
1231             if (cmdfile != null) {
1232                 builder.append("  ").append(cmdfile).append("\n");
1233             }
1234             return builder.toString();
1235         }
1236     }
1237 
1238     private final OptionParser parser = new OptionParser("hp");
1239 
1240     private void handleOptions(String[] args) {
1241         options = new Options();
1242         parser.formatHelpWith(new JmodHelpFormatter(options));
1243 
1244         OptionSpec<List<Path>> classPath
1245                 = parser.accepts("class-path", getMessage("main.opt.class-path"))
1246                         .withRequiredArg()
1247                         .withValuesConvertedBy(ClassPathConverter.INSTANCE);
1248 
1249         OptionSpec<List<Path>> cmds
1250                 = parser.accepts("cmds", getMessage("main.opt.cmds"))
1251                         .withRequiredArg()
1252                         .withValuesConvertedBy(DirPathConverter.INSTANCE);
1253 
1254         OptionSpec<List<Path>> config
1255                 = parser.accepts("config", getMessage("main.opt.config"))
1256                         .withRequiredArg()
1257                         .withValuesConvertedBy(DirPathConverter.INSTANCE);
1258 
1259         OptionSpec<Path> dir
1260                 = parser.accepts("dir", getMessage("main.opt.extractDir"))
1261                         .withRequiredArg()
1262                         .withValuesConvertedBy(new ExtractDirPathConverter());
1263 
1264         OptionSpec<Void> dryrun
1265                 = parser.accepts("dry-run", getMessage("main.opt.dry-run"));
1266 
1267         OptionSpec<PathMatcher> excludes
1268                 = parser.accepts("exclude", getMessage("main.opt.exclude"))
1269                         .withRequiredArg()
1270                         .withValuesConvertedBy(new PathMatcherConverter());
1271 
1272         OptionSpec<Pattern> hashModules
1273                 = parser.accepts("hash-modules", getMessage("main.opt.hash-modules"))
1274                         .withRequiredArg()
1275                         .withValuesConvertedBy(new PatternConverter());
1276 
1277         OptionSpec<Void> help
1278                 = parser.acceptsAll(Set.of("h", "help"), getMessage("main.opt.help"))
1279                         .forHelp();
1280 
1281         OptionSpec<Void> helpExtra
1282                 = parser.accepts("help-extra", getMessage("main.opt.help-extra"));
1283 
1284         OptionSpec<List<Path>> headerFiles
1285                 = parser.accepts("header-files", getMessage("main.opt.header-files"))
1286                         .withRequiredArg()
1287                         .withValuesConvertedBy(DirPathConverter.INSTANCE);
1288 
1289         OptionSpec<List<Path>> libs
1290                 = parser.accepts("libs", getMessage("main.opt.libs"))
1291                         .withRequiredArg()
1292                         .withValuesConvertedBy(DirPathConverter.INSTANCE);
1293 
1294         OptionSpec<List<Path>> legalNotices
1295                 = parser.accepts("legal-notices", getMessage("main.opt.legal-notices"))
1296                         .withRequiredArg()
1297                         .withValuesConvertedBy(DirPathConverter.INSTANCE);
1298 
1299 
1300         OptionSpec<String> mainClass
1301                 = parser.accepts("main-class", getMessage("main.opt.main-class"))
1302                         .withRequiredArg()
1303                         .describedAs(getMessage("main.opt.main-class.arg"));
1304 
1305         OptionSpec<List<Path>> manPages
1306                 = parser.accepts("man-pages", getMessage("main.opt.man-pages"))
1307                         .withRequiredArg()
1308                         .withValuesConvertedBy(DirPathConverter.INSTANCE);
1309 
1310         OptionSpec<List<Path>> modulePath
1311                 = parser.acceptsAll(Set.of("p", "module-path"),
1312                                     getMessage("main.opt.module-path"))
1313                         .withRequiredArg()
1314                         .withValuesConvertedBy(DirPathConverter.INSTANCE);
1315 
1316         OptionSpec<Version> moduleVersion
1317                 = parser.accepts("module-version", getMessage("main.opt.module-version"))
1318                         .withRequiredArg()
1319                         .withValuesConvertedBy(new ModuleVersionConverter());
1320 
1321         OptionSpec<String> osName
1322                 = parser.accepts("os-name", getMessage("main.opt.os-name"))
1323                         .withRequiredArg()
1324                         .describedAs(getMessage("main.opt.os-name.arg"));
1325 
1326         OptionSpec<String> osArch
1327                 = parser.accepts("os-arch", getMessage("main.opt.os-arch"))
1328                         .withRequiredArg()
1329                         .describedAs(getMessage("main.opt.os-arch.arg"));
1330 
1331         OptionSpec<String> osVersion
1332                 = parser.accepts("os-version", getMessage("main.opt.os-version"))
1333                         .withRequiredArg()
1334                         .describedAs(getMessage("main.opt.os-version.arg"));
1335 
1336         OptionSpec<Void> doNotResolveByDefault
1337                 = parser.accepts("do-not-resolve-by-default",
1338                                  getMessage("main.opt.do-not-resolve-by-default"));
1339 
1340         OptionSpec<ModuleResolution> warnIfResolved
1341                 = parser.accepts("warn-if-resolved", getMessage("main.opt.warn-if-resolved"))
1342                         .withRequiredArg()
1343                         .withValuesConvertedBy(new WarnIfResolvedReasonConverter());
1344 
1345         OptionSpec<Void> version
1346                 = parser.accepts("version", getMessage("main.opt.version"));
1347 
1348         NonOptionArgumentSpec<String> nonOptions
1349                 = parser.nonOptions();
1350 
1351         try {
1352             OptionSet opts = parser.parse(args);
1353 
1354             if (opts.has(help) || opts.has(helpExtra) || opts.has(version)) {
1355                 options.help = opts.has(help);
1356                 options.helpExtra = opts.has(helpExtra);
1357                 options.version = opts.has(version);
1358                 return;  // informational message will be shown
1359             }
1360 
1361             List<String> words = opts.valuesOf(nonOptions);
1362             if (words.isEmpty())
1363                 throw new CommandException("err.missing.mode").showUsage(true);
1364             String verb = words.get(0);
1365             try {
1366                 options.mode = Enum.valueOf(Mode.class, verb.toUpperCase());
1367             } catch (IllegalArgumentException e) {
1368                 throw new CommandException("err.invalid.mode", verb).showUsage(true);
1369             }
1370 
1371             if (opts.has(classPath))
1372                 options.classpath = getLastElement(opts.valuesOf(classPath));
1373             if (opts.has(cmds))
1374                 options.cmds = getLastElement(opts.valuesOf(cmds));
1375             if (opts.has(config))
1376                 options.configs = getLastElement(opts.valuesOf(config));
1377             if (opts.has(dir))
1378                 options.extractDir = getLastElement(opts.valuesOf(dir));
1379             if (opts.has(dryrun))
1380                 options.dryrun = true;
1381             if (opts.has(excludes))
1382                 options.excludes = opts.valuesOf(excludes);  // excludes is repeatable
1383             if (opts.has(libs))
1384                 options.libs = getLastElement(opts.valuesOf(libs));
1385             if (opts.has(headerFiles))
1386                 options.headerFiles = getLastElement(opts.valuesOf(headerFiles));
1387             if (opts.has(manPages))
1388                 options.manPages = getLastElement(opts.valuesOf(manPages));
1389             if (opts.has(legalNotices))
1390                 options.legalNotices = getLastElement(opts.valuesOf(legalNotices));
1391             if (opts.has(modulePath)) {
1392                 Path[] dirs = getLastElement(opts.valuesOf(modulePath)).toArray(new Path[0]);
1393                 options.moduleFinder = new ModulePath(Runtime.version(), true, dirs);
1394             }
1395             if (opts.has(moduleVersion))
1396                 options.moduleVersion = getLastElement(opts.valuesOf(moduleVersion));
1397             if (opts.has(mainClass))
1398                 options.mainClass = getLastElement(opts.valuesOf(mainClass));
1399             if (opts.has(osName))
1400                 options.osName = getLastElement(opts.valuesOf(osName));
1401             if (opts.has(osArch))
1402                 options.osArch = getLastElement(opts.valuesOf(osArch));
1403             if (opts.has(osVersion))
1404                 options.osVersion = getLastElement(opts.valuesOf(osVersion));
1405             if (opts.has(warnIfResolved))
1406                 options.moduleResolution = getLastElement(opts.valuesOf(warnIfResolved));
1407             if (opts.has(doNotResolveByDefault)) {
1408                 if (options.moduleResolution == null)
1409                     options.moduleResolution = ModuleResolution.empty();
1410                 options.moduleResolution = options.moduleResolution.withDoNotResolveByDefault();
1411             }
1412             if (opts.has(hashModules)) {
1413                 options.modulesToHash = getLastElement(opts.valuesOf(hashModules));
1414                 // if storing hashes then the module path is required
1415                 if (options.moduleFinder == null)
1416                     throw new CommandException("err.modulepath.must.be.specified")
1417                             .showUsage(true);
1418             }
1419 
1420             if (options.mode.equals(Mode.HASH)) {
1421                 if (options.moduleFinder == null || options.modulesToHash == null)
1422                     throw new CommandException("err.modulepath.must.be.specified")
1423                             .showUsage(true);
1424             } else {
1425                 if (words.size() <= 1)
1426                     throw new CommandException("err.jmod.must.be.specified").showUsage(true);
1427                 Path path = Paths.get(words.get(1));
1428 
1429                 if (options.mode.equals(Mode.CREATE) && Files.exists(path))
1430                     throw new CommandException("err.file.already.exists", path);
1431                 else if ((options.mode.equals(Mode.LIST) ||
1432                             options.mode.equals(Mode.DESCRIBE) ||
1433                             options.mode.equals((Mode.EXTRACT)))
1434                          && Files.notExists(path))
1435                     throw new CommandException("err.jmod.not.found", path);
1436 
1437                 if (options.dryrun) {
1438                     throw new CommandException("err.invalid.dryrun.option");
1439                 }
1440                 options.jmodFile = path;
1441 
1442                 if (words.size() > 2)
1443                     throw new CommandException("err.unknown.option",
1444                             words.subList(2, words.size())).showUsage(true);
1445             }
1446 
1447             if (options.mode.equals(Mode.CREATE) && options.classpath == null)
1448                 throw new CommandException("err.classpath.must.be.specified").showUsage(true);
1449             if (options.mainClass != null && !isValidJavaIdentifier(options.mainClass))
1450                 throw new CommandException("err.invalid.main-class", options.mainClass);
1451             if (options.mode.equals(Mode.EXTRACT) && options.extractDir != null) {
1452                 try {
1453                     Files.createDirectories(options.extractDir);
1454                 } catch (IOException ioe) {
1455                     throw new CommandException("err.cannot.create.dir", options.extractDir);
1456                 }
1457             }
1458         } catch (OptionException e) {
1459              throw new CommandException(e.getMessage());
1460         }
1461     }
1462 
1463     /**
1464      * Returns true if, and only if, the given main class is a legal.
1465      */
1466     static boolean isValidJavaIdentifier(String mainClass) {
1467         if (mainClass.length() == 0)
1468             return false;
1469 
1470         if (!Character.isJavaIdentifierStart(mainClass.charAt(0)))
1471             return false;
1472 
1473         int n = mainClass.length();
1474         for (int i=1; i < n; i++) {
1475             char c = mainClass.charAt(i);
1476             if (!Character.isJavaIdentifierPart(c) && c != '.')
1477                 return false;
1478         }
1479         if (mainClass.charAt(n-1) == '.')
1480             return false;
1481 
1482         return true;
1483     }
1484 
1485     static <E> E getLastElement(List<E> list) {
1486         if (list.size() == 0)
1487             throw new InternalError("Unexpected 0 list size");
1488         return list.get(list.size() - 1);
1489     }
1490 
1491     private void reportError(String message) {
1492         out.println(getMessage("error.prefix") + " " + message);
1493     }
1494 
1495     private void warning(String key, Object... args) {
1496         out.println(getMessage("warn.prefix") + " " + getMessage(key, args));
1497     }
1498 
1499     private void showUsageSummary() {
1500         out.println(getMessage("main.usage.summary", PROGNAME));
1501     }
1502 
1503     private void showHelp() {
1504         out.println(getMessage("main.usage", PROGNAME));
1505         try {
1506             parser.printHelpOn(out);
1507         } catch (IOException x) {
1508             throw new AssertionError(x);
1509         }
1510     }
1511 
1512     private void showVersion() {
1513         out.println(version());
1514     }
1515 
1516     private String version() {
1517         return System.getProperty("java.version");
1518     }
1519 
1520     private static String getMessage(String key, Object... args) {
1521         try {
1522             return MessageFormat.format(ResourceBundleHelper.bundle.getString(key), args);
1523         } catch (MissingResourceException e) {
1524             throw new InternalError("Missing message: " + key);
1525         }
1526     }
1527 
1528     private static class ResourceBundleHelper {
1529         static final ResourceBundle bundle;
1530 
1531         static {
1532             Locale locale = Locale.getDefault();
1533             try {
1534                 bundle = ResourceBundle.getBundle("jdk.tools.jmod.resources.jmod", locale);
1535             } catch (MissingResourceException e) {
1536                 throw new InternalError("Cannot find jmod resource bundle for locale " + locale);
1537             }
1538         }
1539     }
1540 }