1 /*
   2  * Copyright (c) 2012, 2014, 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 com.sun.tools.jdeps;
  26 
  27 import com.sun.tools.classfile.AccessFlags;
  28 import com.sun.tools.classfile.ClassFile;
  29 import com.sun.tools.classfile.ConstantPoolException;
  30 import com.sun.tools.classfile.Dependencies;
  31 import com.sun.tools.classfile.Dependencies.ClassFileError;
  32 import com.sun.tools.classfile.Dependency;
  33 import com.sun.tools.classfile.Dependency.Location;
  34 import com.sun.tools.jdeps.PlatformClassPath.JDKArchive;
  35 import static com.sun.tools.jdeps.Analyzer.Type.*;
  36 import java.io.*;
  37 import java.nio.file.DirectoryStream;
  38 import java.nio.file.Files;
  39 import java.nio.file.Path;
  40 import java.nio.file.Paths;
  41 import java.text.MessageFormat;
  42 import java.util.*;
  43 import java.util.regex.Pattern;
  44 
  45 /**
  46  * Implementation for the jdeps tool for static class dependency analysis.
  47  */
  48 class JdepsTask {
  49     static class BadArgs extends Exception {
  50         static final long serialVersionUID = 8765093759964640721L;
  51         BadArgs(String key, Object... args) {
  52             super(JdepsTask.getMessage(key, args));
  53             this.key = key;
  54             this.args = args;
  55         }
  56 
  57         BadArgs showUsage(boolean b) {
  58             showUsage = b;
  59             return this;
  60         }
  61         final String key;
  62         final Object[] args;
  63         boolean showUsage;
  64     }
  65 
  66     static abstract class Option {
  67         Option(boolean hasArg, String... aliases) {
  68             this.hasArg = hasArg;
  69             this.aliases = aliases;
  70         }
  71 
  72         boolean isHidden() {
  73             return false;
  74         }
  75 
  76         boolean matches(String opt) {
  77             for (String a : aliases) {
  78                 if (a.equals(opt))
  79                     return true;
  80                 if (hasArg && opt.startsWith(a + "="))
  81                     return true;
  82             }
  83             return false;
  84         }
  85 
  86         boolean ignoreRest() {
  87             return false;
  88         }
  89 
  90         abstract void process(JdepsTask task, String opt, String arg) throws BadArgs;
  91         final boolean hasArg;
  92         final String[] aliases;
  93     }
  94 
  95     static abstract class HiddenOption extends Option {
  96         HiddenOption(boolean hasArg, String... aliases) {
  97             super(hasArg, aliases);
  98         }
  99 
 100         boolean isHidden() {
 101             return true;
 102         }
 103     }
 104 
 105     static Option[] recognizedOptions = {
 106         new Option(false, "-h", "-?", "-help") {
 107             void process(JdepsTask task, String opt, String arg) {
 108                 task.options.help = true;
 109             }
 110         },
 111         new Option(true, "-dotoutput") {
 112             void process(JdepsTask task, String opt, String arg) throws BadArgs {
 113                 Path p = Paths.get(arg);
 114                 if (Files.exists(p) && (!Files.isDirectory(p) || !Files.isWritable(p))) {
 115                     throw new BadArgs("err.invalid.path", arg);
 116                 }
 117                 task.options.dotOutputDir = arg;
 118             }
 119         },
 120         new Option(false, "-s", "-summary") {
 121             void process(JdepsTask task, String opt, String arg) {
 122                 task.options.showSummary = true;
 123                 task.options.verbose = SUMMARY;
 124             }
 125         },
 126         new Option(false, "-v", "-verbose",
 127                           "-verbose:package",
 128                           "-verbose:class") {
 129             void process(JdepsTask task, String opt, String arg) throws BadArgs {
 130                 switch (opt) {
 131                     case "-v":
 132                     case "-verbose":
 133                         task.options.verbose = VERBOSE;
 134                         task.options.filterSameArchive = false;
 135                         task.options.filterSamePackage = false;
 136                         break;
 137                     case "-verbose:package":
 138                         task.options.verbose = PACKAGE;
 139                         break;
 140                     case "-verbose:class":
 141                         task.options.verbose = CLASS;
 142                         break;
 143                     default:
 144                         throw new BadArgs("err.invalid.arg.for.option", opt);
 145                 }
 146             }
 147         },
 148         new Option(true, "-cp", "-classpath") {
 149             void process(JdepsTask task, String opt, String arg) {
 150                 task.options.classpath = arg;
 151             }
 152         },
 153         new Option(true, "-p", "-package") {
 154             void process(JdepsTask task, String opt, String arg) {
 155                 task.options.packageNames.add(arg);
 156             }
 157         },
 158         new Option(true, "-e", "-regex") {
 159             void process(JdepsTask task, String opt, String arg) {
 160                 task.options.regex = arg;
 161             }
 162         },
 163 
 164         new Option(true, "-f", "-filter") {
 165             void process(JdepsTask task, String opt, String arg) {
 166                 task.options.filterRegex = arg;
 167             }
 168         },
 169         new Option(false, "-filter:package",
 170                           "-filter:archive",
 171                           "-filter:none") {
 172             void process(JdepsTask task, String opt, String arg) {
 173                 switch (opt) {
 174                     case "-filter:package":
 175                         task.options.filterSamePackage = true;
 176                         task.options.filterSameArchive = false;
 177                         break;
 178                     case "-filter:archive":
 179                         task.options.filterSameArchive = true;
 180                         task.options.filterSamePackage = false;
 181                         break;
 182                     case "-filter:none":
 183                         task.options.filterSameArchive = false;
 184                         task.options.filterSamePackage = false;
 185                         break;
 186                 }
 187             }
 188         },
 189         new Option(true, "-include") {
 190             void process(JdepsTask task, String opt, String arg) throws BadArgs {
 191                 task.options.includePattern = Pattern.compile(arg);
 192             }
 193         },
 194         new Option(false, "-P", "-profile") {
 195             void process(JdepsTask task, String opt, String arg) throws BadArgs {
 196                 task.options.showProfile = true;
 197                 if (Profile.getProfileCount() == 0) {
 198                     throw new BadArgs("err.option.unsupported", opt, getMessage("err.profiles.msg"));
 199                 }
 200             }
 201         },
 202         new Option(false, "-apionly") {
 203             void process(JdepsTask task, String opt, String arg) {
 204                 task.options.apiOnly = true;
 205             }
 206         },
 207         new Option(false, "-R", "-recursive") {
 208             void process(JdepsTask task, String opt, String arg) {
 209                 task.options.depth = 0;
 210                 // turn off filtering
 211                 task.options.filterSameArchive = false;
 212                 task.options.filterSamePackage = false;
 213             }
 214         },
 215         new Option(false, "-jdkinternals") {
 216             void process(JdepsTask task, String opt, String arg) {
 217                 task.options.findJDKInternals = true;
 218                 task.options.verbose = CLASS;
 219                 if (task.options.includePattern == null) {
 220                     task.options.includePattern = Pattern.compile(".*");
 221                 }
 222             }
 223         },
 224         new Option(false, "-version") {
 225             void process(JdepsTask task, String opt, String arg) {
 226                 task.options.version = true;
 227             }
 228         },
 229         new HiddenOption(false, "-fullversion") {
 230             void process(JdepsTask task, String opt, String arg) {
 231                 task.options.fullVersion = true;
 232             }
 233         },
 234         new HiddenOption(false, "-showlabel") {
 235             void process(JdepsTask task, String opt, String arg) {
 236                 task.options.showLabel = true;
 237             }
 238         },
 239         new HiddenOption(false, "-q", "-quiet") {
 240             void process(JdepsTask task, String opt, String arg) {
 241                 task.options.nowarning = true;
 242             }
 243         },
 244         new HiddenOption(true, "-depth") {
 245             void process(JdepsTask task, String opt, String arg) throws BadArgs {
 246                 try {
 247                     task.options.depth = Integer.parseInt(arg);
 248                 } catch (NumberFormatException e) {
 249                     throw new BadArgs("err.invalid.arg.for.option", opt);
 250                 }
 251             }
 252         },
 253     };
 254 
 255     private static final String PROGNAME = "jdeps";
 256     private final Options options = new Options();
 257     private final List<String> classes = new ArrayList<>();
 258 
 259     private PrintWriter log;
 260     void setLog(PrintWriter out) {
 261         log = out;
 262     }
 263 
 264     /**
 265      * Result codes.
 266      */
 267     static final int EXIT_OK = 0, // Completed with no errors.
 268                      EXIT_ERROR = 1, // Completed but reported errors.
 269                      EXIT_CMDERR = 2, // Bad command-line arguments
 270                      EXIT_SYSERR = 3, // System error or resource exhaustion.
 271                      EXIT_ABNORMAL = 4;// terminated abnormally
 272 
 273     int run(String[] args) {
 274         if (log == null) {
 275             log = new PrintWriter(System.out);
 276         }
 277         try {
 278             handleOptions(args);
 279             if (options.help) {
 280                 showHelp();
 281             }
 282             if (options.version || options.fullVersion) {
 283                 showVersion(options.fullVersion);
 284             }
 285             if (classes.isEmpty() && options.includePattern == null) {
 286                 if (options.help || options.version || options.fullVersion) {
 287                     return EXIT_OK;
 288                 } else {
 289                     showHelp();
 290                     return EXIT_CMDERR;
 291                 }
 292             }
 293             if (options.regex != null && options.packageNames.size() > 0) {
 294                 showHelp();
 295                 return EXIT_CMDERR;
 296             }
 297             if (options.findJDKInternals &&
 298                    (options.regex != null || options.packageNames.size() > 0 || options.showSummary)) {
 299                 showHelp();
 300                 return EXIT_CMDERR;
 301             }
 302             if (options.showSummary && options.verbose != SUMMARY) {
 303                 showHelp();
 304                 return EXIT_CMDERR;
 305             }
 306             boolean ok = run();
 307             return ok ? EXIT_OK : EXIT_ERROR;
 308         } catch (BadArgs e) {
 309             reportError(e.key, e.args);
 310             if (e.showUsage) {
 311                 log.println(getMessage("main.usage.summary", PROGNAME));
 312             }
 313             return EXIT_CMDERR;
 314         } catch (IOException e) {
 315             return EXIT_ABNORMAL;
 316         } finally {
 317             log.flush();
 318         }
 319     }
 320 
 321     private final List<Archive> sourceLocations = new ArrayList<>();
 322     private boolean run() throws IOException {
 323         // parse classfiles and find all dependencies
 324         findDependencies();
 325 
 326         Analyzer analyzer = new Analyzer(options.verbose, new Analyzer.Filter() {
 327             @Override
 328             public boolean accepts(Location origin, Archive originArchive,
 329                                    Location target, Archive targetArchive)
 330             {
 331                 if (options.findJDKInternals) {
 332                     // accepts target that is JDK class but not exported
 333                     return isJDKArchive(targetArchive) &&
 334                               !((JDKArchive) targetArchive).isExported(target.getClassName());
 335                 } else if (options.filterSameArchive) {
 336                     // accepts origin and target that from different archive
 337                     return originArchive != targetArchive;
 338                 }
 339                 return true;
 340             }
 341         });
 342 
 343         // analyze the dependencies
 344         analyzer.run(sourceLocations);
 345 
 346         // output result
 347         if (options.dotOutputDir != null) {
 348             Path dir = Paths.get(options.dotOutputDir);
 349             Files.createDirectories(dir);
 350             generateDotFiles(dir, analyzer);
 351         } else {
 352             printRawOutput(log, analyzer);
 353         }
 354 
 355         if (options.findJDKInternals && !options.nowarning) {
 356             for (Archive source : sourceLocations) {
 357                 if (analyzer.hasDependences(source)) {
 358                     warning("warn.replace.useJDKInternals", getMessage("jdeps.wiki.url"));
 359                     break;
 360                 }
 361             }
 362         }
 363         return true;
 364     }
 365 
 366     private void generateSummaryDotFile(Path dir, Analyzer analyzer) throws IOException {
 367         // If verbose mode (-v or -verbose option),
 368         // the summary.dot file shows package-level dependencies.
 369         Analyzer.Type summaryType =
 370             (options.verbose == PACKAGE || options.verbose == SUMMARY) ? SUMMARY : PACKAGE;
 371         Path summary = dir.resolve("summary.dot");
 372         try (PrintWriter sw = new PrintWriter(Files.newOutputStream(summary));
 373              SummaryDotFile dotfile = new SummaryDotFile(sw, summaryType)) {
 374             for (Archive archive : sourceLocations) {
 375                 if (!archive.isEmpty()) {
 376                     if (options.verbose == PACKAGE || options.verbose == SUMMARY) {
 377                         if (options.showLabel) {
 378                             // build labels listing package-level dependencies
 379                             analyzer.visitDependences(archive, dotfile.labelBuilder(), PACKAGE);
 380                         }
 381                     }
 382                     analyzer.visitDependences(archive, dotfile, summaryType);
 383                 }
 384             }
 385         }
 386     }
 387 
 388     private void generateDotFiles(Path dir, Analyzer analyzer) throws IOException {
 389         // output individual .dot file for each archive
 390         if (options.verbose != SUMMARY) {
 391             for (Archive archive : sourceLocations) {
 392                 if (analyzer.hasDependences(archive)) {
 393                     Path dotfile = dir.resolve(archive.getName() + ".dot");
 394                     try (PrintWriter pw = new PrintWriter(Files.newOutputStream(dotfile));
 395                          DotFileFormatter formatter = new DotFileFormatter(pw, archive)) {
 396                         analyzer.visitDependences(archive, formatter);
 397                     }
 398                 }
 399             }
 400         }
 401         // generate summary dot file
 402         generateSummaryDotFile(dir, analyzer);
 403     }
 404 
 405     private void printRawOutput(PrintWriter writer, Analyzer analyzer) {
 406         RawOutputFormatter depFormatter = new RawOutputFormatter(writer);
 407         RawSummaryFormatter summaryFormatter = new RawSummaryFormatter(writer);
 408         for (Archive archive : sourceLocations) {
 409             if (!archive.isEmpty()) {
 410                 analyzer.visitDependences(archive, summaryFormatter, SUMMARY);
 411                 if (analyzer.hasDependences(archive) && options.verbose != SUMMARY) {
 412                     analyzer.visitDependences(archive, depFormatter);
 413                 }
 414             }
 415         }
 416     }
 417 
 418     private boolean isValidClassName(String name) {
 419         if (!Character.isJavaIdentifierStart(name.charAt(0))) {
 420             return false;
 421         }
 422         for (int i=1; i < name.length(); i++) {
 423             char c = name.charAt(i);
 424             if (c != '.'  && !Character.isJavaIdentifierPart(c)) {
 425                 return false;
 426             }
 427         }
 428         return true;
 429     }
 430 
 431     /*
 432      * Dep Filter configured based on the input jdeps option
 433      * 1. -p and -regex to match target dependencies
 434      * 2. -filter:package to filter out same-package dependencies
 435      *
 436      * This filter is applied when jdeps parses the class files
 437      * and filtered dependencies are not stored in the Analyzer.
 438      *
 439      * -filter:archive is applied later in the Analyzer as the
 440      * containing archive of a target class may not be known until
 441      * the entire archive
 442      */
 443     class DependencyFilter implements Dependency.Filter {
 444         final Dependency.Filter filter;
 445         final Pattern filterPattern;
 446         DependencyFilter() {
 447             if (options.regex != null) {
 448                 this.filter = Dependencies.getRegexFilter(Pattern.compile(options.regex));
 449             } else if (options.packageNames.size() > 0) {
 450                 this.filter = Dependencies.getPackageFilter(options.packageNames, false);
 451             } else {
 452                 this.filter = null;
 453             }
 454 
 455             this.filterPattern =
 456                 options.filterRegex != null ? Pattern.compile(options.filterRegex) : null;
 457         }
 458         @Override
 459         public boolean accepts(Dependency d) {
 460             if (d.getOrigin().equals(d.getTarget())) {
 461                 return false;
 462             }
 463             String pn = d.getTarget().getPackageName();
 464             if (options.filterSamePackage && d.getOrigin().getPackageName().equals(pn)) {
 465                 return false;
 466             }
 467 
 468             if (filterPattern != null && filterPattern.matcher(pn).matches()) {
 469                 return false;
 470             }
 471             return filter != null ? filter.accepts(d) : true;
 472         }
 473     }
 474 
 475     /**
 476      * Tests if the given class matches the pattern given in the -include option
 477      * or if it's a public class if -apionly option is specified
 478      */
 479     private boolean matches(String classname, AccessFlags flags) {
 480         if (options.apiOnly && !flags.is(AccessFlags.ACC_PUBLIC)) {
 481             return false;
 482         } else if (options.includePattern != null) {
 483             return options.includePattern.matcher(classname.replace('/', '.')).matches();
 484         } else {
 485             return true;
 486         }
 487     }
 488 
 489     private void findDependencies() throws IOException {
 490         Dependency.Finder finder =
 491             options.apiOnly ? Dependencies.getAPIFinder(AccessFlags.ACC_PROTECTED)
 492                             : Dependencies.getClassDependencyFinder();
 493         Dependency.Filter filter = new DependencyFilter();
 494 
 495         List<Archive> archives = new ArrayList<>();
 496         Deque<String> roots = new LinkedList<>();
 497         for (String s : classes) {
 498             Path p = Paths.get(s);
 499             if (Files.exists(p)) {
 500                 archives.add(Archive.getInstance(p));
 501             } else {
 502                 if (isValidClassName(s)) {
 503                     roots.add(s);
 504                 } else {
 505                     warning("warn.invalid.arg", s);
 506                 }
 507             }
 508         }
 509         sourceLocations.addAll(archives);
 510 
 511         List<Archive> classpaths = new ArrayList<>(); // for class file lookup
 512         classpaths.addAll(getClassPathArchives(options.classpath));
 513         if (options.includePattern != null) {
 514             archives.addAll(classpaths);
 515         }
 516         classpaths.addAll(PlatformClassPath.getArchives());
 517 
 518         // add all classpath archives to the source locations for reporting
 519         sourceLocations.addAll(classpaths);
 520 
 521         // Work queue of names of classfiles to be searched.
 522         // Entries will be unique, and for classes that do not yet have
 523         // dependencies in the results map.
 524         Deque<String> deque = new LinkedList<>();
 525         Set<String> doneClasses = new HashSet<>();
 526 
 527         // get the immediate dependencies of the input files
 528         for (Archive a : archives) {
 529             for (ClassFile cf : a.reader().getClassFiles()) {
 530                 String classFileName;
 531                 try {
 532                     classFileName = cf.getName();
 533                 } catch (ConstantPoolException e) {
 534                     throw new ClassFileError(e);
 535                 }
 536 
 537                 // tests if this class matches the -include or -apiOnly option if specified
 538                 if (!matches(classFileName, cf.access_flags)) {
 539                     continue;
 540                 }
 541 
 542                 if (!doneClasses.contains(classFileName)) {
 543                     doneClasses.add(classFileName);
 544                 }
 545 
 546                 for (Dependency d : finder.findDependencies(cf)) {
 547                     if (filter.accepts(d)) {
 548                         String cn = d.getTarget().getName();
 549                         if (!doneClasses.contains(cn) && !deque.contains(cn)) {
 550                             deque.add(cn);
 551                         }
 552                         a.addClass(d.getOrigin(), d.getTarget());
 553                     }
 554                 }
 555                 for (String name : a.reader().skippedEntries()) {
 556                     warning("warn.skipped.entry", name, a.getPathName());
 557                 }
 558             }
 559         }
 560 
 561         // add Archive for looking up classes from the classpath
 562         // for transitive dependency analysis
 563         Deque<String> unresolved = roots;
 564         int depth = options.depth > 0 ? options.depth : Integer.MAX_VALUE;
 565         do {
 566             String name;
 567             while ((name = unresolved.poll()) != null) {
 568                 if (doneClasses.contains(name)) {
 569                     continue;
 570                 }
 571                 ClassFile cf = null;
 572                 for (Archive a : classpaths) {
 573                     cf = a.reader().getClassFile(name);
 574                     if (cf != null) {
 575                         String classFileName;
 576                         try {
 577                             classFileName = cf.getName();
 578                         } catch (ConstantPoolException e) {
 579                             throw new ClassFileError(e);
 580                         }
 581                         if (!doneClasses.contains(classFileName)) {
 582                             // if name is a fully-qualified class name specified
 583                             // from command-line, this class might already be parsed
 584                             doneClasses.add(classFileName);
 585                             // process @jdk.Exported for JDK classes
 586                             if (isJDKArchive(a)) {
 587                                 ((JDKArchive)a).processJdkExported(cf);
 588                             }
 589                             for (Dependency d : finder.findDependencies(cf)) {
 590                                 if (depth == 0) {
 591                                     // ignore the dependency
 592                                     a.addClass(d.getOrigin());
 593                                     break;
 594                                 } else if (filter.accepts(d)) {
 595                                     a.addClass(d.getOrigin(), d.getTarget());
 596                                     String cn = d.getTarget().getName();
 597                                     if (!doneClasses.contains(cn) && !deque.contains(cn)) {
 598                                         deque.add(cn);
 599                                     }
 600                                 }
 601                             }
 602                         }
 603                         break;
 604                     }
 605                 }
 606                 if (cf == null) {
 607                     doneClasses.add(name);
 608                 }
 609             }
 610             unresolved = deque;
 611             deque = new LinkedList<>();
 612         } while (!unresolved.isEmpty() && depth-- > 0);
 613     }
 614 
 615     public void handleOptions(String[] args) throws BadArgs {
 616         // process options
 617         for (int i=0; i < args.length; i++) {
 618             if (args[i].charAt(0) == '-') {
 619                 String name = args[i];
 620                 Option option = getOption(name);
 621                 String param = null;
 622                 if (option.hasArg) {
 623                     if (name.startsWith("-") && name.indexOf('=') > 0) {
 624                         param = name.substring(name.indexOf('=') + 1, name.length());
 625                     } else if (i + 1 < args.length) {
 626                         param = args[++i];
 627                     }
 628                     if (param == null || param.isEmpty() || param.charAt(0) == '-') {
 629                         throw new BadArgs("err.missing.arg", name).showUsage(true);
 630                     }
 631                 }
 632                 option.process(this, name, param);
 633                 if (option.ignoreRest()) {
 634                     i = args.length;
 635                 }
 636             } else {
 637                 // process rest of the input arguments
 638                 for (; i < args.length; i++) {
 639                     String name = args[i];
 640                     if (name.charAt(0) == '-') {
 641                         throw new BadArgs("err.option.after.class", name).showUsage(true);
 642                     }
 643                     classes.add(name);
 644                 }
 645             }
 646         }
 647     }
 648 
 649     private Option getOption(String name) throws BadArgs {
 650         for (Option o : recognizedOptions) {
 651             if (o.matches(name)) {
 652                 return o;
 653             }
 654         }
 655         throw new BadArgs("err.unknown.option", name).showUsage(true);
 656     }
 657 
 658     private void reportError(String key, Object... args) {
 659         log.println(getMessage("error.prefix") + " " + getMessage(key, args));
 660     }
 661 
 662     private void warning(String key, Object... args) {
 663         log.println(getMessage("warn.prefix") + " " + getMessage(key, args));
 664     }
 665 
 666     private void showHelp() {
 667         log.println(getMessage("main.usage", PROGNAME));
 668         for (Option o : recognizedOptions) {
 669             String name = o.aliases[0].substring(1); // there must always be at least one name
 670             name = name.charAt(0) == '-' ? name.substring(1) : name;
 671             if (o.isHidden() || name.equals("h") || name.startsWith("filter:")) {
 672                 continue;
 673             }
 674             log.println(getMessage("main.opt." + name));
 675         }
 676     }
 677 
 678     private void showVersion(boolean full) {
 679         log.println(version(full ? "full" : "release"));
 680     }
 681 
 682     private String version(String key) {
 683         // key=version:  mm.nn.oo[-milestone]
 684         // key=full:     mm.mm.oo[-milestone]-build
 685         if (ResourceBundleHelper.versionRB == null) {
 686             return System.getProperty("java.version");
 687         }
 688         try {
 689             return ResourceBundleHelper.versionRB.getString(key);
 690         } catch (MissingResourceException e) {
 691             return getMessage("version.unknown", System.getProperty("java.version"));
 692         }
 693     }
 694 
 695     static String getMessage(String key, Object... args) {
 696         try {
 697             return MessageFormat.format(ResourceBundleHelper.bundle.getString(key), args);
 698         } catch (MissingResourceException e) {
 699             throw new InternalError("Missing message: " + key);
 700         }
 701     }
 702 
 703     private static class Options {
 704         boolean help;
 705         boolean version;
 706         boolean fullVersion;
 707         boolean showProfile;
 708         boolean showSummary;
 709         boolean apiOnly;
 710         boolean showLabel;
 711         boolean findJDKInternals;
 712         boolean nowarning;
 713         // default is to show package-level dependencies
 714         // and filter references from same package
 715         Analyzer.Type verbose = PACKAGE;
 716         boolean filterSamePackage = true;
 717         boolean filterSameArchive = false;
 718         String filterRegex;
 719         String dotOutputDir;
 720         String classpath = "";
 721         int depth = 1;
 722         Set<String> packageNames = new HashSet<>();
 723         String regex;             // apply to the dependences
 724         Pattern includePattern;   // apply to classes
 725     }
 726     private static class ResourceBundleHelper {
 727         static final ResourceBundle versionRB;
 728         static final ResourceBundle bundle;
 729         static final ResourceBundle jdkinternals;
 730 
 731         static {
 732             Locale locale = Locale.getDefault();
 733             try {
 734                 bundle = ResourceBundle.getBundle("com.sun.tools.jdeps.resources.jdeps", locale);
 735             } catch (MissingResourceException e) {
 736                 throw new InternalError("Cannot find jdeps resource bundle for locale " + locale);
 737             }
 738             try {
 739                 versionRB = ResourceBundle.getBundle("com.sun.tools.jdeps.resources.version");
 740             } catch (MissingResourceException e) {
 741                 throw new InternalError("version.resource.missing");
 742             }
 743             try {
 744                 jdkinternals = ResourceBundle.getBundle("com.sun.tools.jdeps.resources.jdkinternals");
 745             } catch (MissingResourceException e) {
 746                 throw new InternalError("Cannot find jdkinternals resource bundle");
 747             }
 748         }
 749     }
 750 
 751     private List<Archive> getClassPathArchives(String paths) throws IOException {
 752         List<Archive> result = new ArrayList<>();
 753         if (paths.isEmpty()) {
 754             return result;
 755         }
 756         for (String p : paths.split(File.pathSeparator)) {
 757             if (p.length() > 0) {
 758                 List<Path> files = new ArrayList<>();
 759                 // wildcard to parse all JAR files e.g. -classpath dir/*
 760                 int i = p.lastIndexOf(".*");
 761                 if (i > 0) {
 762                     Path dir = Paths.get(p.substring(0, i));
 763                     try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir, "*.jar")) {
 764                         for (Path entry : stream) {
 765                             files.add(entry);
 766                         }
 767                     }
 768                 } else {
 769                     files.add(Paths.get(p));
 770                 }
 771                 for (Path f : files) {
 772                     if (Files.exists(f)) {
 773                         result.add(Archive.getInstance(f));
 774                     }
 775                 }
 776             }
 777         }
 778         return result;
 779     }
 780 
 781     class RawOutputFormatter implements Analyzer.Visitor {
 782         private final PrintWriter writer;
 783         private String pkg = "";
 784         RawOutputFormatter(PrintWriter writer) {
 785             this.writer = writer;
 786         }
 787         @Override
 788         public void visitDependence(String origin, Archive originArchive,
 789                                     String target, Archive targetArchive) {
 790             String tag = toTag(target, targetArchive);
 791             if (options.verbose == VERBOSE) {
 792                 writer.format("   %-50s -> %-50s %s%n", origin, target, tag);
 793             } else {
 794                 if (!origin.equals(pkg)) {
 795                     pkg = origin;
 796                     writer.format("   %s (%s)%n", origin, originArchive.getName());
 797                 }
 798                 writer.format("      -> %-50s %s%n", target, tag);
 799             }
 800         }
 801     }
 802 
 803     class RawSummaryFormatter implements Analyzer.Visitor {
 804         private final PrintWriter writer;
 805         RawSummaryFormatter(PrintWriter writer) {
 806             this.writer = writer;
 807         }
 808         @Override
 809         public void visitDependence(String origin, Archive originArchive,
 810                                     String target, Archive targetArchive) {
 811             writer.format("%s -> %s", originArchive.getName(), targetArchive.getPathName());
 812             if (options.showProfile && JDKArchive.isProfileArchive(targetArchive)) {
 813                 writer.format(" (%s)", target);
 814             }
 815             writer.format("%n");
 816         }
 817     }
 818 
 819     class DotFileFormatter implements Analyzer.Visitor, AutoCloseable {
 820         private final PrintWriter writer;
 821         private final String name;
 822         DotFileFormatter(PrintWriter writer, Archive archive) {
 823             this.writer = writer;
 824             this.name = archive.getName();
 825             writer.format("digraph \"%s\" {%n", name);
 826             writer.format("    // Path: %s%n", archive.getPathName());
 827         }
 828 
 829         @Override
 830         public void close() {
 831             writer.println("}");
 832         }
 833 
 834         @Override
 835         public void visitDependence(String origin, Archive originArchive,
 836                                     String target, Archive targetArchive) {
 837             String tag = toTag(target, targetArchive);
 838             writer.format("   %-50s -> \"%s\";%n",
 839                           String.format("\"%s\"", origin),
 840                           tag.isEmpty() ? target
 841                                         : String.format("%s (%s)", target, tag));
 842         }
 843     }
 844 
 845     class SummaryDotFile implements Analyzer.Visitor, AutoCloseable {
 846         private final PrintWriter writer;
 847         private final Analyzer.Type type;
 848         private final Map<Archive, Map<Archive,StringBuilder>> edges = new HashMap<>();
 849         SummaryDotFile(PrintWriter writer, Analyzer.Type type) {
 850             this.writer = writer;
 851             this.type = type;
 852             writer.format("digraph \"summary\" {%n");
 853         }
 854 
 855         @Override
 856         public void close() {
 857             writer.println("}");
 858         }
 859 
 860         @Override
 861         public void visitDependence(String origin, Archive originArchive,
 862                                     String target, Archive targetArchive) {
 863             String targetName = type == PACKAGE ? target : targetArchive.getName();
 864             if (type == PACKAGE) {
 865                 String tag = toTag(target, targetArchive, type);
 866                 if (!tag.isEmpty())
 867                     targetName += " (" + tag + ")";
 868             } else if (options.showProfile && JDKArchive.isProfileArchive(targetArchive)) {
 869                 targetName += " (" + target + ")";
 870             }
 871             String label = getLabel(originArchive, targetArchive);
 872             writer.format("  %-50s -> \"%s\"%s;%n",
 873                           String.format("\"%s\"", origin), targetName, label);
 874         }
 875 
 876         String getLabel(Archive origin, Archive target) {
 877             if (edges.isEmpty())
 878                 return "";
 879 
 880             StringBuilder label = edges.get(origin).get(target);
 881             return label == null ? "" : String.format(" [label=\"%s\",fontsize=9]", label.toString());
 882         }
 883 
 884         Analyzer.Visitor labelBuilder() {
 885             // show the package-level dependencies as labels in the dot graph
 886             return new Analyzer.Visitor() {
 887                 @Override
 888                 public void visitDependence(String origin, Archive originArchive, String target, Archive targetArchive) {
 889                     edges.putIfAbsent(originArchive, new HashMap<>());
 890                     edges.get(originArchive).putIfAbsent(targetArchive, new StringBuilder());
 891                     StringBuilder sb = edges.get(originArchive).get(targetArchive);
 892                     String tag = toTag(target, targetArchive, PACKAGE);
 893                     addLabel(sb, origin, target, tag);
 894                 }
 895 
 896                 void addLabel(StringBuilder label, String origin, String target, String tag) {
 897                     label.append(origin).append(" -> ").append(target);
 898                     if (!tag.isEmpty()) {
 899                         label.append(" (" + tag + ")");
 900                     }
 901                     label.append("\\n");
 902                 }
 903             };
 904         }
 905     }
 906 
 907     /**
 908      * Test if the given archive is part of the JDK
 909      */
 910     private boolean isJDKArchive(Archive archive) {
 911         return JDKArchive.class.isInstance(archive);
 912     }
 913 
 914     /**
 915      * If the given archive is JDK archive, this method returns the profile name
 916      * only if -profile option is specified; it accesses a private JDK API and
 917      * the returned value will have "JDK internal API" prefix
 918      *
 919      * For non-JDK archives, this method returns the file name of the archive.
 920      */
 921     private String toTag(String name, Archive source, Analyzer.Type type) {
 922         if (!isJDKArchive(source)) {
 923             return source.getName();
 924         }
 925 
 926         JDKArchive jdk = (JDKArchive)source;
 927         boolean isExported = false;
 928         if (type == CLASS || type == VERBOSE) {
 929             isExported = jdk.isExported(name);
 930         } else {
 931             isExported = jdk.isExportedPackage(name);
 932         }
 933         Profile p = getProfile(name, type);
 934         if (isExported) {
 935             // exported API
 936             return options.showProfile && p != null ? p.profileName() : "";
 937         } else {
 938             String tag = source.getName();
 939             if (options.findJDKInternals) {
 940                 String msg = replacementFor(name);
 941                 tag = msg.isEmpty() ? tag : msg;
 942             }
 943             return "JDK internal API (" + tag + ")";
 944         }
 945     }
 946 
 947     private String toTag(String name, Archive source) {
 948         return toTag(name, source, options.verbose);
 949     }
 950 
 951     private Profile getProfile(String name, Analyzer.Type type) {
 952         String pn = name;
 953         if (type == CLASS || type == VERBOSE) {
 954             int i = name.lastIndexOf('.');
 955             pn = i > 0 ? name.substring(0, i) : "";
 956         }
 957         return Profile.getProfile(pn);
 958     }
 959 
 960     /**
 961      * Returns the recommended replacement API for the given classname;
 962      * or return empty string if replacement API is not known.
 963      */
 964     private String replacementFor(String cn) {
 965         String name = cn;
 966         String value = "";
 967         while (value.isEmpty() && name != null) {
 968             try {
 969                 value = ResourceBundleHelper.jdkinternals.getString(name);
 970             } catch (MissingResourceException e) {
 971                 // go up one subpackage level
 972                 int i = name.lastIndexOf('.');
 973                 name = i > 0 ? name.substring(0, i) : null;
 974             }
 975         }
 976         return value;
 977     };
 978 }