File: ArgCheck.java

package info (click to toggle)
openjdk-21 21.0.8%2B9-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 823,976 kB
  • sloc: java: 5,613,338; xml: 1,643,607; cpp: 1,296,296; ansic: 420,291; asm: 404,850; objc: 20,994; sh: 15,271; javascript: 11,245; python: 6,895; makefile: 2,362; perl: 357; awk: 351; sed: 172; jsp: 24; csh: 3
file content (321 lines) | stat: -rw-r--r-- 14,417 bytes parent folder | download | duplicates (15)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
/*
 * Copyright (c) 2021, 2022, Oracle and/or its affiliates. All rights reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
 */

/**
 * @test
 * @bug 8282008
 * @requires (os.family == "windows")
 * @run main/othervm ArgCheck
 * @summary Check invocation of exe and non-exe programs using ProcessBuilder
 *      and arguments with spaces, backslashes, and simple quoting.
 */

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * Class to check invocation of java, .cmd, and vbs scripts with arguments and various quote cases.
 * Can be run standalone to compare results with other Java versions.
 */
public class ArgCheck {

    private static final Path SRC_DIR = Paths.get(System.getProperty("test.src", "."));
    private static final Path WORK_DIR = Paths.get(System.getProperty("user.dir", "."));
    private static final Path TEST_CLASSES = Paths.get(System.getProperty("test.classes", "."));

    private static final String ECHO_CMD_PATH = WORK_DIR.resolve("EchoArguments.cmd").toString();
    private static final String ECHO_VBS_PATH = WORK_DIR.resolve("EchoArguments.vbs").toString();

    // Test argument containing both a space and a trailing backslash
    // Depending on the mode the final backslash may act as an escape that may turn an added quote to a literal quote
    private static final String SPACE_AND_BACKSLASH = "SPACE AND BACKSLASH\\";
    private static final char DOUBLE_QUOTE = '"';
    private static final char BACKSLASH = '\\';

    private static final String AMBIGUOUS_PROP_NAME = "jdk.lang.Process.allowAmbiguousCommands";
    private static final String AMBIGUOUS_PROP_VALUE = System.getProperty(AMBIGUOUS_PROP_NAME);
    private static final Boolean AMBIGUOUS_PROP_BOOLEAN = AMBIGUOUS_PROP_VALUE == null ? null :
                                                          Boolean.valueOf(!"false".equals(AMBIGUOUS_PROP_VALUE));

    private static final List<String> ECHO_JAVA_ARGS = Arrays.asList("java", "-classpath", TEST_CLASSES.toString(), "ArgCheck");
    private static final List<String> ECHO_CMD_ARGS = Arrays.asList(ECHO_CMD_PATH);
    private static final List<String> ECHO_VBS_ARGS = Arrays.asList("CScript", "/b", ECHO_VBS_PATH);

    /**
     * If zero arguments are supplied, run the test cases, by launching each as a child process.
     * If there are arguments, then this is a child Java process that prints each argument to stdout.
     * The test can be run manually with -Djdk.lang.Process.allowAmbiguousCommands={"true", "false", ""}
     * to run a matching subset of the tests.
     */
    public static void main(String[] args) throws IOException {
        if (args.length > 0) {
            // Echo supplied arguments and exit
            for (String arg : args)
                System.out.println(arg);
            return;
        }

        System.out.println("Java Version: " + System.getProperty("java.version"));

        createFiles();

        int errors = 0;
        int success = 0;
        int skipped = 0;

        for (CMD cmd : CASES) {
            // If System property jdk.lang.process.allowAmbiguousCommands matches the case, test it
            // If undefined, test them all
            if (AMBIGUOUS_PROP_BOOLEAN == null ||
                    AMBIGUOUS_PROP_BOOLEAN.booleanValue() == cmd.allowAmbiguous) {
                try {
                    testCommand(cmd);
                    success++;
                } catch (Exception ex) {
                    ex.printStackTrace();
                    errors++;
                }
            } else {
                // skip unmatched cases
                skipped++;
            }
        }
        if (skipped > 0) {
            System.out.printf("%d cases skipped, they did not match the tests with jdk.lang.Process.allowAmbiguousCommands: %s%n",
                    skipped, AMBIGUOUS_PROP_BOOLEAN);
        }
        System.out.printf("\nSuccess: %d, errors: %d%n", success, errors);
        if (errors > 0) {
            throw new RuntimeException("Errors: " + errors);
        }
    }

    /**
     * A CMD holds the parameters and the expected result of invoking a process with the parameters.
     */
    static class CMD {
        /**
         * Construct a test case.
         * @param allowAmbiguous  true/false to set property jdk.lang.Process.allowAmbiguousCommands
         * @param command list of command parameters to invoke the executable or script
         * @param arguments list of arguments (appended to the command)
         * @param expected    expected lines of output from invoked command
         */
        CMD(boolean allowAmbiguous, List<String> command, List<String> arguments, List<String> expected) {
            this.allowAmbiguous = allowAmbiguous;
            this.command = command;
            this.arguments = arguments;
            this.expected = expected;
        }

        final boolean allowAmbiguous;
        final List<String> command;
        final List<String> arguments;
        final List<String> expected;
    }

    /**
     * List of cases with the command, arguments, allowAmbiguous setting, and the expected results
     */
    static final List<CMD> CASES = Arrays.asList(

            // allowAmbiguousCommands = false, without application supplied double-quotes.
            // The space in the argument requires it to be quoted, the final backslash
            // must not be allowed to turn the quote that is added into a literal
            // instead of closing the quote.
            new CMD(false,
                    ECHO_JAVA_ARGS,
                    Arrays.asList(SPACE_AND_BACKSLASH, "ARG_1"),
                    Arrays.asList(SPACE_AND_BACKSLASH, "ARG_1")),
            new CMD(false,
                    ECHO_CMD_ARGS,
                    Arrays.asList(SPACE_AND_BACKSLASH, "ARG_2"),
                    Arrays.asList(DOUBLE_QUOTE + SPACE_AND_BACKSLASH + DOUBLE_QUOTE, "ARG_2")),
            new CMD(false,
                    ECHO_VBS_ARGS,
                    Arrays.asList(SPACE_AND_BACKSLASH, "ARG_3"),
                    Arrays.asList(SPACE_AND_BACKSLASH + BACKSLASH, "ARG_3")),

            // allowAmbiguousCommands = false, WITH application supplied double-quotes around the argument
            // The argument has surrounding quotes so does not need further quoting.
            // However, for exe commands, the final backslash must not be allowed to turn the quote
            // into a literal instead of closing the quote.
            new CMD(false,
                    ECHO_JAVA_ARGS,
                    Arrays.asList(DOUBLE_QUOTE + SPACE_AND_BACKSLASH + DOUBLE_QUOTE, "ARG_11"),
                    Arrays.asList(SPACE_AND_BACKSLASH, "ARG_11")),
            new CMD(false,
                    ECHO_CMD_ARGS,
                    Arrays.asList(DOUBLE_QUOTE + SPACE_AND_BACKSLASH + DOUBLE_QUOTE, "ARG_12"),
                    Arrays.asList(DOUBLE_QUOTE + SPACE_AND_BACKSLASH + DOUBLE_QUOTE, "ARG_12")),
            new CMD(false,
                    ECHO_VBS_ARGS,
                    Arrays.asList(DOUBLE_QUOTE + SPACE_AND_BACKSLASH + DOUBLE_QUOTE, "ARG_13"),
                    Arrays.asList(SPACE_AND_BACKSLASH + BACKSLASH, "ARG_13")),

            // Legacy mode tests; allowAmbiguousCommands = true; no application supplied quotes
            // The space in the argument requires it to be quoted, the final backslash
            // must not be allowed to turn the quote that is added into a literal
            // instead of closing the quote.
            new CMD(true,
                    ECHO_JAVA_ARGS,
                    Arrays.asList(SPACE_AND_BACKSLASH, "ARG_21"),
                    Arrays.asList(SPACE_AND_BACKSLASH, "ARG_21")),
            new CMD(true,
                    ECHO_CMD_ARGS,
                    Arrays.asList(SPACE_AND_BACKSLASH, "ARG_22"),
                    Arrays.asList(DOUBLE_QUOTE + SPACE_AND_BACKSLASH + BACKSLASH + DOUBLE_QUOTE, "ARG_22")),
            new CMD(true,
                    ECHO_VBS_ARGS,
                    Arrays.asList(SPACE_AND_BACKSLASH, "ARG_23"),
                    Arrays.asList(SPACE_AND_BACKSLASH + BACKSLASH, "ARG_23")),

            // allowAmbiguousCommands = true, WITH application supplied double-quotes around the argument
            // The argument has surrounding quotes so does not need further quoting.
            // The backslash before the final quote is ignored and is interpreted differently for each command.
            new CMD(true,
                    ECHO_JAVA_ARGS,
                    Arrays.asList(DOUBLE_QUOTE + SPACE_AND_BACKSLASH + DOUBLE_QUOTE, "ARG_31"),
                    Arrays.asList("SPACE AND BACKSLASH\" ARG_31")),
            new CMD(true,
                    ECHO_CMD_ARGS,
                    Arrays.asList(DOUBLE_QUOTE + SPACE_AND_BACKSLASH + DOUBLE_QUOTE, "ARG_32"),
                    Arrays.asList(DOUBLE_QUOTE + SPACE_AND_BACKSLASH + DOUBLE_QUOTE, "ARG_32")),
            new CMD(true,
                    ECHO_VBS_ARGS,
                    Arrays.asList(DOUBLE_QUOTE + SPACE_AND_BACKSLASH + DOUBLE_QUOTE, "ARG_33"),
                    Arrays.asList(SPACE_AND_BACKSLASH, "ARG_33"))
    );

    /**
     * Common function to Invoke a process with the commands and check the result.
     *
     * @param cmd a CMD test case with arguments, allowAmbiguousCommands mode, and expected output
     */
    private static void testCommand(CMD cmd) throws Exception {
        System.setProperty(AMBIGUOUS_PROP_NAME, Boolean.toString(cmd.allowAmbiguous));
        List<String> actual = null;
        List<String> arguments = new ArrayList<>(cmd.command);
        arguments.addAll(cmd.arguments);
        try {
            // Launch the process and wait for termination
            ProcessBuilder pb = new ProcessBuilder(arguments);
            Process process = pb.start();
            try (InputStream is = process.getInputStream()) {
                String str = readAllBytesAsString(is);
                str = str.replace("\r", "");
                actual = Arrays.asList(str.split("\n"));
            } catch (IOException ioe) {
                throw new RuntimeException(ioe.getMessage(), ioe);
            }
            int exitCode = process.waitFor();
            if (exitCode != 0) {
                actual = new ArrayList(actual);
                actual.add("Exit code: " + exitCode);
            }
        } catch (IOException ioe) {
            actual = Arrays.asList(ioe.getMessage().replace(arguments.get(0), "CMD"));
        } catch (Exception ex) {
            actual = Arrays.asList(ex.getMessage());       // Use exception message as output
        }
        if (!Objects.equals(actual, cmd.expected)) {
            System.out.println("Invoking(" + cmd.allowAmbiguous + "): " + arguments);
            if (actual.size() != cmd.expected.size()) {
                System.out.println("Args Length: actual: " + actual.size() + " expected: " + cmd.expected.size());
            }
            System.out.println("Actual:   " + actual);
            System.out.println("Expected: " + cmd.expected);
            System.out.println();
            throw new RuntimeException("Unexpected output");
        }
    }

    /**
     * Private method to readAllBytes as a String.
     * (InputStream.readAllBytes is not supported by the JDK until 9)
     * @param is an InputStream
     * @return a String with the contents
     * @throws IOException if an error occurs
     */
    private static String readAllBytesAsString(InputStream is) throws IOException {
        final int BUF_SIZE = 8192;
        byte[] bytes = new byte[BUF_SIZE];
        int off = 0;
        int len;
        while ((len = is.read(bytes, off, bytes.length - off)) > 0) {
            off += len;
            if (off >= bytes.length) {
                // no space in buffer, reallocate larger
                bytes = Arrays.copyOf(bytes, bytes.length + BUF_SIZE);
            }
        }
        return new String(bytes, 0, off, Charset.defaultCharset());
    }

    /**
     * Initialize .cmd and .vbs scripts.
     *
     * @throws Error if an exception occurs
     */
    private static void createFiles() throws IOException {
        Files.write(Paths.get(ECHO_CMD_PATH), EchoArgumentsCmd.getBytes(StandardCharsets.UTF_8));
        Files.write(Paths.get(ECHO_VBS_PATH), EchoArgumentsVbs.getBytes(StandardCharsets.UTF_8));
    }

    /**
     * Self contained .cmd to echo each argument on a separate line.
     */
    static final String EchoArgumentsCmd = "@echo off\n" +
            "set p1=\n" +
            "set p2=\n" +
            "\n" +
            "if not [%1]==[] set p1=%1\n" +
            "if not [%2]==[] set p2=%2\n" +
            "if not [%3]==[] set p3=%3\n" +
            "if defined p1 echo %p1%\n" +
            "if defined p2 echo %p2%\n" +
            "if defined p3 echo %p3%\n" +
            "exit /b 0\n";


    /**
     * Self contained .vbs to echo each argument on a separate line.
     */
    static final String EchoArgumentsVbs = "Option Explicit\n" +
            "Dim arg\n" +
            "for each arg in WScript.Arguments\n" +
            "  WScript.StdOut.WriteLine(arg)\n" +
            "Next\n";
}