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