1 /*
   2  * Copyright (c) 2018, 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         // 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         // Oracle proprietary tools without help message.
  78         "javacpl",
  79         "jmc",
  80         "jweblauncher",
  81         "jcontrol",
  82         "ssvagent"
  83     };
  84 
  85     // Lists which tools support which flags.
  86     private static class ToolHelpSpec {
  87         String toolname;
  88 
  89         // How the flags supposed to be supported are handled.
  90         //
  91         // These flags are supported, i.e.,
  92         // * the tool accepts the flag
  93         // * the tool prints a help message if the flag is specified
  94         // * this help message lists the flag
  95         // * the tool exits with exit code '0'.
  96         boolean supportsQuestionMark;
  97         boolean supportsH;
  98         boolean supportsHelp;
  99 
 100         // One tool returns with exit code != '0'.
 101         int exitcodeOfHelp;
 102 
 103         // How legacy -help is handled.
 104         //
 105         // Tools that so far support -help should still do so, but
 106         // not print documentation about it. Tools that do not
 107         // support -help should not do so in future.
 108         //
 109         // The tools accepts legacy -help. -help should not be
 110         // documented in the usage message.
 111         boolean supportsLegacyHelp;
 112 
 113         // Java itself documents -help. -help prints to stderr,
 114         // while --help prints to stdout. Leave as is.
 115         boolean documentsLegacyHelp;
 116 
 117         // The exit code of the tool if an invalid argument is passed to it.
 118         // An exit code != 0 would be expected, but not all tools handle it
 119         // that way.
 120         int exitcodeOfWrongFlag;
 121 
 122         ToolHelpSpec(String n, int q, int h, int hp, int ex1, int l, int dl, int ex2) {
 123             toolname = n;
 124             supportsQuestionMark = ( q  == 1 ? true : false );
 125             supportsH            = ( h  == 1 ? true : false );
 126             supportsHelp         = ( hp == 1 ? true : false );
 127             exitcodeOfHelp       = ex1;
 128 
 129             supportsLegacyHelp   = (  l == 1 ? true : false );
 130             documentsLegacyHelp  = ( dl == 1 ? true : false );
 131             exitcodeOfWrongFlag  = ex2;
 132         }
 133     }
 134 
 135     static ToolHelpSpec[] jdkTools = {
 136         //               name          -?   -h --help exitcode   -help -help  exitcode
 137         //                                            of help          docu   of wrong
 138         //                                                             mented flag
 139         new ToolHelpSpec("jabswitch",   0,   0,   0,   0,         0,    0,     0),     // /?, prints help message anyways, win only
 140         new ToolHelpSpec("jaotc",       1,   1,   1,   0,         0,    0,     2),     // -?, -h, --help
 141         new ToolHelpSpec("jar",         1,   1,   1,   0,         0,    0,     1),     // -?, -h, --help
 142         new ToolHelpSpec("jarsigner",   1,   1,   1,   0,         1,    0,     1),     // -?, -h, --help, -help accepted but not documented.
 143         new ToolHelpSpec("java",        1,   1,   1,   0,         1,    1,     1),     // -?, -h, --help -help, Documents -help
 144         new ToolHelpSpec("javac",       1,   0,   1,   0,         1,    1,     2),     // -?,     --help -help, Documents -help, -h is already taken for "native header output directory".
 145         new ToolHelpSpec("javadoc",     1,   1,   1,   0,         1,    1,     1),     // -?, -h, --help -help, Documents -help
 146         new ToolHelpSpec("javap",       1,   1,   1,   0,         1,    1,     2),     // -?, -h, --help -help, Documents -help
 147         new ToolHelpSpec("javaw",       1,   1,   1,   0,         1,    1,     1),     // -?, -h, --help -help, Documents -help, win only
 148         new ToolHelpSpec("jcmd",        1,   1,   1,   0,         1,    0,     1),     // -?, -h, --help, -help accepted but not documented.
 149         new ToolHelpSpec("jdb",         1,   1,   1,   0,         1,    1,     0),     // -?, -h, --help -help, Documents -help
 150         new ToolHelpSpec("jdeprscan",   1,   1,   1,   0,         0,    0,     1),     // -?, -h, --help
 151         new ToolHelpSpec("jdeps",       1,   1,   1,   0,         1,    0,     2),     // -?, -h, --help, -help accepted but not documented.
 152         new ToolHelpSpec("jhsdb",       0,   0,   0,   0,         0,    0,     0),     // none, prints help message anyways.
 153         new ToolHelpSpec("jimage",      1,   1,   1,   0,         0,    0,     2),     // -?, -h, --help
 154         new ToolHelpSpec("jinfo",       1,   1,   1,   0,         1,    1,     1),     // -?, -h, --help -help, Documents -help
 155         new ToolHelpSpec("jjs",         0,   1,   1, 100,         0,    0,   100),     //     -h, --help, return code 100
 156         new ToolHelpSpec("jlink",       1,   1,   1,   0,         0,    0,     2),     // -?, -h, --help
 157         new ToolHelpSpec("jmap",        1,   1,   1,   0,         1,    0,     1),     // -?, -h, --help, -help accepted but not documented.
 158         new ToolHelpSpec("jmod",        1,   1,   1,   0,         1,    0,     2),     // -?, -h, --help, -help accepted but not documented.
 159         new ToolHelpSpec("jps",         1,   1,   1,   0,         1,    1,     1),     // -?, -h, --help -help, Documents -help
 160         new ToolHelpSpec("jrunscript",  1,   1,   1,   0,         1,    1,     7),     // -?, -h, --help -help, Documents -help
 161         new ToolHelpSpec("jshell",      1,   1,   1,   0,         1,    0,     1),     // -?, -h, --help, -help accepted but not documented.
 162         new ToolHelpSpec("jstack",      1,   1,   1,   0,         1,    1,     1),     // -?, -h, --help -help, Documents -help
 163         new ToolHelpSpec("jstat",       1,   1,   1,   0,         1,    1,     1),     // -?, -h, --help -help, Documents -help
 164         new ToolHelpSpec("jstatd",      1,   1,   1,   0,         0,    0,     1),     // -?, -h, --help
 165         new ToolHelpSpec("keytool",     1,   1,   1,   0,         1,    0,     1),     // none, prints help message anyways.
 166         new ToolHelpSpec("pack200",     1,   1,   1,   0,         1,    0,     2),     // -?, -h, --help, -help accepted but not documented.
 167         new ToolHelpSpec("rmic",        0,   0,   0,   0,         0,    0,     1),     // none, pirnts help message anyways.
 168         new ToolHelpSpec("rmid",        0,   0,   0,   0,         0,    0,     1),     // none, prints help message anyways.
 169         new ToolHelpSpec("rmiregistry", 0,   0,   0,   0,         0,    0,     1),     // none, prints help message anyways.
 170         new ToolHelpSpec("serialver",   0,   0,   0,   0,         0,    0,     1),     // none, prints help message anyways.
 171         new ToolHelpSpec("unpack200",   1,   1,   1,   0,         1,    0,     2),     // -?, -h, --help, -help accepted but not documented.
 172         // Oracle proprietary tools:
 173         new ToolHelpSpec("javapackager",0,   0,   0,   0,         1,    0,   255),     // -help accepted but not documented.
 174     };
 175 
 176     // Returns true if the file is not a tool.
 177     static boolean notATool(String file) {
 178         if (isWindows && !file.endsWith(EXE_FILE_EXT))
 179             return true;
 180         return false;
 181     }
 182 
 183     // Returns true if tool is listed in TOOLS_NOT_TO_TEST.
 184     static boolean dontTestTool(String tool) {
 185         tool = tool.toLowerCase();
 186         for (String x : TOOLS_NOT_TO_TEST) {
 187             if (tool.toLowerCase().startsWith(x))
 188                 return true;
 189         }
 190         return false;
 191     }
 192 
 193     // Returns corresponding object from jdkTools array.
 194     static ToolHelpSpec getToolHelpSpec(String tool) {
 195         for (ToolHelpSpec x : jdkTools) {
 196             if (tool.toLowerCase().equals(x.toolname) ||
 197                 tool.toLowerCase().equals(x.toolname + ".exe"))
 198                 return x;
 199         }
 200         return null;
 201     }
 202 
 203     // Check whether 'flag' appears in 'line' as a word of itself. It must not
 204     // be a substring of a word, as then similar flags might be matched.
 205     // E.g.: --help matches in the documentation of --help-extra.
 206     // This works only with english locale, as some tools have translated
 207     // usage messages.
 208     static boolean findFlagInLine(String line, String flag) {
 209         if (line.contains(flag) &&
 210             !line.contains("nknown") &&                       // Some tools say 'Unknown option "<flag>"',
 211             !line.contains("invalid flag") &&                 // 'invalid flag: <flag>'
 212             !line.contains("invalid option") &&               // or 'invalid option: <flag>'. Skip that.
 213             !line.contains("FileNotFoundException: -help") && // Special case for idlj.
 214             !line.contains("-h requires an argument") &&      // Special case for javac.
 215             !line.contains("port argument,")) {               // Special case for rmiregistry.
 216             // There might be several appearances of 'flag' in
 217             // 'line'. (-h as substring of --help).
 218             int flagLen = flag.length();
 219             int lineLen = line.length();
 220             for (int i = line.indexOf(flag); i >= 0; i = line.indexOf(flag, i+1)) {
 221                 // There should be a space before 'flag' in 'line', or it's right at the beginning.
 222                 if (i > 0 &&
 223                     line.charAt(i-1) != ' ' &&
 224                     line.charAt(i-1) != '[' &&  // jarsigner
 225                     line.charAt(i-1) != '|' &&  // jstatd
 226                     line.charAt(i-1) != '\t') { // jjs
 227                     continue;
 228                 }
 229                 // There should be a space or comma after 'flag' in 'line', or it's just at the end.
 230                 int posAfter = i + flagLen;
 231                 if (posAfter < lineLen &&
 232                     line.charAt(posAfter) != ' ' &&
 233                     line.charAt(posAfter) != ',' &&
 234                     line.charAt(posAfter) != '[' && // jar
 235                     line.charAt(posAfter) != ']' && // jarsigner
 236                     line.charAt(posAfter) != '|' && // jstatd
 237                     line.charAt(posAfter) != ':' && // jps
 238                     line.charAt(posAfter) != '"') { // keytool
 239                     continue;
 240                 }
 241                 return true;
 242             }
 243         }
 244         return false;
 245     }
 246 
 247     static TestResult runToolWithFlag(File f, String flag) {
 248         String x = f.getAbsolutePath();
 249         TestResult tr = doExec(x, flag);
 250         System.out.println("Testing " + f.getName());
 251         System.out.println("#> " + x + " " + flag);
 252         tr.testOutput.forEach(System.out::println);
 253         System.out.println("#> echo $?");
 254         System.out.println(tr.exitValue);
 255 
 256         return tr;
 257     }
 258 
 259     // Checks whether tool supports flag 'flag' and documents it
 260     // in the help message.
 261     static String testTool(File f, String flag, int exitcode) {
 262         String result = "";
 263         TestResult tr = runToolWithFlag(f, flag);
 264 
 265         // Check that the tool accepted the flag.
 266         if (exitcode == 0 && !tr.isOK()) {
 267             System.out.println("failed");
 268             result = "failed: " + f.getName() + " " + flag + " has exit code " + tr.exitValue + ".\n";
 269         }
 270 
 271         // Check there is a help message listing the flag.
 272         boolean foundFlag = false;
 273         for (String y : tr.testOutput) {
 274             if (!foundFlag && findFlagInLine(y, flag)) { // javac
 275                 foundFlag = true;
 276                 System.out.println("Found documentation of '" + flag + "': '" + y.trim() +"'");
 277             }
 278         }
 279         if (!foundFlag) {
 280             result += "failed: " + f.getName() + " does not document " +
 281                 flag + " in help message.\n";
 282         }
 283 
 284         if (!result.isEmpty())
 285             System.out.println(result);
 286 
 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         // Check there is _no_ documentation of -help.
 303         boolean foundFlag = false;
 304         for (String y : tr.testOutput) {
 305             if (!foundFlag && findFlagInLine(y, "-help")) {  // javac
 306                 foundFlag = true;
 307                 System.out.println("Found documentation of '-help': '" + y.trim() +"'");
 308             }
 309         }
 310         if (foundFlag) {
 311             result += "failed: " + f.getName() + " does document -help " +
 312                 "in help message. This legacy flag should not be documented.\n";
 313         }
 314 
 315         if (!result.isEmpty())
 316             System.out.println(result);
 317 
 318         return result;
 319     }
 320 
 321     // Test that the tool exits with the exit code expected for
 322     // invalid flags. In general, one would expect this to be != 0,
 323     // but currently a row of tools exit with 0 in this case.
 324     // The output should not ask to get help with flag '-help'.
 325     static String testInvalidFlag(File f, String flag, int exitcode, boolean documentsLegacyHelp) {
 326         String result = "";
 327         TestResult tr = runToolWithFlag(f, flag);
 328 
 329         // Check that the tool did exit with the expected return code.
 330         if (!((exitcode == tr.exitValue) ||
 331               // Windows reports -1 where unix reports 255.
 332               (tr.exitValue < 0 && exitcode == tr.exitValue + 256))) {
 333             System.out.println("failed");
 334             result = "failed: " + f.getName() + " " + flag + " should not be " +
 335                      "accepted. But it has exit code " + tr.exitValue + ".\n";
 336         }
 337 
 338         if (!documentsLegacyHelp) {
 339             // Check there is _no_ documentation of -help.
 340             boolean foundFlag = false;
 341             for (String y : tr.testOutput) {
 342                 if (!foundFlag && findFlagInLine(y, "-help")) {  // javac
 343                     foundFlag = true;
 344                     System.out.println("Found documentation of '-help': '" + y.trim() +"'");
 345                 }
 346             }
 347             if (foundFlag) {
 348                 result += "failed: " + f.getName() + " does document -help " +
 349                     "in error message. This legacy flag should not be documented.\n";
 350             }
 351         }
 352 
 353         if (!result.isEmpty())
 354             System.out.println(result);
 355 
 356         return result;
 357     }
 358 
 359     public static void main(String[] args) {
 360         String errorMessage = "";
 361 
 362         // The test analyses the help messages printed. It assumes englisch
 363         // help messages. Thus it only works with english locale.
 364         if (!isEnglishLocale()) { return; }
 365 
 366         for (File f : new File(JAVA_BIN).listFiles()) {
 367             String toolName = f.getName();
 368 
 369             if (notATool(toolName)) {
 370                 continue;
 371             }
 372             if (dontTestTool(toolName)) {
 373                 System.out.println("Skipping test of tool " + toolName +
 374                                    ". Tool has no help message.");
 375                 continue;
 376             }
 377 
 378             ToolHelpSpec tool = getToolHelpSpec(toolName);
 379             if (tool == null) {
 380                 errorMessage += "Tool " + toolName + " not covered by this test. " +
 381                     "Add specification to jdkTools array!\n";
 382                 continue;
 383             }
 384 
 385             // Test for help flags to be supported.
 386             if (tool.supportsQuestionMark == true) {
 387                 errorMessage += testTool(f, "-?", tool.exitcodeOfHelp);
 388             } else {
 389                 System.out.println("Skip " + tool.toolname + ". It does not support -?.");
 390             }
 391             if (tool.supportsH == true) {
 392                 errorMessage += testTool(f, "-h", tool.exitcodeOfHelp);
 393             } else {
 394                 System.out.println("Skip " + tool.toolname + ". It does not support -h.");
 395             }
 396             if (tool.supportsHelp == true) {
 397                 errorMessage += testTool(f, "--help", tool.exitcodeOfHelp);
 398             } else {
 399                 System.out.println("Skip " + tool.toolname + ". It does not support --help.");
 400             }
 401 
 402             // Check that the return code listing in jdkTools[] is
 403             // correct for an invalid flag.
 404             errorMessage += testInvalidFlag(f, "-asdfxgr", tool.exitcodeOfWrongFlag, tool.documentsLegacyHelp);
 405 
 406             // Test for legacy -help flag.
 407             if (!tool.documentsLegacyHelp) {
 408                 if (tool.supportsLegacyHelp == true) {
 409                     errorMessage += testLegacyFlag(f, tool.exitcodeOfHelp);
 410                 } else {
 411                     errorMessage += testInvalidFlag(f, "-help", tool.exitcodeOfWrongFlag, false);
 412                 }
 413             }
 414         }
 415 
 416         if (errorMessage.isEmpty()) {
 417             System.out.println("All help string tests: PASS");
 418         } else {
 419             throw new AssertionError("HelpFlagsTest failed:\n" + errorMessage);
 420         }
 421     }
 422 }