0N/A/*
4944N/A * Copyright (c) 2003, 2012, Oracle and/or its affiliates. All rights reserved.
0N/A * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
0N/A *
0N/A * This code is free software; you can redistribute it and/or modify it
0N/A * under the terms of the GNU General Public License version 2 only, as
0N/A * published by the Free Software Foundation.
0N/A *
0N/A * This code is distributed in the hope that it will be useful, but WITHOUT
0N/A * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
0N/A * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
0N/A * version 2 for more details (a copy is included in the LICENSE file that
0N/A * accompanied this code).
0N/A *
0N/A * You should have received a copy of the GNU General Public License version
0N/A * 2 along with this work; if not, write to the Free Software Foundation,
0N/A * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
0N/A *
2362N/A * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
2362N/A * or visit www.oracle.com if you need additional information or have any
2362N/A * questions.
0N/A */
0N/A
0N/A/*
0N/A * @test
0N/A * @bug 4199068 4738465 4937983 4930681 4926230 4931433 4932663 4986689
0N/A * 5026830 5023243 5070673 4052517 4811767 6192449 6397034 6413313
1651N/A * 6464154 6523983 6206031 4960438 6631352 6631966 6850957 6850958
4103N/A * 4947220 7018606 7034570
0N/A * @summary Basic tests for Process and Environment Variable code
2391N/A * @run main/othervm/timeout=300 Basic
0N/A * @author Martin Buchholz
0N/A */
0N/A
25N/Aimport java.lang.ProcessBuilder.Redirect;
25N/Aimport static java.lang.ProcessBuilder.Redirect.*;
25N/A
0N/Aimport java.io.*;
5376N/Aimport java.lang.reflect.Field;
0N/Aimport java.util.*;
2473N/Aimport java.util.concurrent.CountDownLatch;
0N/Aimport java.security.*;
5377N/Aimport sun.misc.Unsafe;
0N/Aimport java.util.regex.Pattern;
4666N/Aimport java.util.regex.Matcher;
0N/Aimport static java.lang.System.getenv;
0N/Aimport static java.lang.System.out;
0N/Aimport static java.lang.Boolean.TRUE;
0N/Aimport static java.util.AbstractMap.SimpleImmutableEntry;
0N/A
0N/Apublic class Basic {
0N/A
3664N/A /* used for Windows only */
3664N/A static final String systemRoot = System.getenv("SystemRoot");
3664N/A
4666N/A /* used for Mac OS X only */
4666N/A static final String cfUserTextEncoding = System.getenv("__CF_USER_TEXT_ENCODING");
4666N/A
0N/A private static String commandOutput(Reader r) throws Throwable {
0N/A StringBuilder sb = new StringBuilder();
0N/A int c;
0N/A while ((c = r.read()) > 0)
0N/A if (c != '\r')
0N/A sb.append((char) c);
0N/A return sb.toString();
0N/A }
0N/A
0N/A private static String commandOutput(Process p) throws Throwable {
0N/A check(p.getInputStream() == p.getInputStream());
0N/A check(p.getOutputStream() == p.getOutputStream());
0N/A check(p.getErrorStream() == p.getErrorStream());
0N/A Reader r = new InputStreamReader(p.getInputStream(),"UTF-8");
0N/A String output = commandOutput(r);
0N/A equal(p.waitFor(), 0);
0N/A equal(p.exitValue(), 0);
0N/A return output;
0N/A }
0N/A
0N/A private static String commandOutput(ProcessBuilder pb) {
0N/A try {
0N/A return commandOutput(pb.start());
0N/A } catch (Throwable t) {
0N/A String commandline = "";
0N/A for (String arg : pb.command())
0N/A commandline += " " + arg;
0N/A System.out.println("Exception trying to run process: " + commandline);
0N/A unexpected(t);
0N/A return "";
0N/A }
0N/A }
0N/A
0N/A private static String commandOutput(String...command) {
0N/A try {
0N/A return commandOutput(Runtime.getRuntime().exec(command));
0N/A } catch (Throwable t) {
0N/A String commandline = "";
0N/A for (String arg : command)
0N/A commandline += " " + arg;
0N/A System.out.println("Exception trying to run process: " + commandline);
0N/A unexpected(t);
0N/A return "";
0N/A }
0N/A }
0N/A
0N/A private static void checkCommandOutput(ProcessBuilder pb,
0N/A String expected,
0N/A String failureMsg) {
0N/A String got = commandOutput(pb);
0N/A check(got.equals(expected),
0N/A failureMsg + "\n" +
0N/A "Expected: \"" + expected + "\"\n" +
0N/A "Got: \"" + got + "\"");
0N/A }
0N/A
0N/A private static String absolutifyPath(String path) {
0N/A StringBuilder sb = new StringBuilder();
0N/A for (String file : path.split(File.pathSeparator)) {
0N/A if (sb.length() != 0)
0N/A sb.append(File.pathSeparator);
0N/A sb.append(new File(file).getAbsolutePath());
0N/A }
0N/A return sb.toString();
0N/A }
0N/A
0N/A // compare windows-style, by canonicalizing to upper case,
0N/A // not lower case as String.compareToIgnoreCase does
0N/A private static class WindowsComparator
0N/A implements Comparator<String> {
0N/A public int compare(String x, String y) {
0N/A return x.toUpperCase(Locale.US)
0N/A .compareTo(y.toUpperCase(Locale.US));
0N/A }
0N/A }
0N/A
0N/A private static String sortedLines(String lines) {
0N/A String[] arr = lines.split("\n");
0N/A List<String> ls = new ArrayList<String>();
0N/A for (String s : arr)
0N/A ls.add(s);
0N/A Collections.sort(ls, new WindowsComparator());
0N/A StringBuilder sb = new StringBuilder();
0N/A for (String s : ls)
0N/A sb.append(s + "\n");
0N/A return sb.toString();
0N/A }
0N/A
0N/A private static void compareLinesIgnoreCase(String lines1, String lines2) {
0N/A if (! (sortedLines(lines1).equalsIgnoreCase(sortedLines(lines2)))) {
0N/A String dashes =
0N/A "-----------------------------------------------------";
0N/A out.println(dashes);
0N/A out.print(sortedLines(lines1));
0N/A out.println(dashes);
0N/A out.print(sortedLines(lines2));
0N/A out.println(dashes);
0N/A out.println("sizes: " + sortedLines(lines1).length() +
0N/A " " + sortedLines(lines2).length());
0N/A
0N/A fail("Sorted string contents differ");
0N/A }
0N/A }
0N/A
0N/A private static final Runtime runtime = Runtime.getRuntime();
0N/A
0N/A private static final String[] winEnvCommand = {"cmd.exe", "/c", "set"};
0N/A
0N/A private static String winEnvFilter(String env) {
0N/A return env.replaceAll("\r", "")
0N/A .replaceAll("(?m)^(?:COMSPEC|PROMPT|PATHEXT)=.*\n","");
0N/A }
0N/A
0N/A private static String unixEnvProg() {
0N/A return new File("/usr/bin/env").canExecute() ? "/usr/bin/env"
0N/A : "/bin/env";
0N/A }
0N/A
0N/A private static String nativeEnv(String[] env) {
0N/A try {
0N/A if (Windows.is()) {
0N/A return winEnvFilter
0N/A (commandOutput(runtime.exec(winEnvCommand, env)));
0N/A } else {
0N/A return commandOutput(runtime.exec(unixEnvProg(), env));
0N/A }
0N/A } catch (Throwable t) { throw new Error(t); }
0N/A }
0N/A
0N/A private static String nativeEnv(ProcessBuilder pb) {
0N/A try {
0N/A if (Windows.is()) {
0N/A pb.command(winEnvCommand);
0N/A return winEnvFilter(commandOutput(pb));
0N/A } else {
0N/A pb.command(new String[]{unixEnvProg()});
0N/A return commandOutput(pb);
0N/A }
0N/A } catch (Throwable t) { throw new Error(t); }
0N/A }
0N/A
0N/A private static void checkSizes(Map<String,String> environ, int size) {
0N/A try {
0N/A equal(size, environ.size());
0N/A equal(size, environ.entrySet().size());
0N/A equal(size, environ.keySet().size());
0N/A equal(size, environ.values().size());
0N/A
0N/A boolean isEmpty = (size == 0);
0N/A equal(isEmpty, environ.isEmpty());
0N/A equal(isEmpty, environ.entrySet().isEmpty());
0N/A equal(isEmpty, environ.keySet().isEmpty());
0N/A equal(isEmpty, environ.values().isEmpty());
0N/A } catch (Throwable t) { unexpected(t); }
0N/A }
0N/A
0N/A private interface EnvironmentFrobber {
0N/A void doIt(Map<String,String> environ);
0N/A }
0N/A
0N/A private static void testVariableDeleter(EnvironmentFrobber fooDeleter) {
0N/A try {
0N/A Map<String,String> environ = new ProcessBuilder().environment();
0N/A environ.put("Foo", "BAAR");
0N/A fooDeleter.doIt(environ);
0N/A equal(environ.get("Foo"), null);
0N/A equal(environ.remove("Foo"), null);
0N/A } catch (Throwable t) { unexpected(t); }
0N/A }
0N/A
0N/A private static void testVariableAdder(EnvironmentFrobber fooAdder) {
0N/A try {
0N/A Map<String,String> environ = new ProcessBuilder().environment();
0N/A environ.remove("Foo");
0N/A fooAdder.doIt(environ);
0N/A equal(environ.get("Foo"), "Bahrein");
0N/A } catch (Throwable t) { unexpected(t); }
0N/A }
0N/A
0N/A private static void testVariableModifier(EnvironmentFrobber fooModifier) {
0N/A try {
0N/A Map<String,String> environ = new ProcessBuilder().environment();
0N/A environ.put("Foo","OldValue");
0N/A fooModifier.doIt(environ);
0N/A equal(environ.get("Foo"), "NewValue");
0N/A } catch (Throwable t) { unexpected(t); }
0N/A }
0N/A
0N/A private static void printUTF8(String s) throws IOException {
0N/A out.write(s.getBytes("UTF-8"));
0N/A }
0N/A
0N/A private static String getenvAsString(Map<String,String> environment) {
0N/A StringBuilder sb = new StringBuilder();
0N/A for (Map.Entry<String,String> e : environment.entrySet())
0N/A // Ignore magic environment variables added by the launcher
0N/A if (! e.getKey().equals("NLSPATH") &&
0N/A ! e.getKey().equals("XFILESEARCHPATH") &&
0N/A ! e.getKey().equals("LD_LIBRARY_PATH"))
0N/A sb.append(e.getKey())
0N/A .append('=')
0N/A .append(e.getValue())
0N/A .append(',');
0N/A return sb.toString();
0N/A }
0N/A
2473N/A static void print4095(OutputStream s, byte b) throws Throwable {
0N/A byte[] bytes = new byte[4095];
2473N/A Arrays.fill(bytes, b);
0N/A s.write(bytes); // Might hang!
0N/A }
0N/A
1270N/A static void checkPermissionDenied(ProcessBuilder pb) {
1270N/A try {
1270N/A pb.start();
1270N/A fail("Expected IOException not thrown");
1270N/A } catch (IOException e) {
1270N/A String m = e.getMessage();
1270N/A if (EnglishUnix.is() &&
1270N/A ! matches(m, "Permission denied"))
1270N/A unexpected(e);
1270N/A } catch (Throwable t) { unexpected(t); }
1270N/A }
1270N/A
0N/A public static class JavaChild {
0N/A public static void main(String args[]) throws Throwable {
0N/A String action = args[0];
2473N/A if (action.equals("sleep")) {
2473N/A Thread.sleep(10 * 60 * 1000L);
2473N/A } else if (action.equals("testIO")) {
25N/A String expected = "standard input";
25N/A char[] buf = new char[expected.length()+1];
25N/A int n = new InputStreamReader(System.in).read(buf,0,buf.length);
25N/A if (n != expected.length())
25N/A System.exit(5);
25N/A if (! new String(buf,0,n).equals(expected))
25N/A System.exit(5);
25N/A System.err.print("standard error");
25N/A System.out.print("standard output");
25N/A } else if (action.equals("testInheritIO")) {
25N/A List<String> childArgs = new ArrayList<String>(javaChildArgs);
25N/A childArgs.add("testIO");
25N/A ProcessBuilder pb = new ProcessBuilder(childArgs);
25N/A pb.inheritIO();
25N/A ProcessResults r = run(pb);
25N/A if (! r.out().equals(""))
25N/A System.exit(7);
25N/A if (! r.err().equals(""))
25N/A System.exit(8);
25N/A if (r.exitValue() != 0)
25N/A System.exit(9);
25N/A } else if (action.equals("System.getenv(String)")) {
0N/A String val = System.getenv(args[1]);
0N/A printUTF8(val == null ? "null" : val);
0N/A } else if (action.equals("System.getenv(\\u1234)")) {
0N/A String val = System.getenv("\u1234");
0N/A printUTF8(val == null ? "null" : val);
0N/A } else if (action.equals("System.getenv()")) {
0N/A printUTF8(getenvAsString(System.getenv()));
1651N/A } else if (action.equals("ArrayOOME")) {
1651N/A Object dummy;
1651N/A switch(new Random().nextInt(3)) {
1651N/A case 0: dummy = new Integer[Integer.MAX_VALUE]; break;
1651N/A case 1: dummy = new double[Integer.MAX_VALUE]; break;
1651N/A case 2: dummy = new byte[Integer.MAX_VALUE][]; break;
1651N/A default: throw new InternalError();
1651N/A }
0N/A } else if (action.equals("pwd")) {
0N/A printUTF8(new File(System.getProperty("user.dir"))
0N/A .getCanonicalPath());
0N/A } else if (action.equals("print4095")) {
2473N/A print4095(System.out, (byte) '!');
2473N/A print4095(System.err, (byte) 'E');
0N/A System.exit(5);
0N/A } else if (action.equals("OutErr")) {
0N/A // You might think the system streams would be
0N/A // buffered, and in fact they are implemented using
0N/A // BufferedOutputStream, but each and every print
0N/A // causes immediate operating system I/O.
0N/A System.out.print("out");
0N/A System.err.print("err");
0N/A System.out.print("out");
0N/A System.err.print("err");
0N/A } else if (action.equals("null PATH")) {
0N/A equal(System.getenv("PATH"), null);
0N/A check(new File("/bin/true").exists());
0N/A check(new File("/bin/false").exists());
0N/A ProcessBuilder pb1 = new ProcessBuilder();
0N/A ProcessBuilder pb2 = new ProcessBuilder();
0N/A pb2.environment().put("PATH", "anyOldPathIgnoredAnyways");
0N/A ProcessResults r;
0N/A
0N/A for (final ProcessBuilder pb :
0N/A new ProcessBuilder[] {pb1, pb2}) {
0N/A pb.command("true");
1270N/A equal(run(pb).exitValue(), True.exitValue());
0N/A
0N/A pb.command("false");
1270N/A equal(run(pb).exitValue(), False.exitValue());
0N/A }
0N/A
0N/A if (failed != 0) throw new Error("null PATH");
0N/A } else if (action.equals("PATH search algorithm")) {
0N/A equal(System.getenv("PATH"), "dir1:dir2:");
0N/A check(new File("/bin/true").exists());
0N/A check(new File("/bin/false").exists());
0N/A String[] cmd = {"prog"};
0N/A ProcessBuilder pb1 = new ProcessBuilder(cmd);
0N/A ProcessBuilder pb2 = new ProcessBuilder(cmd);
0N/A ProcessBuilder pb3 = new ProcessBuilder(cmd);
0N/A pb2.environment().put("PATH", "anyOldPathIgnoredAnyways");
0N/A pb3.environment().remove("PATH");
0N/A
0N/A for (final ProcessBuilder pb :
0N/A new ProcessBuilder[] {pb1, pb2, pb3}) {
0N/A try {
0N/A // Not on PATH at all; directories don't exist
0N/A try {
0N/A pb.start();
0N/A fail("Expected IOException not thrown");
0N/A } catch (IOException e) {
0N/A String m = e.getMessage();
0N/A if (EnglishUnix.is() &&
0N/A ! matches(m, "No such file"))
0N/A unexpected(e);
0N/A } catch (Throwable t) { unexpected(t); }
0N/A
0N/A // Not on PATH at all; directories exist
0N/A new File("dir1").mkdirs();
0N/A new File("dir2").mkdirs();
0N/A try {
0N/A pb.start();
0N/A fail("Expected IOException not thrown");
0N/A } catch (IOException e) {
0N/A String m = e.getMessage();
0N/A if (EnglishUnix.is() &&
0N/A ! matches(m, "No such file"))
0N/A unexpected(e);
0N/A } catch (Throwable t) { unexpected(t); }
0N/A
0N/A // Can't execute a directory -- permission denied
0N/A // Report EACCES errno
0N/A new File("dir1/prog").mkdirs();
1270N/A checkPermissionDenied(pb);
0N/A
0N/A // continue searching if EACCES
0N/A copy("/bin/true", "dir2/prog");
1270N/A equal(run(pb).exitValue(), True.exitValue());
0N/A new File("dir1/prog").delete();
0N/A new File("dir2/prog").delete();
0N/A
0N/A new File("dir2/prog").mkdirs();
0N/A copy("/bin/true", "dir1/prog");
1270N/A equal(run(pb).exitValue(), True.exitValue());
0N/A
1270N/A // Check empty PATH component means current directory.
1270N/A //
1270N/A // While we're here, let's test different kinds of
1270N/A // Unix executables, and PATH vs explicit searching.
0N/A new File("dir1/prog").delete();
0N/A new File("dir2/prog").delete();
1270N/A for (String[] command :
1270N/A new String[][] {
1270N/A new String[] {"./prog"},
1270N/A cmd}) {
1270N/A pb.command(command);
1270N/A File prog = new File("./prog");
1270N/A // "Normal" binaries
1270N/A copy("/bin/true", "./prog");
1270N/A equal(run(pb).exitValue(),
1270N/A True.exitValue());
1270N/A copy("/bin/false", "./prog");
1270N/A equal(run(pb).exitValue(),
1270N/A False.exitValue());
1270N/A prog.delete();
1270N/A // Interpreter scripts with #!
1270N/A setFileContents(prog, "#!/bin/true\n");
1270N/A prog.setExecutable(true);
1270N/A equal(run(pb).exitValue(),
1270N/A True.exitValue());
1270N/A prog.delete();
1270N/A setFileContents(prog, "#!/bin/false\n");
1270N/A prog.setExecutable(true);
1270N/A equal(run(pb).exitValue(),
1270N/A False.exitValue());
1270N/A // Traditional shell scripts without #!
1270N/A setFileContents(prog, "exec /bin/true\n");
1270N/A prog.setExecutable(true);
1270N/A equal(run(pb).exitValue(),
1270N/A True.exitValue());
1270N/A prog.delete();
1270N/A setFileContents(prog, "exec /bin/false\n");
1270N/A prog.setExecutable(true);
1270N/A equal(run(pb).exitValue(),
1270N/A False.exitValue());
1270N/A prog.delete();
1270N/A }
1270N/A
1270N/A // Test Unix interpreter scripts
1270N/A File dir1Prog = new File("dir1/prog");
1270N/A dir1Prog.delete();
1270N/A pb.command(new String[] {"prog", "world"});
1270N/A setFileContents(dir1Prog, "#!/bin/echo hello\n");
1270N/A checkPermissionDenied(pb);
1270N/A dir1Prog.setExecutable(true);
1270N/A equal(run(pb).out(), "hello dir1/prog world\n");
1270N/A equal(run(pb).exitValue(), True.exitValue());
1270N/A dir1Prog.delete();
1270N/A pb.command(cmd);
1270N/A
1270N/A // Test traditional shell scripts without #!
1270N/A setFileContents(dir1Prog, "/bin/echo \"$@\"\n");
1270N/A pb.command(new String[] {"prog", "hello", "world"});
1270N/A checkPermissionDenied(pb);
1270N/A dir1Prog.setExecutable(true);
1270N/A equal(run(pb).out(), "hello world\n");
1270N/A equal(run(pb).exitValue(), True.exitValue());
1270N/A dir1Prog.delete();
1270N/A pb.command(cmd);
0N/A
0N/A // If prog found on both parent and child's PATH,
0N/A // parent's is used.
0N/A new File("dir1/prog").delete();
0N/A new File("dir2/prog").delete();
0N/A new File("prog").delete();
0N/A new File("dir3").mkdirs();
0N/A copy("/bin/true", "dir1/prog");
0N/A copy("/bin/false", "dir3/prog");
0N/A pb.environment().put("PATH","dir3");
1270N/A equal(run(pb).exitValue(), True.exitValue());
0N/A copy("/bin/true", "dir3/prog");
0N/A copy("/bin/false", "dir1/prog");
1270N/A equal(run(pb).exitValue(), False.exitValue());
0N/A
0N/A } finally {
0N/A // cleanup
0N/A new File("dir1/prog").delete();
0N/A new File("dir2/prog").delete();
0N/A new File("dir3/prog").delete();
0N/A new File("dir1").delete();
0N/A new File("dir2").delete();
0N/A new File("dir3").delete();
0N/A new File("prog").delete();
0N/A }
0N/A }
0N/A
0N/A if (failed != 0) throw new Error("PATH search algorithm");
0N/A }
0N/A else throw new Error("JavaChild invocation error");
0N/A }
0N/A }
0N/A
0N/A private static void copy(String src, String dst) {
0N/A system("/bin/cp", "-fp", src, dst);
0N/A }
0N/A
0N/A private static void system(String... command) {
0N/A try {
0N/A ProcessBuilder pb = new ProcessBuilder(command);
0N/A ProcessResults r = run(pb.start());
0N/A equal(r.exitValue(), 0);
0N/A equal(r.out(), "");
0N/A equal(r.err(), "");
0N/A } catch (Throwable t) { unexpected(t); }
0N/A }
0N/A
0N/A private static String javaChildOutput(ProcessBuilder pb, String...args) {
0N/A List<String> list = new ArrayList<String>(javaChildArgs);
0N/A for (String arg : args)
0N/A list.add(arg);
0N/A pb.command(list);
0N/A return commandOutput(pb);
0N/A }
0N/A
0N/A private static String getenvInChild(ProcessBuilder pb) {
0N/A return javaChildOutput(pb, "System.getenv()");
0N/A }
0N/A
0N/A private static String getenvInChild1234(ProcessBuilder pb) {
0N/A return javaChildOutput(pb, "System.getenv(\\u1234)");
0N/A }
0N/A
0N/A private static String getenvInChild(ProcessBuilder pb, String name) {
0N/A return javaChildOutput(pb, "System.getenv(String)", name);
0N/A }
0N/A
0N/A private static String pwdInChild(ProcessBuilder pb) {
0N/A return javaChildOutput(pb, "pwd");
0N/A }
0N/A
0N/A private static final String javaExe =
0N/A System.getProperty("java.home") +
0N/A File.separator + "bin" + File.separator + "java";
0N/A
0N/A private static final String classpath =
0N/A System.getProperty("java.class.path");
0N/A
0N/A private static final List<String> javaChildArgs =
0N/A Arrays.asList(new String[]
0N/A { javaExe, "-classpath", absolutifyPath(classpath),
0N/A "Basic$JavaChild"});
0N/A
0N/A private static void testEncoding(String encoding, String tested) {
0N/A try {
0N/A // If round trip conversion works, should be able to set env vars
0N/A // correctly in child.
0N/A if (new String(tested.getBytes()).equals(tested)) {
0N/A out.println("Testing " + encoding + " environment values");
0N/A ProcessBuilder pb = new ProcessBuilder();
0N/A pb.environment().put("ASCIINAME",tested);
0N/A equal(getenvInChild(pb,"ASCIINAME"), tested);
0N/A }
0N/A } catch (Throwable t) { unexpected(t); }
0N/A }
0N/A
0N/A static class Windows {
0N/A public static boolean is() { return is; }
0N/A private static final boolean is =
0N/A System.getProperty("os.name").startsWith("Windows");
0N/A }
0N/A
0N/A static class Unix {
0N/A public static boolean is() { return is; }
0N/A private static final boolean is =
0N/A (! Windows.is() &&
0N/A new File("/bin/sh").exists() &&
0N/A new File("/bin/true").exists() &&
0N/A new File("/bin/false").exists());
0N/A }
0N/A
0N/A static class UnicodeOS {
0N/A public static boolean is() { return is; }
0N/A private static final String osName = System.getProperty("os.name");
0N/A private static final boolean is =
0N/A // MacOS X would probably also qualify
0N/A osName.startsWith("Windows") &&
0N/A ! osName.startsWith("Windows 9") &&
0N/A ! osName.equals("Windows Me");
0N/A }
0N/A
4666N/A static class MacOSX {
4666N/A public static boolean is() { return is; }
4666N/A private static final String osName = System.getProperty("os.name");
4944N/A private static final boolean is = osName.contains("OS X");
4666N/A }
4666N/A
0N/A static class True {
0N/A public static int exitValue() { return 0; }
0N/A }
0N/A
0N/A private static class False {
0N/A public static int exitValue() { return exitValue; }
0N/A private static final int exitValue = exitValue0();
0N/A private static int exitValue0() {
0N/A // /bin/false returns an *unspecified* non-zero number.
0N/A try {
0N/A if (! Unix.is())
0N/A return -1;
0N/A else {
0N/A int rc = new ProcessBuilder("/bin/false")
0N/A .start().waitFor();
0N/A check(rc != 0);
0N/A return rc;
0N/A }
0N/A } catch (Throwable t) { unexpected(t); return -1; }
0N/A }
0N/A }
0N/A
0N/A static class EnglishUnix {
0N/A private final static Boolean is =
0N/A (! Windows.is() && isEnglish("LANG") && isEnglish("LC_ALL"));
0N/A
0N/A private static boolean isEnglish(String envvar) {
0N/A String val = getenv(envvar);
0N/A return (val == null) || val.matches("en.*");
0N/A }
0N/A
0N/A /** Returns true if we can expect English OS error strings */
0N/A static boolean is() { return is; }
0N/A }
0N/A
0N/A private static boolean matches(String str, String regex) {
0N/A return Pattern.compile(regex).matcher(str).find();
0N/A }
0N/A
4666N/A private static String matchAndExtract(String str, String regex) {
4666N/A Matcher matcher = Pattern.compile(regex).matcher(str);
4666N/A if (matcher.find()) {
4666N/A return matcher.group();
4666N/A } else {
4666N/A return "";
4666N/A }
4666N/A }
4666N/A
4666N/A /* Only used for Mac OS X --
4666N/A * Mac OS X adds the variable __CF_USER_TEXT_ENCODING to an empty
4666N/A * environment. The environment variable JAVA_MAIN_CLASS_<pid> should also
4666N/A * be set in Mac OS X.
4666N/A * Check for both by removing them both from the list of env variables.
4666N/A */
4666N/A private static String removeMacExpectedVars(String vars) {
4666N/A // Check for __CF_USER_TEXT_ENCODING
4666N/A String cleanedVars = vars.replace("__CF_USER_TEXT_ENCODING="
4666N/A +cfUserTextEncoding+",","");
4666N/A if (cleanedVars.equals(vars)) {
4666N/A fail("Environment variable __CF_USER_TEXT_ENCODING not set. "
4666N/A + "MAC OS X should set __CF_USER_TEXT_ENCODING in "
4666N/A + "an empty environment.");
4666N/A }
4666N/A
4666N/A // Check for JAVA_MAIN_CLASS_<pid>
4666N/A String javaMainClassStr
4666N/A = matchAndExtract(cleanedVars,
4666N/A "JAVA_MAIN_CLASS_\\d+=Basic.JavaChild,");
4666N/A if (javaMainClassStr.equals("")) {
4666N/A fail("JAVA_MAIN_CLASS_<pid> not set. "
4666N/A + "Should be set in Mac OS X env.");
4666N/A }
4666N/A return cleanedVars.replace(javaMainClassStr,"");
4666N/A }
4666N/A
0N/A private static String sortByLinesWindowsly(String text) {
0N/A String[] lines = text.split("\n");
0N/A Arrays.sort(lines, new WindowsComparator());
0N/A StringBuilder sb = new StringBuilder();
0N/A for (String line : lines)
0N/A sb.append(line).append("\n");
0N/A return sb.toString();
0N/A }
0N/A
0N/A private static void checkMapSanity(Map<String,String> map) {
0N/A try {
0N/A Set<String> keySet = map.keySet();
0N/A Collection<String> values = map.values();
0N/A Set<Map.Entry<String,String>> entrySet = map.entrySet();
0N/A
0N/A equal(entrySet.size(), keySet.size());
0N/A equal(entrySet.size(), values.size());
0N/A
0N/A StringBuilder s1 = new StringBuilder();
0N/A for (Map.Entry<String,String> e : entrySet)
0N/A s1.append(e.getKey() + "=" + e.getValue() + "\n");
0N/A
0N/A StringBuilder s2 = new StringBuilder();
0N/A for (String var : keySet)
0N/A s2.append(var + "=" + map.get(var) + "\n");
0N/A
0N/A equal(s1.toString(), s2.toString());
0N/A
0N/A Iterator<String> kIter = keySet.iterator();
0N/A Iterator<String> vIter = values.iterator();
0N/A Iterator<Map.Entry<String,String>> eIter = entrySet.iterator();
0N/A
0N/A while (eIter.hasNext()) {
0N/A Map.Entry<String,String> entry = eIter.next();
0N/A String key = kIter.next();
0N/A String value = vIter.next();
0N/A check(entrySet.contains(entry));
0N/A check(keySet.contains(key));
0N/A check(values.contains(value));
0N/A check(map.containsKey(key));
0N/A check(map.containsValue(value));
0N/A equal(entry.getKey(), key);
0N/A equal(entry.getValue(), value);
0N/A }
0N/A check(! kIter.hasNext() &&
0N/A ! vIter.hasNext());
0N/A
0N/A } catch (Throwable t) { unexpected(t); }
0N/A }
0N/A
0N/A private static void checkMapEquality(Map<String,String> map1,
0N/A Map<String,String> map2) {
0N/A try {
0N/A equal(map1.size(), map2.size());
0N/A equal(map1.isEmpty(), map2.isEmpty());
0N/A for (String key : map1.keySet()) {
0N/A equal(map1.get(key), map2.get(key));
0N/A check(map2.keySet().contains(key));
0N/A }
0N/A equal(map1, map2);
0N/A equal(map2, map1);
0N/A equal(map1.entrySet(), map2.entrySet());
0N/A equal(map2.entrySet(), map1.entrySet());
0N/A equal(map1.keySet(), map2.keySet());
0N/A equal(map2.keySet(), map1.keySet());
0N/A
0N/A equal(map1.hashCode(), map2.hashCode());
0N/A equal(map1.entrySet().hashCode(), map2.entrySet().hashCode());
0N/A equal(map1.keySet().hashCode(), map2.keySet().hashCode());
0N/A } catch (Throwable t) { unexpected(t); }
0N/A }
0N/A
25N/A static void checkRedirects(ProcessBuilder pb,
25N/A Redirect in, Redirect out, Redirect err) {
25N/A equal(pb.redirectInput(), in);
25N/A equal(pb.redirectOutput(), out);
25N/A equal(pb.redirectError(), err);
25N/A }
25N/A
25N/A static void redirectIO(ProcessBuilder pb,
25N/A Redirect in, Redirect out, Redirect err) {
25N/A pb.redirectInput(in);
25N/A pb.redirectOutput(out);
25N/A pb.redirectError(err);
25N/A }
25N/A
25N/A static void setFileContents(File file, String contents) {
25N/A try {
25N/A Writer w = new FileWriter(file);
25N/A w.write(contents);
25N/A w.close();
25N/A } catch (Throwable t) { unexpected(t); }
25N/A }
25N/A
25N/A static String fileContents(File file) {
25N/A try {
25N/A Reader r = new FileReader(file);
25N/A StringBuilder sb = new StringBuilder();
25N/A char[] buffer = new char[1024];
25N/A int n;
25N/A while ((n = r.read(buffer)) != -1)
25N/A sb.append(buffer,0,n);
25N/A r.close();
25N/A return new String(sb);
25N/A } catch (Throwable t) { unexpected(t); return ""; }
25N/A }
25N/A
25N/A static void testIORedirection() throws Throwable {
25N/A final File ifile = new File("ifile");
25N/A final File ofile = new File("ofile");
25N/A final File efile = new File("efile");
25N/A ifile.delete();
25N/A ofile.delete();
25N/A efile.delete();
25N/A
25N/A //----------------------------------------------------------------
25N/A // Check mutual inequality of different types of Redirect
25N/A //----------------------------------------------------------------
25N/A Redirect[] redirects =
25N/A { PIPE,
25N/A INHERIT,
25N/A Redirect.from(ifile),
25N/A Redirect.to(ifile),
25N/A Redirect.appendTo(ifile),
25N/A Redirect.from(ofile),
25N/A Redirect.to(ofile),
25N/A Redirect.appendTo(ofile),
25N/A };
25N/A for (int i = 0; i < redirects.length; i++)
25N/A for (int j = 0; j < redirects.length; j++)
25N/A equal(redirects[i].equals(redirects[j]), (i == j));
25N/A
25N/A //----------------------------------------------------------------
25N/A // Check basic properties of different types of Redirect
25N/A //----------------------------------------------------------------
25N/A equal(PIPE.type(), Redirect.Type.PIPE);
25N/A equal(PIPE.toString(), "PIPE");
25N/A equal(PIPE.file(), null);
25N/A
25N/A equal(INHERIT.type(), Redirect.Type.INHERIT);
25N/A equal(INHERIT.toString(), "INHERIT");
25N/A equal(INHERIT.file(), null);
25N/A
25N/A equal(Redirect.from(ifile).type(), Redirect.Type.READ);
25N/A equal(Redirect.from(ifile).toString(),
25N/A "redirect to read from file \"ifile\"");
25N/A equal(Redirect.from(ifile).file(), ifile);
25N/A equal(Redirect.from(ifile),
25N/A Redirect.from(ifile));
25N/A equal(Redirect.from(ifile).hashCode(),
25N/A Redirect.from(ifile).hashCode());
25N/A
25N/A equal(Redirect.to(ofile).type(), Redirect.Type.WRITE);
25N/A equal(Redirect.to(ofile).toString(),
25N/A "redirect to write to file \"ofile\"");
25N/A equal(Redirect.to(ofile).file(), ofile);
25N/A equal(Redirect.to(ofile),
25N/A Redirect.to(ofile));
25N/A equal(Redirect.to(ofile).hashCode(),
25N/A Redirect.to(ofile).hashCode());
25N/A
25N/A equal(Redirect.appendTo(ofile).type(), Redirect.Type.APPEND);
25N/A equal(Redirect.appendTo(efile).toString(),
25N/A "redirect to append to file \"efile\"");
25N/A equal(Redirect.appendTo(efile).file(), efile);
25N/A equal(Redirect.appendTo(efile),
25N/A Redirect.appendTo(efile));
25N/A equal(Redirect.appendTo(efile).hashCode(),
25N/A Redirect.appendTo(efile).hashCode());
25N/A
25N/A //----------------------------------------------------------------
25N/A // Check initial values of redirects
25N/A //----------------------------------------------------------------
25N/A List<String> childArgs = new ArrayList<String>(javaChildArgs);
25N/A childArgs.add("testIO");
25N/A final ProcessBuilder pb = new ProcessBuilder(childArgs);
25N/A checkRedirects(pb, PIPE, PIPE, PIPE);
25N/A
25N/A //----------------------------------------------------------------
25N/A // Check inheritIO
25N/A //----------------------------------------------------------------
25N/A pb.inheritIO();
25N/A checkRedirects(pb, INHERIT, INHERIT, INHERIT);
25N/A
25N/A //----------------------------------------------------------------
25N/A // Check setters and getters agree
25N/A //----------------------------------------------------------------
25N/A pb.redirectInput(ifile);
25N/A equal(pb.redirectInput().file(), ifile);
25N/A equal(pb.redirectInput(), Redirect.from(ifile));
25N/A
25N/A pb.redirectOutput(ofile);
25N/A equal(pb.redirectOutput().file(), ofile);
25N/A equal(pb.redirectOutput(), Redirect.to(ofile));
25N/A
25N/A pb.redirectError(efile);
25N/A equal(pb.redirectError().file(), efile);
25N/A equal(pb.redirectError(), Redirect.to(efile));
25N/A
25N/A THROWS(IllegalArgumentException.class,
25N/A new Fun(){void f() {
25N/A pb.redirectInput(Redirect.to(ofile)); }},
25N/A new Fun(){void f() {
25N/A pb.redirectInput(Redirect.appendTo(ofile)); }},
25N/A new Fun(){void f() {
25N/A pb.redirectOutput(Redirect.from(ifile)); }},
25N/A new Fun(){void f() {
25N/A pb.redirectError(Redirect.from(ifile)); }});
25N/A
25N/A THROWS(IOException.class,
25N/A // Input file does not exist
25N/A new Fun(){void f() throws Throwable { pb.start(); }});
25N/A setFileContents(ifile, "standard input");
25N/A
25N/A //----------------------------------------------------------------
25N/A // Writing to non-existent files
25N/A //----------------------------------------------------------------
25N/A {
25N/A ProcessResults r = run(pb);
25N/A equal(r.exitValue(), 0);
25N/A equal(fileContents(ofile), "standard output");
25N/A equal(fileContents(efile), "standard error");
25N/A equal(r.out(), "");
25N/A equal(r.err(), "");
25N/A ofile.delete();
25N/A efile.delete();
25N/A }
25N/A
25N/A //----------------------------------------------------------------
25N/A // Both redirectErrorStream + redirectError
25N/A //----------------------------------------------------------------
25N/A {
25N/A pb.redirectErrorStream(true);
25N/A ProcessResults r = run(pb);
25N/A equal(r.exitValue(), 0);
25N/A equal(fileContents(ofile),
25N/A "standard error" + "standard output");
25N/A equal(fileContents(efile), "");
25N/A equal(r.out(), "");
25N/A equal(r.err(), "");
25N/A ofile.delete();
25N/A efile.delete();
25N/A }
25N/A
25N/A //----------------------------------------------------------------
25N/A // Appending to existing files
25N/A //----------------------------------------------------------------
25N/A {
25N/A setFileContents(ofile, "ofile-contents");
25N/A setFileContents(efile, "efile-contents");
25N/A pb.redirectOutput(Redirect.appendTo(ofile));
25N/A pb.redirectError(Redirect.appendTo(efile));
25N/A pb.redirectErrorStream(false);
25N/A ProcessResults r = run(pb);
25N/A equal(r.exitValue(), 0);
25N/A equal(fileContents(ofile),
25N/A "ofile-contents" + "standard output");
25N/A equal(fileContents(efile),
25N/A "efile-contents" + "standard error");
25N/A equal(r.out(), "");
25N/A equal(r.err(), "");
25N/A ofile.delete();
25N/A efile.delete();
25N/A }
25N/A
25N/A //----------------------------------------------------------------
25N/A // Replacing existing files
25N/A //----------------------------------------------------------------
25N/A {
25N/A setFileContents(ofile, "ofile-contents");
25N/A setFileContents(efile, "efile-contents");
25N/A pb.redirectOutput(ofile);
25N/A pb.redirectError(Redirect.to(efile));
25N/A ProcessResults r = run(pb);
25N/A equal(r.exitValue(), 0);
25N/A equal(fileContents(ofile), "standard output");
25N/A equal(fileContents(efile), "standard error");
25N/A equal(r.out(), "");
25N/A equal(r.err(), "");
25N/A ofile.delete();
25N/A efile.delete();
25N/A }
25N/A
25N/A //----------------------------------------------------------------
25N/A // Appending twice to the same file?
25N/A //----------------------------------------------------------------
25N/A {
25N/A setFileContents(ofile, "ofile-contents");
25N/A setFileContents(efile, "efile-contents");
25N/A Redirect appender = Redirect.appendTo(ofile);
25N/A pb.redirectOutput(appender);
25N/A pb.redirectError(appender);
25N/A ProcessResults r = run(pb);
25N/A equal(r.exitValue(), 0);
25N/A equal(fileContents(ofile),
25N/A "ofile-contents" +
25N/A "standard error" +
25N/A "standard output");
25N/A equal(fileContents(efile), "efile-contents");
25N/A equal(r.out(), "");
25N/A equal(r.err(), "");
25N/A ifile.delete();
25N/A ofile.delete();
25N/A efile.delete();
25N/A }
25N/A
25N/A //----------------------------------------------------------------
25N/A // Testing INHERIT is harder.
25N/A // Note that this requires __FOUR__ nested JVMs involved in one test,
25N/A // if you count the harness JVM.
25N/A //----------------------------------------------------------------
25N/A {
25N/A redirectIO(pb, PIPE, PIPE, PIPE);
25N/A List<String> command = pb.command();
25N/A command.set(command.size() - 1, "testInheritIO");
25N/A Process p = pb.start();
25N/A new PrintStream(p.getOutputStream()).print("standard input");
25N/A p.getOutputStream().close();
25N/A ProcessResults r = run(p);
25N/A equal(r.exitValue(), 0);
25N/A equal(r.out(), "standard output");
25N/A equal(r.err(), "standard error");
25N/A }
25N/A
25N/A //----------------------------------------------------------------
25N/A // Test security implications of I/O redirection
25N/A //----------------------------------------------------------------
25N/A
25N/A // Read access to current directory is always granted;
25N/A // So create a tmpfile for input instead.
25N/A final File tmpFile = File.createTempFile("Basic", "tmp");
25N/A setFileContents(tmpFile, "standard input");
25N/A
25N/A final Policy policy = new Policy();
25N/A Policy.setPolicy(policy);
25N/A System.setSecurityManager(new SecurityManager());
25N/A try {
25N/A final Permission xPermission
25N/A = new FilePermission("<<ALL FILES>>", "execute");
25N/A final Permission rxPermission
25N/A = new FilePermission("<<ALL FILES>>", "read,execute");
25N/A final Permission wxPermission
25N/A = new FilePermission("<<ALL FILES>>", "write,execute");
25N/A final Permission rwxPermission
25N/A = new FilePermission("<<ALL FILES>>", "read,write,execute");
25N/A
25N/A THROWS(SecurityException.class,
25N/A new Fun() { void f() throws IOException {
25N/A policy.setPermissions(xPermission);
25N/A redirectIO(pb, from(tmpFile), PIPE, PIPE);
25N/A pb.start();}},
25N/A new Fun() { void f() throws IOException {
25N/A policy.setPermissions(rxPermission);
25N/A redirectIO(pb, PIPE, to(ofile), PIPE);
25N/A pb.start();}},
25N/A new Fun() { void f() throws IOException {
25N/A policy.setPermissions(rxPermission);
25N/A redirectIO(pb, PIPE, PIPE, to(efile));
25N/A pb.start();}});
25N/A
25N/A {
25N/A policy.setPermissions(rxPermission);
25N/A redirectIO(pb, from(tmpFile), PIPE, PIPE);
25N/A ProcessResults r = run(pb);
25N/A equal(r.out(), "standard output");
25N/A equal(r.err(), "standard error");
25N/A }
25N/A
25N/A {
25N/A policy.setPermissions(wxPermission);
25N/A redirectIO(pb, PIPE, to(ofile), to(efile));
25N/A Process p = pb.start();
25N/A new PrintStream(p.getOutputStream()).print("standard input");
25N/A p.getOutputStream().close();
25N/A ProcessResults r = run(p);
25N/A policy.setPermissions(rwxPermission);
25N/A equal(fileContents(ofile), "standard output");
25N/A equal(fileContents(efile), "standard error");
25N/A }
25N/A
25N/A {
25N/A policy.setPermissions(rwxPermission);
25N/A redirectIO(pb, from(tmpFile), to(ofile), to(efile));
25N/A ProcessResults r = run(pb);
25N/A policy.setPermissions(rwxPermission);
25N/A equal(fileContents(ofile), "standard output");
25N/A equal(fileContents(efile), "standard error");
25N/A }
25N/A
25N/A } finally {
25N/A policy.setPermissions(new RuntimePermission("setSecurityManager"));
25N/A System.setSecurityManager(null);
25N/A tmpFile.delete();
25N/A ifile.delete();
25N/A ofile.delete();
25N/A efile.delete();
25N/A }
25N/A }
25N/A
0N/A private static void realMain(String[] args) throws Throwable {
0N/A if (Windows.is())
0N/A System.out.println("This appears to be a Windows system.");
0N/A if (Unix.is())
0N/A System.out.println("This appears to be a Unix system.");
0N/A if (UnicodeOS.is())
0N/A System.out.println("This appears to be a Unicode-based OS.");
0N/A
25N/A try { testIORedirection(); }
25N/A catch (Throwable t) { unexpected(t); }
25N/A
0N/A //----------------------------------------------------------------
0N/A // Basic tests for setting, replacing and deleting envvars
0N/A //----------------------------------------------------------------
0N/A try {
0N/A ProcessBuilder pb = new ProcessBuilder();
0N/A Map<String,String> environ = pb.environment();
0N/A
0N/A // New env var
0N/A environ.put("QUUX", "BAR");
0N/A equal(environ.get("QUUX"), "BAR");
0N/A equal(getenvInChild(pb,"QUUX"), "BAR");
0N/A
0N/A // Modify env var
0N/A environ.put("QUUX","bear");
0N/A equal(environ.get("QUUX"), "bear");
0N/A equal(getenvInChild(pb,"QUUX"), "bear");
0N/A checkMapSanity(environ);
0N/A
0N/A // Remove env var
0N/A environ.remove("QUUX");
0N/A equal(environ.get("QUUX"), null);
0N/A equal(getenvInChild(pb,"QUUX"), "null");
0N/A checkMapSanity(environ);
0N/A
0N/A // Remove non-existent env var
0N/A environ.remove("QUUX");
0N/A equal(environ.get("QUUX"), null);
0N/A equal(getenvInChild(pb,"QUUX"), "null");
0N/A checkMapSanity(environ);
0N/A } catch (Throwable t) { unexpected(t); }
0N/A
0N/A //----------------------------------------------------------------
0N/A // Pass Empty environment to child
0N/A //----------------------------------------------------------------
0N/A try {
0N/A ProcessBuilder pb = new ProcessBuilder();
0N/A pb.environment().clear();
3664N/A String expected = Windows.is() ? "SystemRoot="+systemRoot+",": "";
3664N/A if (Windows.is()) {
3664N/A pb.environment().put("SystemRoot", systemRoot);
3664N/A }
4666N/A String result = getenvInChild(pb);
4666N/A if (MacOSX.is()) {
4666N/A result = removeMacExpectedVars(result);
4666N/A }
4666N/A equal(result, expected);
0N/A } catch (Throwable t) { unexpected(t); }
0N/A
0N/A //----------------------------------------------------------------
0N/A // System.getenv() is read-only.
0N/A //----------------------------------------------------------------
0N/A THROWS(UnsupportedOperationException.class,
0N/A new Fun(){void f(){ getenv().put("FOO","BAR");}},
0N/A new Fun(){void f(){ getenv().remove("PATH");}},
0N/A new Fun(){void f(){ getenv().keySet().remove("PATH");}},
0N/A new Fun(){void f(){ getenv().values().remove("someValue");}});
0N/A
0N/A try {
0N/A Collection<Map.Entry<String,String>> c = getenv().entrySet();
0N/A if (! c.isEmpty())
0N/A try {
0N/A c.iterator().next().setValue("foo");
0N/A fail("Expected UnsupportedOperationException not thrown");
0N/A } catch (UnsupportedOperationException e) {} // OK
0N/A } catch (Throwable t) { unexpected(t); }
0N/A
0N/A //----------------------------------------------------------------
0N/A // System.getenv() always returns the same object in our implementation.
0N/A //----------------------------------------------------------------
0N/A try {
0N/A check(System.getenv() == System.getenv());
0N/A } catch (Throwable t) { unexpected(t); }
0N/A
0N/A //----------------------------------------------------------------
0N/A // You can't create an env var name containing "=",
0N/A // or an env var name or value containing NUL.
0N/A //----------------------------------------------------------------
0N/A {
0N/A final Map<String,String> m = new ProcessBuilder().environment();
0N/A THROWS(IllegalArgumentException.class,
0N/A new Fun(){void f(){ m.put("FOO=","BAR");}},
0N/A new Fun(){void f(){ m.put("FOO\u0000","BAR");}},
0N/A new Fun(){void f(){ m.put("FOO","BAR\u0000");}});
0N/A }
0N/A
0N/A //----------------------------------------------------------------
0N/A // Commands must never be null.
0N/A //----------------------------------------------------------------
0N/A THROWS(NullPointerException.class,
0N/A new Fun(){void f(){
0N/A new ProcessBuilder((List<String>)null);}},
0N/A new Fun(){void f(){
0N/A new ProcessBuilder().command((List<String>)null);}});
0N/A
0N/A //----------------------------------------------------------------
0N/A // Put in a command; get the same one back out.
0N/A //----------------------------------------------------------------
0N/A try {
0N/A List<String> command = new ArrayList<String>();
0N/A ProcessBuilder pb = new ProcessBuilder(command);
0N/A check(pb.command() == command);
0N/A List<String> command2 = new ArrayList<String>(2);
0N/A command2.add("foo");
0N/A command2.add("bar");
0N/A pb.command(command2);
0N/A check(pb.command() == command2);
0N/A pb.command("foo", "bar");
0N/A check(pb.command() != command2 && pb.command().equals(command2));
0N/A pb.command(command2);
0N/A command2.add("baz");
0N/A equal(pb.command().get(2), "baz");
0N/A } catch (Throwable t) { unexpected(t); }
0N/A
0N/A //----------------------------------------------------------------
0N/A // Commands must contain at least one element.
0N/A //----------------------------------------------------------------
0N/A THROWS(IndexOutOfBoundsException.class,
0N/A new Fun() { void f() throws IOException {
0N/A new ProcessBuilder().start();}},
0N/A new Fun() { void f() throws IOException {
0N/A new ProcessBuilder(new ArrayList<String>()).start();}},
0N/A new Fun() { void f() throws IOException {
0N/A Runtime.getRuntime().exec(new String[]{});}});
0N/A
0N/A //----------------------------------------------------------------
0N/A // Commands must not contain null elements at start() time.
0N/A //----------------------------------------------------------------
0N/A THROWS(NullPointerException.class,
0N/A new Fun() { void f() throws IOException {
0N/A new ProcessBuilder("foo",null,"bar").start();}},
0N/A new Fun() { void f() throws IOException {
0N/A new ProcessBuilder((String)null).start();}},
0N/A new Fun() { void f() throws IOException {
0N/A new ProcessBuilder(new String[]{null}).start();}},
0N/A new Fun() { void f() throws IOException {
0N/A new ProcessBuilder(new String[]{"foo",null,"bar"}).start();}});
0N/A
0N/A //----------------------------------------------------------------
0N/A // Command lists are growable.
0N/A //----------------------------------------------------------------
0N/A try {
0N/A new ProcessBuilder().command().add("foo");
0N/A new ProcessBuilder("bar").command().add("foo");
0N/A new ProcessBuilder(new String[]{"1","2"}).command().add("3");
0N/A } catch (Throwable t) { unexpected(t); }
0N/A
0N/A //----------------------------------------------------------------
0N/A // Nulls in environment updates generate NullPointerException
0N/A //----------------------------------------------------------------
0N/A try {
0N/A final Map<String,String> env = new ProcessBuilder().environment();
0N/A THROWS(NullPointerException.class,
0N/A new Fun(){void f(){ env.put("foo",null);}},
0N/A new Fun(){void f(){ env.put(null,"foo");}},
0N/A new Fun(){void f(){ env.remove(null);}},
0N/A new Fun(){void f(){
0N/A for (Map.Entry<String,String> e : env.entrySet())
0N/A e.setValue(null);}},
0N/A new Fun() { void f() throws IOException {
0N/A Runtime.getRuntime().exec(new String[]{"foo"},
0N/A new String[]{null});}});
0N/A } catch (Throwable t) { unexpected(t); }
0N/A
0N/A //----------------------------------------------------------------
0N/A // Non-String types in environment updates generate ClassCastException
0N/A //----------------------------------------------------------------
0N/A try {
0N/A final Map<String,String> env = new ProcessBuilder().environment();
0N/A THROWS(ClassCastException.class,
0N/A new Fun(){void f(){ env.remove(TRUE);}},
0N/A new Fun(){void f(){ env.keySet().remove(TRUE);}},
0N/A new Fun(){void f(){ env.values().remove(TRUE);}},
0N/A new Fun(){void f(){ env.entrySet().remove(TRUE);}});
0N/A } catch (Throwable t) { unexpected(t); }
0N/A
0N/A //----------------------------------------------------------------
0N/A // Check query operations on environment maps
0N/A //----------------------------------------------------------------
0N/A try {
0N/A List<Map<String,String>> envs =
0N/A new ArrayList<Map<String,String>>(2);
0N/A envs.add(System.getenv());
0N/A envs.add(new ProcessBuilder().environment());
0N/A for (final Map<String,String> env : envs) {
0N/A //----------------------------------------------------------------
0N/A // Nulls in environment queries are forbidden.
0N/A //----------------------------------------------------------------
0N/A THROWS(NullPointerException.class,
0N/A new Fun(){void f(){ getenv(null);}},
0N/A new Fun(){void f(){ env.get(null);}},
0N/A new Fun(){void f(){ env.containsKey(null);}},
0N/A new Fun(){void f(){ env.containsValue(null);}},
0N/A new Fun(){void f(){ env.keySet().contains(null);}},
0N/A new Fun(){void f(){ env.values().contains(null);}});
0N/A
0N/A //----------------------------------------------------------------
0N/A // Non-String types in environment queries are forbidden.
0N/A //----------------------------------------------------------------
0N/A THROWS(ClassCastException.class,
0N/A new Fun(){void f(){ env.get(TRUE);}},
0N/A new Fun(){void f(){ env.containsKey(TRUE);}},
0N/A new Fun(){void f(){ env.containsValue(TRUE);}},
0N/A new Fun(){void f(){ env.keySet().contains(TRUE);}},
0N/A new Fun(){void f(){ env.values().contains(TRUE);}});
0N/A
0N/A //----------------------------------------------------------------
0N/A // Illegal String values in environment queries are (grumble) OK
0N/A //----------------------------------------------------------------
0N/A equal(env.get("\u0000"), null);
0N/A check(! env.containsKey("\u0000"));
0N/A check(! env.containsValue("\u0000"));
0N/A check(! env.keySet().contains("\u0000"));
0N/A check(! env.values().contains("\u0000"));
0N/A }
0N/A
0N/A } catch (Throwable t) { unexpected(t); }
0N/A
0N/A try {
0N/A final Set<Map.Entry<String,String>> entrySet =
0N/A new ProcessBuilder().environment().entrySet();
0N/A THROWS(NullPointerException.class,
0N/A new Fun(){void f(){ entrySet.contains(null);}});
0N/A THROWS(ClassCastException.class,
0N/A new Fun(){void f(){ entrySet.contains(TRUE);}},
0N/A new Fun(){void f(){
0N/A entrySet.contains(
0N/A new SimpleImmutableEntry<Boolean,String>(TRUE,""));}});
0N/A
0N/A check(! entrySet.contains
0N/A (new SimpleImmutableEntry<String,String>("", "")));
0N/A } catch (Throwable t) { unexpected(t); }
0N/A
0N/A //----------------------------------------------------------------
0N/A // Put in a directory; get the same one back out.
0N/A //----------------------------------------------------------------
0N/A try {
0N/A ProcessBuilder pb = new ProcessBuilder();
0N/A File foo = new File("foo");
0N/A equal(pb.directory(), null);
0N/A equal(pb.directory(foo).directory(), foo);
0N/A equal(pb.directory(null).directory(), null);
0N/A } catch (Throwable t) { unexpected(t); }
0N/A
0N/A //----------------------------------------------------------------
0N/A // If round-trip conversion works, check envvar pass-through to child
0N/A //----------------------------------------------------------------
0N/A try {
0N/A testEncoding("ASCII", "xyzzy");
0N/A testEncoding("Latin1", "\u00f1\u00e1");
0N/A testEncoding("Unicode", "\u22f1\u11e1");
0N/A } catch (Throwable t) { unexpected(t); }
0N/A
0N/A //----------------------------------------------------------------
0N/A // A surprisingly large number of ways to delete an environment var.
0N/A //----------------------------------------------------------------
0N/A testVariableDeleter(new EnvironmentFrobber() {
0N/A public void doIt(Map<String,String> environ) {
0N/A environ.remove("Foo");}});
0N/A
0N/A testVariableDeleter(new EnvironmentFrobber() {
0N/A public void doIt(Map<String,String> environ) {
0N/A environ.keySet().remove("Foo");}});
0N/A
0N/A testVariableDeleter(new EnvironmentFrobber() {
0N/A public void doIt(Map<String,String> environ) {
0N/A environ.values().remove("BAAR");}});
0N/A
0N/A testVariableDeleter(new EnvironmentFrobber() {
0N/A public void doIt(Map<String,String> environ) {
0N/A // Legally fabricate a ProcessEnvironment.StringEntry,
0N/A // even though it's private.
0N/A Map<String,String> environ2
0N/A = new ProcessBuilder().environment();
0N/A environ2.clear();
0N/A environ2.put("Foo","BAAR");
0N/A // Subtlety alert.
0N/A Map.Entry<String,String> e
0N/A = environ2.entrySet().iterator().next();
0N/A environ.entrySet().remove(e);}});
0N/A
0N/A testVariableDeleter(new EnvironmentFrobber() {
0N/A public void doIt(Map<String,String> environ) {
0N/A Map.Entry<String,String> victim = null;
0N/A for (Map.Entry<String,String> e : environ.entrySet())
0N/A if (e.getKey().equals("Foo"))
0N/A victim = e;
0N/A if (victim != null)
0N/A environ.entrySet().remove(victim);}});
0N/A
0N/A testVariableDeleter(new EnvironmentFrobber() {
0N/A public void doIt(Map<String,String> environ) {
0N/A Iterator<String> it = environ.keySet().iterator();
0N/A while (it.hasNext()) {
0N/A String val = it.next();
0N/A if (val.equals("Foo"))
0N/A it.remove();}}});
0N/A
0N/A testVariableDeleter(new EnvironmentFrobber() {
0N/A public void doIt(Map<String,String> environ) {
0N/A Iterator<Map.Entry<String,String>> it
0N/A = environ.entrySet().iterator();
0N/A while (it.hasNext()) {
0N/A Map.Entry<String,String> e = it.next();
0N/A if (e.getKey().equals("Foo"))
0N/A it.remove();}}});
0N/A
0N/A testVariableDeleter(new EnvironmentFrobber() {
0N/A public void doIt(Map<String,String> environ) {
0N/A Iterator<String> it = environ.values().iterator();
0N/A while (it.hasNext()) {
0N/A String val = it.next();
0N/A if (val.equals("BAAR"))
0N/A it.remove();}}});
0N/A
0N/A //----------------------------------------------------------------
0N/A // A surprisingly small number of ways to add an environment var.
0N/A //----------------------------------------------------------------
0N/A testVariableAdder(new EnvironmentFrobber() {
0N/A public void doIt(Map<String,String> environ) {
0N/A environ.put("Foo","Bahrein");}});
0N/A
0N/A //----------------------------------------------------------------
0N/A // A few ways to modify an environment var.
0N/A //----------------------------------------------------------------
0N/A testVariableModifier(new EnvironmentFrobber() {
0N/A public void doIt(Map<String,String> environ) {
0N/A environ.put("Foo","NewValue");}});
0N/A
0N/A testVariableModifier(new EnvironmentFrobber() {
0N/A public void doIt(Map<String,String> environ) {
0N/A for (Map.Entry<String,String> e : environ.entrySet())
0N/A if (e.getKey().equals("Foo"))
0N/A e.setValue("NewValue");}});
0N/A
0N/A //----------------------------------------------------------------
0N/A // Fiddle with environment sizes
0N/A //----------------------------------------------------------------
0N/A try {
0N/A Map<String,String> environ = new ProcessBuilder().environment();
0N/A int size = environ.size();
0N/A checkSizes(environ, size);
0N/A
0N/A environ.put("UnLiKeLYeNVIROmtNam", "someVal");
0N/A checkSizes(environ, size+1);
0N/A
0N/A // Check for environment independence
0N/A new ProcessBuilder().environment().clear();
0N/A
0N/A environ.put("UnLiKeLYeNVIROmtNam", "someOtherVal");
0N/A checkSizes(environ, size+1);
0N/A
0N/A environ.remove("UnLiKeLYeNVIROmtNam");
0N/A checkSizes(environ, size);
0N/A
0N/A environ.clear();
0N/A checkSizes(environ, 0);
0N/A
0N/A environ.clear();
0N/A checkSizes(environ, 0);
0N/A
0N/A environ = new ProcessBuilder().environment();
0N/A environ.keySet().clear();
0N/A checkSizes(environ, 0);
0N/A
0N/A environ = new ProcessBuilder().environment();
0N/A environ.entrySet().clear();
0N/A checkSizes(environ, 0);
0N/A
0N/A environ = new ProcessBuilder().environment();
0N/A environ.values().clear();
0N/A checkSizes(environ, 0);
0N/A } catch (Throwable t) { unexpected(t); }
0N/A
0N/A //----------------------------------------------------------------
0N/A // Check that various map invariants hold
0N/A //----------------------------------------------------------------
0N/A checkMapSanity(new ProcessBuilder().environment());
0N/A checkMapSanity(System.getenv());
0N/A checkMapEquality(new ProcessBuilder().environment(),
0N/A new ProcessBuilder().environment());
0N/A
0N/A
0N/A //----------------------------------------------------------------
0N/A // Check effects on external "env" command.
0N/A //----------------------------------------------------------------
0N/A try {
0N/A Set<String> env1 = new HashSet<String>
0N/A (Arrays.asList(nativeEnv((String[])null).split("\n")));
0N/A
0N/A ProcessBuilder pb = new ProcessBuilder();
0N/A pb.environment().put("QwErTyUiOp","AsDfGhJk");
0N/A
0N/A Set<String> env2 = new HashSet<String>
0N/A (Arrays.asList(nativeEnv(pb).split("\n")));
0N/A
0N/A check(env2.size() == env1.size() + 1);
0N/A env1.add("QwErTyUiOp=AsDfGhJk");
0N/A check(env1.equals(env2));
0N/A } catch (Throwable t) { unexpected(t); }
0N/A
0N/A //----------------------------------------------------------------
0N/A // Test Runtime.exec(...envp...)
0N/A // Check for sort order of environment variables on Windows.
0N/A //----------------------------------------------------------------
0N/A try {
4103N/A String systemRoot = "SystemRoot=" + System.getenv("SystemRoot");
0N/A // '+' < 'A' < 'Z' < '_' < 'a' < 'z' < '~'
0N/A String[]envp = {"FOO=BAR","BAZ=GORP","QUUX=",
4103N/A "+=+", "_=_", "~=~", systemRoot};
0N/A String output = nativeEnv(envp);
4103N/A String expected = "+=+\nBAZ=GORP\nFOO=BAR\nQUUX=\n"+systemRoot+"\n_=_\n~=~\n";
0N/A // On Windows, Java must keep the environment sorted.
0N/A // Order is random on Unix, so this test does the sort.
0N/A if (! Windows.is())
0N/A output = sortByLinesWindowsly(output);
0N/A equal(output, expected);
0N/A } catch (Throwable t) { unexpected(t); }
0N/A
0N/A //----------------------------------------------------------------
4103N/A // Test Runtime.exec(...envp...)
4103N/A // and check SystemRoot gets set automatically on Windows
4103N/A //----------------------------------------------------------------
4103N/A try {
4103N/A if (Windows.is()) {
4103N/A String systemRoot = "SystemRoot=" + System.getenv("SystemRoot");
4103N/A String[]envp = {"FOO=BAR","BAZ=GORP","QUUX=",
4103N/A "+=+", "_=_", "~=~"};
4103N/A String output = nativeEnv(envp);
4103N/A String expected = "+=+\nBAZ=GORP\nFOO=BAR\nQUUX=\n"+systemRoot+"\n_=_\n~=~\n";
4103N/A equal(output, expected);
4103N/A }
4103N/A } catch (Throwable t) { unexpected(t); }
4103N/A
4103N/A //----------------------------------------------------------------
0N/A // System.getenv() must be consistent with System.getenv(String)
0N/A //----------------------------------------------------------------
0N/A try {
0N/A for (Map.Entry<String,String> e : getenv().entrySet())
0N/A equal(getenv(e.getKey()), e.getValue());
0N/A } catch (Throwable t) { unexpected(t); }
0N/A
0N/A //----------------------------------------------------------------
0N/A // Fiddle with working directory in child
0N/A //----------------------------------------------------------------
0N/A try {
0N/A String canonicalUserDir =
0N/A new File(System.getProperty("user.dir")).getCanonicalPath();
0N/A String[] sdirs = new String[]
0N/A {".", "..", "/", "/bin",
2247N/A "C:", "c:", "C:/", "c:\\", "\\", "\\bin",
2247N/A "c:\\windows ", "c:\\Program Files", "c:\\Program Files\\" };
0N/A for (String sdir : sdirs) {
0N/A File dir = new File(sdir);
0N/A if (! (dir.isDirectory() && dir.exists()))
0N/A continue;
0N/A out.println("Testing directory " + dir);
2247N/A //dir = new File(dir.getCanonicalPath());
0N/A
0N/A ProcessBuilder pb = new ProcessBuilder();
0N/A equal(pb.directory(), null);
0N/A equal(pwdInChild(pb), canonicalUserDir);
0N/A
0N/A pb.directory(dir);
0N/A equal(pb.directory(), dir);
2247N/A equal(pwdInChild(pb), dir.getCanonicalPath());
0N/A
0N/A pb.directory(null);
0N/A equal(pb.directory(), null);
0N/A equal(pwdInChild(pb), canonicalUserDir);
0N/A
0N/A pb.directory(dir);
0N/A }
0N/A } catch (Throwable t) { unexpected(t); }
0N/A
0N/A //----------------------------------------------------------------
2247N/A // Working directory with Unicode in child
2247N/A //----------------------------------------------------------------
2247N/A try {
2247N/A if (UnicodeOS.is()) {
2247N/A File dir = new File(System.getProperty("test.dir", "."),
2247N/A "ProcessBuilderDir\u4e00\u4e02");
2247N/A try {
2247N/A if (!dir.exists())
2247N/A dir.mkdir();
2247N/A out.println("Testing Unicode directory:" + dir);
2247N/A ProcessBuilder pb = new ProcessBuilder();
2247N/A pb.directory(dir);
2247N/A equal(pwdInChild(pb), dir.getCanonicalPath());
2247N/A } finally {
2247N/A if (dir.exists())
2247N/A dir.delete();
2247N/A }
2247N/A }
2247N/A } catch (Throwable t) { unexpected(t); }
2247N/A
2247N/A //----------------------------------------------------------------
1651N/A // OOME in child allocating maximally sized array
1651N/A // Test for hotspot/jvmti bug 6850957
1651N/A //----------------------------------------------------------------
1651N/A try {
1651N/A List<String> list = new ArrayList<String>(javaChildArgs);
1651N/A list.add(1, String.format("-XX:OnOutOfMemoryError=%s -version",
1651N/A javaExe));
1651N/A list.add("ArrayOOME");
1651N/A ProcessResults r = run(new ProcessBuilder(list));
1651N/A check(r.out().contains("java.lang.OutOfMemoryError:"));
1651N/A check(r.out().contains(javaExe));
1651N/A check(r.err().contains(System.getProperty("java.version")));
1651N/A equal(r.exitValue(), 1);
1651N/A } catch (Throwable t) { unexpected(t); }
1651N/A
1651N/A //----------------------------------------------------------------
0N/A // Windows has tricky semi-case-insensitive semantics
0N/A //----------------------------------------------------------------
0N/A if (Windows.is())
0N/A try {
0N/A out.println("Running case insensitve variable tests");
0N/A for (String[] namePair :
0N/A new String[][]
0N/A { new String[]{"PATH","PaTh"},
0N/A new String[]{"home","HOME"},
0N/A new String[]{"SYSTEMROOT","SystemRoot"}}) {
0N/A check((getenv(namePair[0]) == null &&
0N/A getenv(namePair[1]) == null)
0N/A ||
0N/A getenv(namePair[0]).equals(getenv(namePair[1])),
0N/A "Windows environment variables are not case insensitive");
0N/A }
0N/A } catch (Throwable t) { unexpected(t); }
0N/A
0N/A //----------------------------------------------------------------
0N/A // Test proper Unicode child environment transfer
0N/A //----------------------------------------------------------------
0N/A if (UnicodeOS.is())
0N/A try {
0N/A ProcessBuilder pb = new ProcessBuilder();
0N/A pb.environment().put("\u1234","\u5678");
0N/A pb.environment().remove("PATH");
0N/A equal(getenvInChild1234(pb), "\u5678");
0N/A } catch (Throwable t) { unexpected(t); }
0N/A
0N/A
0N/A //----------------------------------------------------------------
0N/A // Test Runtime.exec(...envp...) with envstrings with initial `='
0N/A //----------------------------------------------------------------
0N/A try {
0N/A List<String> childArgs = new ArrayList<String>(javaChildArgs);
0N/A childArgs.add("System.getenv()");
0N/A String[] cmdp = childArgs.toArray(new String[childArgs.size()]);
3664N/A String[] envp;
3664N/A String[] envpWin = {"=ExitValue=3", "=C:=\\", "SystemRoot="+systemRoot};
3664N/A String[] envpOth = {"=ExitValue=3", "=C:=\\"};
3664N/A if (Windows.is()) {
3664N/A envp = envpWin;
3664N/A } else {
3664N/A envp = envpOth;
3664N/A }
0N/A Process p = Runtime.getRuntime().exec(cmdp, envp);
3664N/A String expected = Windows.is() ? "=C:=\\,SystemRoot="+systemRoot+",=ExitValue=3," : "=C:=\\,";
4666N/A String commandOutput = commandOutput(p);
4666N/A if (MacOSX.is()) {
4666N/A commandOutput = removeMacExpectedVars(commandOutput);
4666N/A }
4666N/A equal(commandOutput, expected);
0N/A if (Windows.is()) {
0N/A ProcessBuilder pb = new ProcessBuilder(childArgs);
0N/A pb.environment().clear();
3664N/A pb.environment().put("SystemRoot", systemRoot);
0N/A pb.environment().put("=ExitValue", "3");
0N/A pb.environment().put("=C:", "\\");
0N/A equal(commandOutput(pb), expected);
0N/A }
0N/A } catch (Throwable t) { unexpected(t); }
0N/A
0N/A //----------------------------------------------------------------
0N/A // Test Runtime.exec(...envp...) with envstrings without any `='
0N/A //----------------------------------------------------------------
0N/A try {
0N/A String[] cmdp = {"echo"};
0N/A String[] envp = {"Hello", "World"}; // Yuck!
0N/A Process p = Runtime.getRuntime().exec(cmdp, envp);
0N/A equal(commandOutput(p), "\n");
0N/A } catch (Throwable t) { unexpected(t); }
0N/A
0N/A //----------------------------------------------------------------
0N/A // Test Runtime.exec(...envp...) with envstrings containing NULs
0N/A //----------------------------------------------------------------
0N/A try {
0N/A List<String> childArgs = new ArrayList<String>(javaChildArgs);
0N/A childArgs.add("System.getenv()");
0N/A String[] cmdp = childArgs.toArray(new String[childArgs.size()]);
3664N/A String[] envpWin = {"SystemRoot="+systemRoot, "LC_ALL=C\u0000\u0000", // Yuck!
3664N/A "FO\u0000=B\u0000R"};
3664N/A String[] envpOth = {"LC_ALL=C\u0000\u0000", // Yuck!
0N/A "FO\u0000=B\u0000R"};
3664N/A String[] envp;
3664N/A if (Windows.is()) {
3664N/A envp = envpWin;
3664N/A } else {
3664N/A envp = envpOth;
3664N/A }
4638N/A System.out.println ("cmdp");
4638N/A for (int i=0; i<cmdp.length; i++) {
4638N/A System.out.printf ("cmdp %d: %s\n", i, cmdp[i]);
4638N/A }
4638N/A System.out.println ("envp");
4638N/A for (int i=0; i<envp.length; i++) {
4638N/A System.out.printf ("envp %d: %s\n", i, envp[i]);
4638N/A }
0N/A Process p = Runtime.getRuntime().exec(cmdp, envp);
4666N/A String commandOutput = commandOutput(p);
4666N/A if (MacOSX.is()) {
4666N/A commandOutput = removeMacExpectedVars(commandOutput);
4666N/A }
4666N/A check(commandOutput.equals(Windows.is()
4666N/A ? "SystemRoot="+systemRoot+",LC_ALL=C,"
4666N/A : "LC_ALL=C,"),
0N/A "Incorrect handling of envstrings containing NULs");
0N/A } catch (Throwable t) { unexpected(t); }
0N/A
0N/A //----------------------------------------------------------------
0N/A // Test the redirectErrorStream property
0N/A //----------------------------------------------------------------
0N/A try {
0N/A ProcessBuilder pb = new ProcessBuilder();
0N/A equal(pb.redirectErrorStream(), false);
0N/A equal(pb.redirectErrorStream(true), pb);
0N/A equal(pb.redirectErrorStream(), true);
0N/A equal(pb.redirectErrorStream(false), pb);
0N/A equal(pb.redirectErrorStream(), false);
0N/A } catch (Throwable t) { unexpected(t); }
0N/A
0N/A try {
0N/A List<String> childArgs = new ArrayList<String>(javaChildArgs);
0N/A childArgs.add("OutErr");
0N/A ProcessBuilder pb = new ProcessBuilder(childArgs);
0N/A {
1270N/A ProcessResults r = run(pb);
0N/A equal(r.out(), "outout");
0N/A equal(r.err(), "errerr");
0N/A }
0N/A {
0N/A pb.redirectErrorStream(true);
1270N/A ProcessResults r = run(pb);
0N/A equal(r.out(), "outerrouterr");
0N/A equal(r.err(), "");
0N/A }
0N/A } catch (Throwable t) { unexpected(t); }
0N/A
1270N/A if (Unix.is()) {
0N/A //----------------------------------------------------------------
0N/A // We can find true and false when PATH is null
0N/A //----------------------------------------------------------------
0N/A try {
0N/A List<String> childArgs = new ArrayList<String>(javaChildArgs);
0N/A childArgs.add("null PATH");
0N/A ProcessBuilder pb = new ProcessBuilder(childArgs);
0N/A pb.environment().remove("PATH");
1270N/A ProcessResults r = run(pb);
0N/A equal(r.out(), "");
0N/A equal(r.err(), "");
0N/A equal(r.exitValue(), 0);
0N/A } catch (Throwable t) { unexpected(t); }
0N/A
0N/A //----------------------------------------------------------------
0N/A // PATH search algorithm on Unix
0N/A //----------------------------------------------------------------
0N/A try {
0N/A List<String> childArgs = new ArrayList<String>(javaChildArgs);
0N/A childArgs.add("PATH search algorithm");
0N/A ProcessBuilder pb = new ProcessBuilder(childArgs);
0N/A pb.environment().put("PATH", "dir1:dir2:");
1270N/A ProcessResults r = run(pb);
0N/A equal(r.out(), "");
0N/A equal(r.err(), "");
0N/A equal(r.exitValue(), True.exitValue());
0N/A } catch (Throwable t) { unexpected(t); }
0N/A
0N/A //----------------------------------------------------------------
0N/A // Parent's, not child's PATH is used
0N/A //----------------------------------------------------------------
0N/A try {
0N/A new File("suBdiR").mkdirs();
0N/A copy("/bin/true", "suBdiR/unliKely");
0N/A final ProcessBuilder pb =
0N/A new ProcessBuilder(new String[]{"unliKely"});
0N/A pb.environment().put("PATH", "suBdiR");
0N/A THROWS(IOException.class,
0N/A new Fun() {void f() throws Throwable {pb.start();}});
0N/A } catch (Throwable t) { unexpected(t);
0N/A } finally {
0N/A new File("suBdiR/unliKely").delete();
0N/A new File("suBdiR").delete();
0N/A }
0N/A }
0N/A
0N/A //----------------------------------------------------------------
0N/A // Attempt to start bogus program ""
0N/A //----------------------------------------------------------------
0N/A try {
0N/A new ProcessBuilder("").start();
0N/A fail("Expected IOException not thrown");
0N/A } catch (IOException e) {
0N/A String m = e.getMessage();
0N/A if (EnglishUnix.is() &&
0N/A ! matches(m, "No such file or directory"))
0N/A unexpected(e);
0N/A } catch (Throwable t) { unexpected(t); }
0N/A
0N/A //----------------------------------------------------------------
0N/A // Check that attempt to execute program name with funny
0N/A // characters throws an exception containing those characters.
0N/A //----------------------------------------------------------------
0N/A for (String programName : new String[] {"\u00f0", "\u01f0"})
0N/A try {
0N/A new ProcessBuilder(programName).start();
0N/A fail("Expected IOException not thrown");
0N/A } catch (IOException e) {
0N/A String m = e.getMessage();
0N/A Pattern p = Pattern.compile(programName);
0N/A if (! matches(m, programName)
0N/A || (EnglishUnix.is()
0N/A && ! matches(m, "No such file or directory")))
0N/A unexpected(e);
0N/A } catch (Throwable t) { unexpected(t); }
0N/A
0N/A //----------------------------------------------------------------
0N/A // Attempt to start process in nonexistent directory fails.
0N/A //----------------------------------------------------------------
0N/A try {
0N/A new ProcessBuilder("echo")
0N/A .directory(new File("UnLiKeLY"))
0N/A .start();
0N/A fail("Expected IOException not thrown");
0N/A } catch (IOException e) {
0N/A String m = e.getMessage();
0N/A if (! matches(m, "in directory")
0N/A || (EnglishUnix.is() &&
0N/A ! matches(m, "No such file or directory")))
0N/A unexpected(e);
0N/A } catch (Throwable t) { unexpected(t); }
0N/A
0N/A //----------------------------------------------------------------
2473N/A // Attempt to write 4095 bytes to the pipe buffer without a
2473N/A // reader to drain it would deadlock, if not for the fact that
0N/A // interprocess pipe buffers are at least 4096 bytes.
2473N/A //
2473N/A // Also, check that available reports all the bytes expected
2473N/A // in the pipe buffer, and that I/O operations do the expected
2473N/A // things.
0N/A //----------------------------------------------------------------
0N/A try {
0N/A List<String> childArgs = new ArrayList<String>(javaChildArgs);
0N/A childArgs.add("print4095");
2473N/A final int SIZE = 4095;
2473N/A final Process p = new ProcessBuilder(childArgs).start();
2473N/A print4095(p.getOutputStream(), (byte) '!'); // Might hang!
2473N/A p.waitFor(); // Might hang!
2473N/A equal(SIZE, p.getInputStream().available());
2473N/A equal(SIZE, p.getErrorStream().available());
2473N/A THROWS(IOException.class,
2473N/A new Fun(){void f() throws IOException {
2473N/A p.getOutputStream().write((byte) '!');
2473N/A p.getOutputStream().flush();
2473N/A }});
2473N/A
2473N/A final byte[] bytes = new byte[SIZE + 1];
2473N/A equal(SIZE, p.getInputStream().read(bytes));
2473N/A for (int i = 0; i < SIZE; i++)
2473N/A equal((byte) '!', bytes[i]);
2473N/A equal((byte) 0, bytes[SIZE]);
2473N/A
2473N/A equal(SIZE, p.getErrorStream().read(bytes));
2473N/A for (int i = 0; i < SIZE; i++)
2473N/A equal((byte) 'E', bytes[i]);
2473N/A equal((byte) 0, bytes[SIZE]);
2473N/A
2473N/A equal(0, p.getInputStream().available());
2473N/A equal(0, p.getErrorStream().available());
2473N/A equal(-1, p.getErrorStream().read());
2473N/A equal(-1, p.getInputStream().read());
2473N/A
0N/A equal(p.exitValue(), 5);
2473N/A
3643N/A p.getInputStream().close();
3643N/A p.getErrorStream().close();
3643N/A p.getOutputStream().close();
2473N/A
2473N/A InputStream[] streams = { p.getInputStream(), p.getErrorStream() };
2473N/A for (final InputStream in : streams) {
2473N/A Fun[] ops = {
2473N/A new Fun(){void f() throws IOException {
2473N/A in.read(); }},
2473N/A new Fun(){void f() throws IOException {
2473N/A in.read(bytes); }},
2473N/A new Fun(){void f() throws IOException {
2473N/A in.available(); }}
2473N/A };
2473N/A for (Fun op : ops) {
2473N/A try {
2473N/A op.f();
2473N/A fail();
2473N/A } catch (IOException expected) {
2473N/A check(expected.getMessage()
2473N/A .matches("[Ss]tream [Cc]losed"));
2473N/A }
2473N/A }
2473N/A }
2473N/A } catch (Throwable t) { unexpected(t); }
2473N/A
2473N/A //----------------------------------------------------------------
2473N/A // Check that reads which are pending when Process.destroy is
2473N/A // called, get EOF, not IOException("Stream closed").
2473N/A //----------------------------------------------------------------
2473N/A try {
2473N/A final int cases = 4;
2473N/A for (int i = 0; i < cases; i++) {
2473N/A final int action = i;
2473N/A List<String> childArgs = new ArrayList<String>(javaChildArgs);
2473N/A childArgs.add("sleep");
2473N/A final byte[] bytes = new byte[10];
2473N/A final Process p = new ProcessBuilder(childArgs).start();
2473N/A final CountDownLatch latch = new CountDownLatch(1);
5376N/A final InputStream s;
5376N/A switch (action & 0x1) {
5376N/A case 0: s = p.getInputStream(); break;
5376N/A case 1: s = p.getErrorStream(); break;
5376N/A default: throw new Error();
5376N/A }
2473N/A final Thread thread = new Thread() {
2473N/A public void run() {
2473N/A try {
5376N/A int r;
2473N/A latch.countDown();
5376N/A switch (action & 0x2) {
5376N/A case 0: r = s.read(); break;
5376N/A case 2: r = s.read(bytes); break;
5376N/A default: throw new Error();
2473N/A }
2473N/A equal(-1, r);
2473N/A } catch (Throwable t) { unexpected(t); }}};
2473N/A
2473N/A thread.start();
2473N/A latch.await();
5377N/A Thread.sleep(10);
5376N/A
5376N/A String os = System.getProperty("os.name");
5376N/A if (os.equalsIgnoreCase("Solaris") ||
5376N/A os.equalsIgnoreCase("SunOS"))
5376N/A {
5376N/A final Object deferred;
5376N/A Class<?> c = s.getClass();
5376N/A if (c.getName().equals(
5376N/A "java.lang.UNIXProcess$DeferredCloseInputStream"))
5376N/A {
5376N/A deferred = s;
5376N/A } else {
5376N/A Field deferredField = p.getClass().
5376N/A getDeclaredField("stdout_inner_stream");
5376N/A deferredField.setAccessible(true);
5376N/A deferred = deferredField.get(p);
5376N/A }
5376N/A Field useCountField = deferred.getClass().
5376N/A getDeclaredField("useCount");
5376N/A useCountField.setAccessible(true);
5376N/A
5376N/A while (useCountField.getInt(deferred) <= 0) {
5376N/A Thread.yield();
5376N/A }
5377N/A } else if (s instanceof BufferedInputStream) {
5377N/A Field f = Unsafe.class.getDeclaredField("theUnsafe");
5377N/A f.setAccessible(true);
5377N/A Unsafe unsafe = (Unsafe)f.get(null);
5377N/A
5377N/A while (unsafe.tryMonitorEnter(s)) {
5377N/A unsafe.monitorExit(s);
5377N/A Thread.sleep(1);
5377N/A }
5376N/A }
2473N/A p.destroy();
2473N/A thread.join();
2473N/A }
0N/A } catch (Throwable t) { unexpected(t); }
0N/A
0N/A //----------------------------------------------------------------
2800N/A // Check that subprocesses which create subprocesses of their
2800N/A // own do not cause parent to hang waiting for file
2800N/A // descriptors to be closed.
2800N/A //----------------------------------------------------------------
2800N/A try {
2800N/A if (Unix.is()
2800N/A && new File("/bin/bash").exists()
2800N/A && new File("/bin/sleep").exists()) {
2800N/A final String[] cmd = { "/bin/bash", "-c", "(/bin/sleep 6666)" };
2800N/A final ProcessBuilder pb = new ProcessBuilder(cmd);
2800N/A final Process p = pb.start();
2800N/A final InputStream stdout = p.getInputStream();
2800N/A final InputStream stderr = p.getErrorStream();
2800N/A final OutputStream stdin = p.getOutputStream();
2800N/A final Thread reader = new Thread() {
2800N/A public void run() {
2800N/A try { stdout.read(); }
2800N/A catch (IOException e) {
2883N/A // Check that reader failed because stream was
2883N/A // asynchronously closed.
2800N/A // e.printStackTrace();
2800N/A if (EnglishUnix.is() &&
2883N/A ! (e.getMessage().matches(".*Bad file.*")))
2800N/A unexpected(e);
2800N/A }
2800N/A catch (Throwable t) { unexpected(t); }}};
2800N/A reader.setDaemon(true);
2800N/A reader.start();
2800N/A Thread.sleep(100);
2800N/A p.destroy();
2800N/A // Subprocess is now dead, but file descriptors remain open.
2800N/A check(p.waitFor() != 0);
2800N/A check(p.exitValue() != 0);
2800N/A stdout.close();
2800N/A stderr.close();
2800N/A stdin.close();
2800N/A //----------------------------------------------------------
2800N/A // There remain unsolved issues with asynchronous close.
2800N/A // Here's a highly non-portable experiment to demonstrate:
2800N/A //----------------------------------------------------------
2800N/A if (Boolean.getBoolean("wakeupJeff!")) {
2800N/A System.out.println("wakeupJeff!");
2800N/A // Initialize signal handler for INTERRUPT_SIGNAL.
2800N/A new FileInputStream("/bin/sleep").getChannel().close();
2800N/A // Send INTERRUPT_SIGNAL to every thread in this java.
2800N/A String[] wakeupJeff = {
2800N/A "/bin/bash", "-c",
2800N/A "/bin/ps --noheaders -Lfp $PPID | " +
2800N/A "/usr/bin/perl -nale 'print $F[3]' | " +
2800N/A // INTERRUPT_SIGNAL == 62 on my machine du jour.
2800N/A "/usr/bin/xargs kill -62"
2800N/A };
2800N/A new ProcessBuilder(wakeupJeff).start().waitFor();
2800N/A // If wakeupJeff worked, reader probably got EBADF.
2800N/A reader.join();
2800N/A }
2800N/A }
2800N/A } catch (Throwable t) { unexpected(t); }
2800N/A
2800N/A //----------------------------------------------------------------
0N/A // Attempt to start process with insufficient permissions fails.
0N/A //----------------------------------------------------------------
0N/A try {
0N/A new File("emptyCommand").delete();
0N/A new FileOutputStream("emptyCommand").close();
0N/A new File("emptyCommand").setExecutable(false);
0N/A new ProcessBuilder("./emptyCommand").start();
0N/A fail("Expected IOException not thrown");
0N/A } catch (IOException e) {
0N/A new File("./emptyCommand").delete();
0N/A String m = e.getMessage();
0N/A if (EnglishUnix.is() &&
0N/A ! matches(m, "Permission denied"))
0N/A unexpected(e);
0N/A } catch (Throwable t) { unexpected(t); }
0N/A
0N/A new File("emptyCommand").delete();
0N/A
0N/A //----------------------------------------------------------------
0N/A // Check for correct security permission behavior
0N/A //----------------------------------------------------------------
0N/A final Policy policy = new Policy();
0N/A Policy.setPolicy(policy);
0N/A System.setSecurityManager(new SecurityManager());
0N/A
0N/A try {
0N/A // No permissions required to CREATE a ProcessBuilder
0N/A policy.setPermissions(/* Nothing */);
0N/A new ProcessBuilder("env").directory(null).directory();
0N/A new ProcessBuilder("env").directory(new File("dir")).directory();
0N/A new ProcessBuilder("env").command("??").command();
0N/A } catch (Throwable t) { unexpected(t); }
0N/A
0N/A THROWS(SecurityException.class,
0N/A new Fun() { void f() throws IOException {
0N/A policy.setPermissions(/* Nothing */);
0N/A System.getenv("foo");}},
0N/A new Fun() { void f() throws IOException {
0N/A policy.setPermissions(/* Nothing */);
0N/A System.getenv();}},
0N/A new Fun() { void f() throws IOException {
0N/A policy.setPermissions(/* Nothing */);
0N/A new ProcessBuilder("echo").start();}},
0N/A new Fun() { void f() throws IOException {
0N/A policy.setPermissions(/* Nothing */);
0N/A Runtime.getRuntime().exec("echo");}},
0N/A new Fun() { void f() throws IOException {
0N/A policy.setPermissions(new RuntimePermission("getenv.bar"));
0N/A System.getenv("foo");}});
0N/A
0N/A try {
0N/A policy.setPermissions(new RuntimePermission("getenv.foo"));
0N/A System.getenv("foo");
0N/A
0N/A policy.setPermissions(new RuntimePermission("getenv.*"));
0N/A System.getenv("foo");
0N/A System.getenv();
0N/A new ProcessBuilder().environment();
0N/A } catch (Throwable t) { unexpected(t); }
0N/A
0N/A
0N/A final Permission execPermission
0N/A = new FilePermission("<<ALL FILES>>", "execute");
0N/A
0N/A THROWS(SecurityException.class,
0N/A new Fun() { void f() throws IOException {
0N/A // environment permission by itself insufficient
0N/A policy.setPermissions(new RuntimePermission("getenv.*"));
0N/A ProcessBuilder pb = new ProcessBuilder("env");
0N/A pb.environment().put("foo","bar");
0N/A pb.start();}},
0N/A new Fun() { void f() throws IOException {
0N/A // exec permission by itself insufficient
0N/A policy.setPermissions(execPermission);
0N/A ProcessBuilder pb = new ProcessBuilder("env");
0N/A pb.environment().put("foo","bar");
0N/A pb.start();}});
0N/A
0N/A try {
0N/A // Both permissions? OK.
0N/A policy.setPermissions(new RuntimePermission("getenv.*"),
0N/A execPermission);
0N/A ProcessBuilder pb = new ProcessBuilder("env");
0N/A pb.environment().put("foo","bar");
25N/A Process p = pb.start();
25N/A closeStreams(p);
0N/A } catch (IOException e) { // OK
0N/A } catch (Throwable t) { unexpected(t); }
0N/A
0N/A try {
0N/A // Don't need environment permission unless READING environment
0N/A policy.setPermissions(execPermission);
0N/A Runtime.getRuntime().exec("env", new String[]{});
0N/A } catch (IOException e) { // OK
0N/A } catch (Throwable t) { unexpected(t); }
0N/A
0N/A try {
0N/A // Don't need environment permission unless READING environment
0N/A policy.setPermissions(execPermission);
0N/A new ProcessBuilder("env").start();
0N/A } catch (IOException e) { // OK
0N/A } catch (Throwable t) { unexpected(t); }
0N/A
0N/A // Restore "normal" state without a security manager
0N/A policy.setPermissions(new RuntimePermission("setSecurityManager"));
0N/A System.setSecurityManager(null);
0N/A
0N/A }
0N/A
25N/A static void closeStreams(Process p) {
25N/A try {
25N/A p.getOutputStream().close();
25N/A p.getInputStream().close();
25N/A p.getErrorStream().close();
25N/A } catch (Throwable t) { unexpected(t); }
25N/A }
25N/A
0N/A //----------------------------------------------------------------
0N/A // A Policy class designed to make permissions fiddling very easy.
0N/A //----------------------------------------------------------------
0N/A private static class Policy extends java.security.Policy {
0N/A private Permissions perms;
0N/A
0N/A public void setPermissions(Permission...permissions) {
0N/A perms = new Permissions();
0N/A for (Permission permission : permissions)
0N/A perms.add(permission);
0N/A }
0N/A
0N/A public Policy() { setPermissions(/* Nothing */); }
0N/A
0N/A public PermissionCollection getPermissions(CodeSource cs) {
0N/A return perms;
0N/A }
0N/A
0N/A public PermissionCollection getPermissions(ProtectionDomain pd) {
0N/A return perms;
0N/A }
0N/A
0N/A public boolean implies(ProtectionDomain pd, Permission p) {
0N/A return perms.implies(p);
0N/A }
0N/A
0N/A public void refresh() {}
0N/A }
0N/A
0N/A private static class StreamAccumulator extends Thread {
0N/A private final InputStream is;
0N/A private final StringBuilder sb = new StringBuilder();
0N/A private Throwable throwable = null;
0N/A
0N/A public String result () throws Throwable {
0N/A if (throwable != null)
0N/A throw throwable;
0N/A return sb.toString();
0N/A }
0N/A
0N/A StreamAccumulator (InputStream is) {
0N/A this.is = is;
0N/A }
0N/A
0N/A public void run() {
0N/A try {
0N/A Reader r = new InputStreamReader(is);
0N/A char[] buf = new char[4096];
0N/A int n;
0N/A while ((n = r.read(buf)) > 0) {
0N/A sb.append(buf,0,n);
0N/A }
0N/A } catch (Throwable t) {
0N/A throwable = t;
25N/A } finally {
25N/A try { is.close(); }
25N/A catch (Throwable t) { throwable = t; }
0N/A }
0N/A }
0N/A }
0N/A
25N/A static ProcessResults run(ProcessBuilder pb) {
25N/A try {
25N/A return run(pb.start());
25N/A } catch (Throwable t) { unexpected(t); return null; }
25N/A }
25N/A
0N/A private static ProcessResults run(Process p) {
0N/A Throwable throwable = null;
0N/A int exitValue = -1;
0N/A String out = "";
0N/A String err = "";
0N/A
0N/A StreamAccumulator outAccumulator =
0N/A new StreamAccumulator(p.getInputStream());
0N/A StreamAccumulator errAccumulator =
0N/A new StreamAccumulator(p.getErrorStream());
0N/A
0N/A try {
0N/A outAccumulator.start();
0N/A errAccumulator.start();
0N/A
0N/A exitValue = p.waitFor();
0N/A
0N/A outAccumulator.join();
0N/A errAccumulator.join();
0N/A
0N/A out = outAccumulator.result();
0N/A err = errAccumulator.result();
0N/A } catch (Throwable t) {
0N/A throwable = t;
0N/A }
0N/A
0N/A return new ProcessResults(out, err, exitValue, throwable);
0N/A }
0N/A
0N/A //----------------------------------------------------------------
0N/A // Results of a command
0N/A //----------------------------------------------------------------
0N/A private static class ProcessResults {
0N/A private final String out;
0N/A private final String err;
0N/A private final int exitValue;
0N/A private final Throwable throwable;
0N/A
0N/A public ProcessResults(String out,
0N/A String err,
0N/A int exitValue,
0N/A Throwable throwable) {
0N/A this.out = out;
0N/A this.err = err;
0N/A this.exitValue = exitValue;
0N/A this.throwable = throwable;
0N/A }
0N/A
0N/A public String out() { return out; }
0N/A public String err() { return err; }
0N/A public int exitValue() { return exitValue; }
0N/A public Throwable throwable() { return throwable; }
0N/A
0N/A public String toString() {
0N/A StringBuilder sb = new StringBuilder();
0N/A sb.append("<STDOUT>\n" + out() + "</STDOUT>\n")
0N/A .append("<STDERR>\n" + err() + "</STDERR>\n")
0N/A .append("exitValue = " + exitValue + "\n");
0N/A if (throwable != null)
0N/A sb.append(throwable.getStackTrace());
0N/A return sb.toString();
0N/A }
0N/A }
0N/A
0N/A //--------------------- Infrastructure ---------------------------
0N/A static volatile int passed = 0, failed = 0;
0N/A static void pass() {passed++;}
0N/A static void fail() {failed++; Thread.dumpStack();}
0N/A static void fail(String msg) {System.out.println(msg); fail();}
0N/A static void unexpected(Throwable t) {failed++; t.printStackTrace();}
0N/A static void check(boolean cond) {if (cond) pass(); else fail();}
0N/A static void check(boolean cond, String m) {if (cond) pass(); else fail(m);}
0N/A static void equal(Object x, Object y) {
0N/A if (x == null ? y == null : x.equals(y)) pass();
0N/A else fail(x + " not equal to " + y);}
3664N/A
0N/A public static void main(String[] args) throws Throwable {
0N/A try {realMain(args);} catch (Throwable t) {unexpected(t);}
0N/A System.out.printf("%nPassed = %d, failed = %d%n%n", passed, failed);
0N/A if (failed > 0) throw new AssertionError("Some tests failed");}
0N/A private static abstract class Fun {abstract void f() throws Throwable;}
0N/A static void THROWS(Class<? extends Throwable> k, Fun... fs) {
0N/A for (Fun f : fs)
0N/A try { f.f(); fail("Expected " + k.getName() + " not thrown"); }
0N/A catch (Throwable t) {
0N/A if (k.isAssignableFrom(t.getClass())) pass();
0N/A else unexpected(t);}}
0N/A}