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