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