Basic.java revision 0
0N/A/*
0N/A * Copyright 2003-2007 Sun Microsystems, Inc. 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 *
0N/A * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
0N/A * CA 95054 USA or visit www.sun.com if you need additional information or
0N/A * have any 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
0N/A * 6464154 6523983 6206031
0N/A * @summary Basic tests for Process and Environment Variable code
0N/A * @run main/othervm Basic
0N/A * @author Martin Buchholz
0N/A */
0N/A
0N/Aimport java.io.*;
0N/Aimport java.util.*;
0N/Aimport java.security.*;
0N/Aimport java.util.regex.Pattern;
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
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
0N/A static void print4095(OutputStream s) throws Throwable {
0N/A byte[] bytes = new byte[4095];
0N/A Arrays.fill(bytes, (byte) '!');
0N/A s.write(bytes); // Might hang!
0N/A }
0N/A
0N/A public static class JavaChild {
0N/A public static void main(String args[]) throws Throwable {
0N/A String action = args[0];
0N/A 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()));
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")) {
0N/A print4095(System.out);
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");
0N/A r = run(pb.start());
0N/A equal(r.exitValue(), True.exitValue());
0N/A
0N/A pb.command("false");
0N/A r = run(pb.start());
0N/A equal(r.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();
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, "Permission denied"))
0N/A unexpected(e);
0N/A } catch (Throwable t) { unexpected(t); }
0N/A
0N/A // continue searching if EACCES
0N/A copy("/bin/true", "dir2/prog");
0N/A equal(run(pb.start()).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");
0N/A equal(run(pb.start()).exitValue(), True.exitValue());
0N/A
0N/A // Check empty PATH component means current directory
0N/A new File("dir1/prog").delete();
0N/A new File("dir2/prog").delete();
0N/A copy("/bin/true", "./prog");
0N/A equal(run(pb.start()).exitValue(), True.exitValue());
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");
0N/A equal(run(pb.start()).exitValue(), True.exitValue());
0N/A copy("/bin/true", "dir3/prog");
0N/A copy("/bin/false", "dir1/prog");
0N/A equal(run(pb.start()).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
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
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
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
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();
0N/A equal(getenvInChild(pb), "");
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 {
0N/A // '+' < 'A' < 'Z' < '_' < 'a' < 'z' < '~'
0N/A String[]envp = {"FOO=BAR","BAZ=GORP","QUUX=",
0N/A "+=+", "_=_", "~=~"};
0N/A String output = nativeEnv(envp);
0N/A String expected = "+=+\nBAZ=GORP\nFOO=BAR\nQUUX=\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 //----------------------------------------------------------------
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",
0N/A "C:", "c:", "C:/", "c:\\", "\\", "\\bin" };
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);
0N/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);
0N/A equal(pwdInChild(pb), dir.toString());
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 //----------------------------------------------------------------
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()]);
0N/A String[] envp = {"=ExitValue=3", "=C:=\\"};
0N/A Process p = Runtime.getRuntime().exec(cmdp, envp);
0N/A String expected = Windows.is() ? "=C:=\\,=ExitValue=3," : "=C:=\\,";
0N/A equal(commandOutput(p), expected);
0N/A if (Windows.is()) {
0N/A ProcessBuilder pb = new ProcessBuilder(childArgs);
0N/A pb.environment().clear();
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()]);
0N/A String[] envp = {"LC_ALL=C\u0000\u0000", // Yuck!
0N/A "FO\u0000=B\u0000R"};
0N/A Process p = Runtime.getRuntime().exec(cmdp, envp);
0N/A check(commandOutput(p).equals("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 {
0N/A ProcessResults r = run(pb.start());
0N/A equal(r.out(), "outout");
0N/A equal(r.err(), "errerr");
0N/A }
0N/A {
0N/A pb.redirectErrorStream(true);
0N/A ProcessResults r = run(pb.start());
0N/A equal(r.out(), "outerrouterr");
0N/A equal(r.err(), "");
0N/A }
0N/A } catch (Throwable t) { unexpected(t); }
0N/A
0N/A if (! Windows.is() &&
0N/A new File("/bin/true").exists() &&
0N/A new File("/bin/false").exists()) {
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");
0N/A ProcessResults r = run(pb.start());
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:");
0N/A ProcessResults r = run(pb.start());
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 //----------------------------------------------------------------
0N/A // This would deadlock, if not for the fact that
0N/A // interprocess pipe buffers are at least 4096 bytes.
0N/A //----------------------------------------------------------------
0N/A try {
0N/A List<String> childArgs = new ArrayList<String>(javaChildArgs);
0N/A childArgs.add("print4095");
0N/A Process p = new ProcessBuilder(childArgs).start();
0N/A print4095(p.getOutputStream()); // Might hang!
0N/A p.waitFor(); // Might hang!
0N/A equal(p.exitValue(), 5);
0N/A } catch (Throwable t) { unexpected(t); }
0N/A
0N/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 //e.printStackTrace();
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");
0N/A pb.start();
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
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;
0N/A }
0N/A }
0N/A }
0N/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);}
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}