1 /*
   2  * Copyright (c) 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.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  */
  23 
  24 /**
  25  * @test
  26  * @summary Validate and test -?, -h and --help flags. All tools in the jdk
  27  *          should take the same flags to display the help message. These
  28  *          flags should be documented in the printed help message. The
  29  *          tool should quit without error code after displaying the
  30  *          help message (if there  is no other problem with the command
  31  *          line).
  32  *          Also check that tools that used to accept -help still do so,
  33  *          but do not document it. Test that tools that never accepted
  34  *          -help don't do so in future. I.e., check that the tool returns
  35  *          with the same return code as called with an invalid flag, and
  36  *          does not print anything containing '-help' in that case.
  37  * @compile HelpFlagsTest.java
  38  * @run main HelpFlagsTest
  39  */
  40 
  41 import java.io.File;
  42 import java.io.FileFilter;
  43 import java.util.Map;
  44 import java.util.ArrayList;
  45 import java.util.HashMap;
  46 import java.util.List;
  47 import java.util.HashSet;
  48 import java.util.Set;
  49 
  50 
  51 public class HelpFlagsTest extends TestHelper {
  52 
  53 
  54     // Tools that should not be tested because a usage message is pointless.
  55     static final String[] TOOLS_NOT_TO_TEST = {
  56         "appletviewer",     // deprecated, don't test
  57         "jaccessinspector", // gui, don't test, win only
  58         "jaccesswalker",    // gui, don't test, win only
  59         "jconsole",         // gui, don't test
  60         "servertool",       // none. Shell, don't test.
  61         "javaw",            // don't test, win only
  62         // The flags of these tools need to be fixed in Java EE.
  63         // The tools are deprecated for removal in Java SE. Don't test.
  64         "idlj",
  65         "orbd",
  66         "schemagen",
  67         "tnameserv",
  68         "wsgen",
  69         "wsimport",
  70         "xjc",
  71         // These shall have a help message that resembles that of 
  72         // MIT's tools. Thus -?, -h and --help are supported, but not
  73         // mentioned in the help text.
  74         "kinit",
  75         "klist",
  76         "ktab"
  77     };
  78 
  79     // Lists which tools support which flags.
  80     private static class ToolHelpSpec {
  81         String toolname;
  82 
  83         // How the flags supposed to be supported are handled.
  84         //
  85         // These flags are supported, i.e.,
  86         // * the tool accepts the flag
  87         // * the tool prints a help message if the flag is specified
  88         // * this help message lists the flag
  89         // * the tool exits with exit code '0'.
  90         boolean supports_q;
  91         boolean supports_h;
  92         boolean supports_help;
  93         // One tool returns with exit code != '0'.
  94         int exitcode_of_help;
  95 
  96         // How legacy -help is handled.
  97         //
  98         // Tools that so far support -help should still do so, but
  99         // not print documentation about it. Tools that do not
 100         // support -help should not do so in future.
 101         //
 102         // The tools accepts legacy -help. -help should not be
 103         // documented in the usage message.
 104         boolean supports_legacy_help;
 105         // Java itself documents -help. -help prints to stderr,
 106         // while --help prints to stdout. Leave as is.
 107         boolean documents_legacy_help;
 108 
 109         // The exit code of the tool if an invalid argument is passed to it.
 110         // An exit code != 0 would be expected, but not all tools handle it
 111         // that way.
 112         int exitcode_of_wrong_flag;
 113 
 114         // Some tools accept the invalid argument and thus hang the test.
 115         // Don't execute these with the wrong flags.
 116         // This actually should be considered a bug in the corresponding tool.
 117         boolean dont_execute_with_wrong_flags;
 118 
 119         ToolHelpSpec(String n, int q, int h, int hp, int ex1, int l, int dl, int ex2, int hangs) {
 120             toolname = n;
 121             supports_q    = ( q  == 1 ? true : false );
 122             supports_h    = ( h  == 1 ? true : false );
 123             supports_help = ( hp == 1 ? true : false );
 124             exitcode_of_help = ex1;
 125 
 126             supports_legacy_help   = (  l == 1 ? true : false );
 127             documents_legacy_help  = ( dl == 1 ? true : false );
 128             exitcode_of_wrong_flag = ex2;
 129 
 130             dont_execute_with_wrong_flags = ( hangs == 1 ? true : false );
 131         }
 132     }
 133 
 134     static ToolHelpSpec[] jdkTools = {
 135         //               name          -?   -h --help exitcode   -help -help  exitcode  Don't
 136         //                                            of help          docu   of wrong  test
 137         //                                                             mented flag      inv flag
 138         new ToolHelpSpec("jabswitch",   0,   0,   0,   0,         0,    0,     0,       0),   // /?, prints help message anyways, win only
 139         new ToolHelpSpec("jaotc",       1,   1,   1,   0,         0,    0,     2,       0),   // -?, -h, --help
 140         new ToolHelpSpec("jar",         1,   1,   1,   0,         0,    0,     1,       0),   // -?, -h, --help
 141         new ToolHelpSpec("jarsigner",   1,   1,   1,   0,         1,    0,     1,       0),   // -?, -h, --help, -help accepted but not documented.
 142         new ToolHelpSpec("java",        1,   1,   1,   0,         1,    1,     1,       0),   // -?, -h, --help -help, Documents -help
 143         new ToolHelpSpec("javac",       1,   0,   1,   0,         1,    1,     2,       0),   // -?,     --help -help, Documents -help, -h is already taken for "native header output directory".
 144         new ToolHelpSpec("javadoc",     1,   1,   1,   0,         0,    0,     1,       0),   // -?, -h, --help
 145         new ToolHelpSpec("javah",       1,   1,   1,   0,         1,    0,     1,       0),   // -?, -h, --help, -help accepted but not documented.
 146         new ToolHelpSpec("javap",       1,   1,   1,   0,         1,    0,     2,       0),   // -?, -h, --help, -help accepted but not documented.
 147         new ToolHelpSpec("javaw",       1,   1,   1,   0,         1,    1,     1,       0),   // -?, -h, --help -help, win only
 148         new ToolHelpSpec("jcmd",        1,   1,   1,   0,         1,    0,     1,       0),   // -?, -h, --help, -help accepted but not documented.
 149         new ToolHelpSpec("jdb",         1,   1,   1,   0,         1,    0,     0,       0),   // -?, -h, --help, -help accepted but not documented.
 150         new ToolHelpSpec("jdeprscan",   1,   1,   1,   0,         0,    0,     1,       0),   // -?, -h, --help
 151         new ToolHelpSpec("jdeps",       1,   1,   1,   0,         1,    0,     2,       0),   // -?, -h, --help, -help accepted but not documented.
 152         new ToolHelpSpec("jhsdb",       0,   0,   0,   0,         0,    0,     0,       0),   // none, prints help message anyways.
 153         new ToolHelpSpec("jimage",      1,   1,   1,   0,         0,    0,     2,       0),   // -?, -h, --help
 154         new ToolHelpSpec("jinfo",       1,   1,   1,   0,         1,    0,     1,       0),   // -?, -h, --help, -help accepted but not documented.
 155         new ToolHelpSpec("jjs",         0,   1,   1, 100,         0,    0,   100,       0),   //     -h, --help, return code 100
 156         new ToolHelpSpec("jlink",       1,   1,   1,   0,         0,    0,     2,       0),   // -?, -h, --help
 157         new ToolHelpSpec("jmap",        1,   1,   1,   0,         1,    0,     1,       0),   // -?, -h, --help, -help accepted but not documented.
 158         new ToolHelpSpec("jmod",        1,   1,   1,   0,         1,    0,     2,       0),   // -?, -h, --help, -help accepted but not documented.
 159         new ToolHelpSpec("jps",         1,   1,   1,   0,         1,    0,     1,       0),   // -?, -h, --help, -help accepted but not documented.
 160         new ToolHelpSpec("jrunscript",  1,   1,   1,   0,         1,    0,     7,       0),   // -?, -h, --help, -help accepted but not documented.
 161         new ToolHelpSpec("jshell",      1,   1,   1,   0,         1,    0,     1,       0),   // -?, -h, --help, -help accepted but not documented.
 162         new ToolHelpSpec("jstack",      1,   1,   1,   0,         1,    0,     1,       0),   // -?, -h, --help, -help accepted but not documented.
 163         new ToolHelpSpec("jstat",       1,   1,   1,   0,         1,    0,     1,       0),   // -?, -h, --help, -help accepted but not documented.
 164         new ToolHelpSpec("jstatd",      1,   1,   1,   0,         0,    0,     1,       0),   // -?, -h, --help
 165         new ToolHelpSpec("keytool",     1,   1,   1,   0,         1,    0,     1,       0),   // none, prints help message anyways.
 166         new ToolHelpSpec("pack200",     1,   1,   1,   0,         1,    0,     2,       0),   // -?, -h, --help, -help accepted but not documented.
 167         new ToolHelpSpec("policytool",  0,   0,   0,   0,         0,    0,     0,       0),   // none, prints help message anyways.
 168         new ToolHelpSpec("rmic",        0,   0,   0,   0,         0,    0,     1,       0),   // none, pirnts help message anyways.
 169         new ToolHelpSpec("rmid",        0,   0,   0,   0,         0,    0,     1,       0),   // none, prints help message anyways.
 170         new ToolHelpSpec("rmiregistry", 0,   0,   0,   0,         0,    0,     1,       0),   // none, prints help message anyways.
 171         new ToolHelpSpec("serialver",   0,   0,   0,   0,         0,    0,     1,       0),   // none, prints help message anyways.
 172         new ToolHelpSpec("unpack200",   1,   1,   1,   0,         1,    0,     2,       0),   // -?, -h, --help, -help accepted but not documented.
 173     };
 174 
 175 
 176     // Returns true if the file is not a tool.
 177     static boolean notATool(String file) {
 178         file = file.toLowerCase();
 179         if (file.endsWith(".dll") ||
 180             file.endsWith(".map") ||
 181             file.endsWith(".pdb") ||
 182             file.equals("server")) {  // server subdir on windows.
 183             return true;
 184         }
 185         return false;
 186     }
 187 
 188     // Returns true if tool is listed in TOOLS_NOT_TO_TEST.
 189     static boolean dontTestTool(String tool) {
 190         tool = tool.toLowerCase();
 191         for (String x : TOOLS_NOT_TO_TEST) {
 192             if (tool.toLowerCase().startsWith(x)) return true;
 193         }
 194         return false;
 195     }
 196 
 197     // Returns corresponding object from jdkTools array.
 198     static ToolHelpSpec getToolHelpSpec(String tool) {
 199         for (ToolHelpSpec x : jdkTools) {
 200             if (tool.toLowerCase().equals(x.toolname) ||
 201                 tool.toLowerCase().equals(x.toolname + ".exe")) return x;
 202         }
 203         return null;
 204     }
 205 
 206     // Check whether 'flag' appears in 'line' as a word of itself. I must not
 207     // be a substring of a word, as then similar flags might be matched.
 208     // E.g.: --help matches in the documentation of --help-extra.
 209     // This works only with english locale, as some tools have translated
 210     // usage messages.
 211     static boolean findFlagInLine(String line, String flag) {
 212         if (line.contains(flag) &&
 213             !line.contains("nknown") &&                       // Some tools say 'Unknown option "<flag>"',
 214             !line.contains("invalid flag") &&                 // 'invalid flag: <flag>'
 215             !line.contains("invalid option") &&               // or 'invalid option: <flag>'. Skip that.
 216             !line.contains("FileNotFoundException: -help") && // Special case for idlj.
 217             !line.contains("-h requires an argument") &&      // Special case for javac.
 218             !line.contains("port argument,")) {               // Special case for rmiregistry.
 219             // There might be several appearances of 'flag' in
 220             // 'line'. (-h as substring of --help).
 221             int flagLen = flag.length();
 222             int lineLen = line.length();
 223             for (int i = line.indexOf(flag); i >= 0; i = line.indexOf(flag, i+1)) {
 224                 // There should be a space before 'flag' in 'line', or it's right at the beginning.
 225                 if (i > 0 &&
 226                     line.charAt(i-1) != ' ' &&
 227                     line.charAt(i-1) != '[' &&  // jarsigner
 228                     line.charAt(i-1) != '|' &&  // jstatd
 229                     line.charAt(i-1) != '\t') { // jjs
 230                     continue;
 231                 }
 232                 // There should be a space or comma after 'flag' in 'line', or it's just at the end.
 233                 int posAfter = i + flagLen;
 234                 if (posAfter < lineLen &&
 235                     line.charAt(posAfter) != ' ' &&
 236                     line.charAt(posAfter) != ',' &&
 237                     line.charAt(posAfter) != '[' && // jar
 238                     line.charAt(posAfter) != ']' && // jarsigner
 239                     line.charAt(posAfter) != '|' && // jstatd
 240                     line.charAt(posAfter) != ':' && // jps
 241                     line.charAt(posAfter) != '"') { // keytool
 242                     continue;
 243                 }
 244                 return true;
 245             }
 246         }
 247         return false;
 248     }
 249 
 250     static TestResult runToolWithFlag(File f, String flag) {
 251         String x = f.getAbsolutePath();
 252         TestResult tr = doExec(x, flag);
 253         System.out.println("Testing " + f.getName());
 254         System.out.println("#> " + x + " " + flag);
 255         tr.testOutput.forEach(System.out::println);
 256         System.out.println("#> echo $?");
 257         System.out.println(tr.exitValue);
 258 
 259         return tr;
 260     }
 261 
 262     // Checks whether tool supports flag 'flag' and documents it
 263     // in the help message.
 264     static String testTool(File f, String flag, int exitcode) {
 265         String result = "";
 266         TestResult tr = runToolWithFlag(f, flag);
 267 
 268         // Check that the tool accepted the flag.
 269         if (exitcode == 0 && !tr.isOK()) {
 270             System.out.println("failed");
 271             result = "failed: " + f.getName() + " " + flag + " has exit code " + tr.exitValue + ".\n";
 272         }
 273 
 274         // Check there is a help message listing the flag.
 275         boolean foundFlag = false;
 276         for (String y : tr.testOutput) {
 277             if (!foundFlag && findFlagInLine(y, flag)) { // javac
 278                 foundFlag = true;
 279                 System.out.println("Found documentation of '" + flag + "': '" + y.trim() +"'");
 280             }
 281         }
 282         if (!foundFlag) {
 283             result += "failed: " + f.getName() + " does not document " +
 284                 flag + " in help message.\n";
 285         }
 286         if (!result.isEmpty()) { System.out.println(result); }
 287         return result;
 288     }
 289 
 290     // Test the tool supports legacy option -help, but does
 291     // not document it.
 292     static String testLegacyFlag(File f, int exitcode) {
 293         String result = "";
 294         TestResult tr = runToolWithFlag(f, "-help");
 295 
 296         // Check that the tool accepted the flag.
 297         if (exitcode == 0 && !tr.isOK()) {
 298             System.out.println("failed");
 299             result = "failed: " + f.getName() + " -help has exit code " + tr.exitValue + ".\n";
 300         }
 301 
 302 
 303         // Check there is _no_ documentation of -help.
 304         boolean foundFlag = false;
 305         for (String y : tr.testOutput) {
 306             if (!foundFlag && findFlagInLine(y, "-help")) {  // javac
 307                 foundFlag = true;
 308                 System.out.println("Found documentation of '-help': '" + y.trim() +"'");
 309             }
 310         }
 311         if (foundFlag) {
 312             result += "failed: " + f.getName() + " does document -help " +
 313                 "in help message. This legacy flag should not be documented.\n";
 314         }
 315         if (!result.isEmpty()) { System.out.println(result); }
 316         return result;
 317     }
 318 
 319     // Test that the tool exits with the exit code expected for
 320     // invalid flags. In general, one would expect this to be != 0,
 321     // but currently a row of tools exit with 0 in this case.
 322     // The output should not ask to get help with flag '-help'.
 323     static String testInvalidFlag(File f, String flag, int exitcode) {
 324         String result = "";
 325         TestResult tr = runToolWithFlag(f, flag);
 326 
 327         // Check that the tool did exit with the expected return code.
 328         if (!((exitcode == tr.exitValue) ||
 329               // Windows reports -1 where unix reports 255.
 330               (tr.exitValue < 0 && exitcode == tr.exitValue + 256))) {
 331             System.out.println("failed");
 332             result = "failed: " + f.getName() + " " + flag + " should not be " +
 333                      "accepted. But it has exit code " + tr.exitValue + ".\n";
 334         }
 335 
 336         // Check there is _no_ documentation of -help.
 337         boolean foundFlag = false;
 338         for (String y : tr.testOutput) {
 339             if (!foundFlag && findFlagInLine(y, "-help")) {  // javac
 340                 foundFlag = true;
 341                 System.out.println("Found documentation of '-help': '" + y.trim() +"'");
 342             }
 343         }
 344         if (foundFlag) {
 345             result += "failed: " + f.getName() + " does document -help " +
 346                 "in error message. This legacy flag should not be documented.\n";
 347         }
 348         if (!result.isEmpty()) { System.out.println(result); }
 349         return result;
 350     }
 351 
 352     public static void main(String[] args) {
 353         String errorMessage = "";
 354 
 355         for (File f : new File(JAVA_BIN).listFiles()) {
 356             String toolName = f.getName();
 357 
 358             if (notATool(toolName)) {
 359                 continue;
 360             }
 361             if (dontTestTool(toolName)) {
 362                 System.out.println("Skipping test of tool " + toolName +
 363                                    ". Tool has no help message.");
 364                 continue;
 365             }
 366 
 367             ToolHelpSpec tool = getToolHelpSpec(toolName);
 368             if (tool == null) {
 369                 errorMessage += "Tool " + toolName + " not covered by this test. " +
 370                     "Add specification to jdkTools array!\n";
 371                 continue;
 372             }
 373 
 374             // Test for help flags to be supported.
 375             if (tool.supports_q == true) {
 376                 errorMessage += testTool(f, "-?", tool.exitcode_of_help);
 377             } else {
 378                 System.out.println("Skip " + tool.toolname + ". It does not support -?.");
 379             }
 380             if (tool.supports_h == true) {
 381                 errorMessage += testTool(f, "-h", tool.exitcode_of_help);
 382             } else {
 383                 System.out.println("Skip " + tool.toolname + ". It does not support -h.");
 384             }
 385             if (tool.supports_help == true) {
 386                 errorMessage += testTool(f, "--help", tool.exitcode_of_help);
 387             } else {
 388                 System.out.println("Skip " + tool.toolname + ". It does not support --help.");
 389             }
 390 
 391             // Check that the return code listing in jdkTools[] is
 392             // correct for an invalid flag.
 393             if (!tool.dont_execute_with_wrong_flags) {
 394                 errorMessage += testInvalidFlag(f, "-asdfxgr", tool.exitcode_of_wrong_flag);
 395             }
 396 
 397             // Test for legacy -help flag.
 398             if (!tool.documents_legacy_help) {
 399                 if (tool.supports_legacy_help == true) {
 400                     errorMessage += testLegacyFlag(f, tool.exitcode_of_help);
 401                 } else {
 402                     if (!tool.dont_execute_with_wrong_flags) {
 403                         errorMessage += testInvalidFlag(f, "-help", tool.exitcode_of_wrong_flag);
 404                     }
 405                 }
 406             }
 407         }
 408 
 409         if (errorMessage.isEmpty()) {
 410             System.out.println("All help string tests: PASS");
 411         } else {
 412             throw new AssertionError("HelpFlagsTest failed:\n" + errorMessage);
 413         }
 414     }
 415 }