blob: 745fab468b9d4376a2b5362422900c8a025e089a [file] [log] [blame]
duke6e45e102007-12-01 00:00:00 +00001/*
xdonod10b8cf2008-07-02 12:55:45 -07002 * Copyright 2003-2008 Sun Microsystems, Inc. All Rights Reserved.
duke6e45e102007-12-01 00:00:00 +00003 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.
8 *
9 * This code is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
12 * version 2 for more details (a copy is included in the LICENSE file that
13 * accompanied this code).
14 *
15 * You should have received a copy of the GNU General Public License version
16 * 2 along with this work; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18 *
19 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
20 * CA 95054 USA or visit www.sun.com if you need additional information or
21 * have any questions.
22 */
23
24/*
25 * @test
26 * @bug 4199068 4738465 4937983 4930681 4926230 4931433 4932663 4986689
27 * 5026830 5023243 5070673 4052517 4811767 6192449 6397034 6413313
martindd2fd9f2008-03-10 14:32:51 -070028 * 6464154 6523983 6206031 4960438 6631352 6631966
duke6e45e102007-12-01 00:00:00 +000029 * @summary Basic tests for Process and Environment Variable code
30 * @run main/othervm Basic
31 * @author Martin Buchholz
32 */
33
martindd2fd9f2008-03-10 14:32:51 -070034import java.lang.ProcessBuilder.Redirect;
35import static java.lang.ProcessBuilder.Redirect.*;
36
duke6e45e102007-12-01 00:00:00 +000037import java.io.*;
38import java.util.*;
39import java.security.*;
40import java.util.regex.Pattern;
41import static java.lang.System.getenv;
42import static java.lang.System.out;
43import static java.lang.Boolean.TRUE;
44import static java.util.AbstractMap.SimpleImmutableEntry;
45
46public class Basic {
47
48 private static String commandOutput(Reader r) throws Throwable {
49 StringBuilder sb = new StringBuilder();
50 int c;
51 while ((c = r.read()) > 0)
52 if (c != '\r')
53 sb.append((char) c);
54 return sb.toString();
55 }
56
57 private static String commandOutput(Process p) throws Throwable {
58 check(p.getInputStream() == p.getInputStream());
59 check(p.getOutputStream() == p.getOutputStream());
60 check(p.getErrorStream() == p.getErrorStream());
61 Reader r = new InputStreamReader(p.getInputStream(),"UTF-8");
62 String output = commandOutput(r);
63 equal(p.waitFor(), 0);
64 equal(p.exitValue(), 0);
65 return output;
66 }
67
68 private static String commandOutput(ProcessBuilder pb) {
69 try {
70 return commandOutput(pb.start());
71 } catch (Throwable t) {
72 String commandline = "";
73 for (String arg : pb.command())
74 commandline += " " + arg;
75 System.out.println("Exception trying to run process: " + commandline);
76 unexpected(t);
77 return "";
78 }
79 }
80
81 private static String commandOutput(String...command) {
82 try {
83 return commandOutput(Runtime.getRuntime().exec(command));
84 } catch (Throwable t) {
85 String commandline = "";
86 for (String arg : command)
87 commandline += " " + arg;
88 System.out.println("Exception trying to run process: " + commandline);
89 unexpected(t);
90 return "";
91 }
92 }
93
94 private static void checkCommandOutput(ProcessBuilder pb,
95 String expected,
96 String failureMsg) {
97 String got = commandOutput(pb);
98 check(got.equals(expected),
99 failureMsg + "\n" +
100 "Expected: \"" + expected + "\"\n" +
101 "Got: \"" + got + "\"");
102 }
103
104 private static String absolutifyPath(String path) {
105 StringBuilder sb = new StringBuilder();
106 for (String file : path.split(File.pathSeparator)) {
107 if (sb.length() != 0)
108 sb.append(File.pathSeparator);
109 sb.append(new File(file).getAbsolutePath());
110 }
111 return sb.toString();
112 }
113
114 // compare windows-style, by canonicalizing to upper case,
115 // not lower case as String.compareToIgnoreCase does
116 private static class WindowsComparator
117 implements Comparator<String> {
118 public int compare(String x, String y) {
119 return x.toUpperCase(Locale.US)
120 .compareTo(y.toUpperCase(Locale.US));
121 }
122 }
123
124 private static String sortedLines(String lines) {
125 String[] arr = lines.split("\n");
126 List<String> ls = new ArrayList<String>();
127 for (String s : arr)
128 ls.add(s);
129 Collections.sort(ls, new WindowsComparator());
130 StringBuilder sb = new StringBuilder();
131 for (String s : ls)
132 sb.append(s + "\n");
133 return sb.toString();
134 }
135
136 private static void compareLinesIgnoreCase(String lines1, String lines2) {
137 if (! (sortedLines(lines1).equalsIgnoreCase(sortedLines(lines2)))) {
138 String dashes =
139 "-----------------------------------------------------";
140 out.println(dashes);
141 out.print(sortedLines(lines1));
142 out.println(dashes);
143 out.print(sortedLines(lines2));
144 out.println(dashes);
145 out.println("sizes: " + sortedLines(lines1).length() +
146 " " + sortedLines(lines2).length());
147
148 fail("Sorted string contents differ");
149 }
150 }
151
152 private static final Runtime runtime = Runtime.getRuntime();
153
154 private static final String[] winEnvCommand = {"cmd.exe", "/c", "set"};
155
156 private static String winEnvFilter(String env) {
157 return env.replaceAll("\r", "")
158 .replaceAll("(?m)^(?:COMSPEC|PROMPT|PATHEXT)=.*\n","");
159 }
160
161 private static String unixEnvProg() {
162 return new File("/usr/bin/env").canExecute() ? "/usr/bin/env"
163 : "/bin/env";
164 }
165
166 private static String nativeEnv(String[] env) {
167 try {
168 if (Windows.is()) {
169 return winEnvFilter
170 (commandOutput(runtime.exec(winEnvCommand, env)));
171 } else {
172 return commandOutput(runtime.exec(unixEnvProg(), env));
173 }
174 } catch (Throwable t) { throw new Error(t); }
175 }
176
177 private static String nativeEnv(ProcessBuilder pb) {
178 try {
179 if (Windows.is()) {
180 pb.command(winEnvCommand);
181 return winEnvFilter(commandOutput(pb));
182 } else {
183 pb.command(new String[]{unixEnvProg()});
184 return commandOutput(pb);
185 }
186 } catch (Throwable t) { throw new Error(t); }
187 }
188
189 private static void checkSizes(Map<String,String> environ, int size) {
190 try {
191 equal(size, environ.size());
192 equal(size, environ.entrySet().size());
193 equal(size, environ.keySet().size());
194 equal(size, environ.values().size());
195
196 boolean isEmpty = (size == 0);
197 equal(isEmpty, environ.isEmpty());
198 equal(isEmpty, environ.entrySet().isEmpty());
199 equal(isEmpty, environ.keySet().isEmpty());
200 equal(isEmpty, environ.values().isEmpty());
201 } catch (Throwable t) { unexpected(t); }
202 }
203
204 private interface EnvironmentFrobber {
205 void doIt(Map<String,String> environ);
206 }
207
208 private static void testVariableDeleter(EnvironmentFrobber fooDeleter) {
209 try {
210 Map<String,String> environ = new ProcessBuilder().environment();
211 environ.put("Foo", "BAAR");
212 fooDeleter.doIt(environ);
213 equal(environ.get("Foo"), null);
214 equal(environ.remove("Foo"), null);
215 } catch (Throwable t) { unexpected(t); }
216 }
217
218 private static void testVariableAdder(EnvironmentFrobber fooAdder) {
219 try {
220 Map<String,String> environ = new ProcessBuilder().environment();
221 environ.remove("Foo");
222 fooAdder.doIt(environ);
223 equal(environ.get("Foo"), "Bahrein");
224 } catch (Throwable t) { unexpected(t); }
225 }
226
227 private static void testVariableModifier(EnvironmentFrobber fooModifier) {
228 try {
229 Map<String,String> environ = new ProcessBuilder().environment();
230 environ.put("Foo","OldValue");
231 fooModifier.doIt(environ);
232 equal(environ.get("Foo"), "NewValue");
233 } catch (Throwable t) { unexpected(t); }
234 }
235
236 private static void printUTF8(String s) throws IOException {
237 out.write(s.getBytes("UTF-8"));
238 }
239
240 private static String getenvAsString(Map<String,String> environment) {
241 StringBuilder sb = new StringBuilder();
242 for (Map.Entry<String,String> e : environment.entrySet())
243 // Ignore magic environment variables added by the launcher
244 if (! e.getKey().equals("NLSPATH") &&
245 ! e.getKey().equals("XFILESEARCHPATH") &&
246 ! e.getKey().equals("LD_LIBRARY_PATH"))
247 sb.append(e.getKey())
248 .append('=')
249 .append(e.getValue())
250 .append(',');
251 return sb.toString();
252 }
253
254 static void print4095(OutputStream s) throws Throwable {
255 byte[] bytes = new byte[4095];
256 Arrays.fill(bytes, (byte) '!');
257 s.write(bytes); // Might hang!
258 }
259
martin2ea07df2009-06-14 14:23:22 -0700260 static void checkPermissionDenied(ProcessBuilder pb) {
261 try {
262 pb.start();
263 fail("Expected IOException not thrown");
264 } catch (IOException e) {
265 String m = e.getMessage();
266 if (EnglishUnix.is() &&
267 ! matches(m, "Permission denied"))
268 unexpected(e);
269 } catch (Throwable t) { unexpected(t); }
270 }
271
duke6e45e102007-12-01 00:00:00 +0000272 public static class JavaChild {
273 public static void main(String args[]) throws Throwable {
274 String action = args[0];
martindd2fd9f2008-03-10 14:32:51 -0700275 if (action.equals("testIO")) {
276 String expected = "standard input";
277 char[] buf = new char[expected.length()+1];
278 int n = new InputStreamReader(System.in).read(buf,0,buf.length);
279 if (n != expected.length())
280 System.exit(5);
281 if (! new String(buf,0,n).equals(expected))
282 System.exit(5);
283 System.err.print("standard error");
284 System.out.print("standard output");
285 } else if (action.equals("testInheritIO")) {
286 List<String> childArgs = new ArrayList<String>(javaChildArgs);
287 childArgs.add("testIO");
288 ProcessBuilder pb = new ProcessBuilder(childArgs);
289 pb.inheritIO();
290 ProcessResults r = run(pb);
291 if (! r.out().equals(""))
292 System.exit(7);
293 if (! r.err().equals(""))
294 System.exit(8);
295 if (r.exitValue() != 0)
296 System.exit(9);
297 } else if (action.equals("System.getenv(String)")) {
duke6e45e102007-12-01 00:00:00 +0000298 String val = System.getenv(args[1]);
299 printUTF8(val == null ? "null" : val);
300 } else if (action.equals("System.getenv(\\u1234)")) {
301 String val = System.getenv("\u1234");
302 printUTF8(val == null ? "null" : val);
303 } else if (action.equals("System.getenv()")) {
304 printUTF8(getenvAsString(System.getenv()));
305 } else if (action.equals("pwd")) {
306 printUTF8(new File(System.getProperty("user.dir"))
307 .getCanonicalPath());
308 } else if (action.equals("print4095")) {
309 print4095(System.out);
310 System.exit(5);
311 } else if (action.equals("OutErr")) {
312 // You might think the system streams would be
313 // buffered, and in fact they are implemented using
314 // BufferedOutputStream, but each and every print
315 // causes immediate operating system I/O.
316 System.out.print("out");
317 System.err.print("err");
318 System.out.print("out");
319 System.err.print("err");
320 } else if (action.equals("null PATH")) {
321 equal(System.getenv("PATH"), null);
322 check(new File("/bin/true").exists());
323 check(new File("/bin/false").exists());
324 ProcessBuilder pb1 = new ProcessBuilder();
325 ProcessBuilder pb2 = new ProcessBuilder();
326 pb2.environment().put("PATH", "anyOldPathIgnoredAnyways");
327 ProcessResults r;
328
329 for (final ProcessBuilder pb :
330 new ProcessBuilder[] {pb1, pb2}) {
331 pb.command("true");
martin2ea07df2009-06-14 14:23:22 -0700332 equal(run(pb).exitValue(), True.exitValue());
duke6e45e102007-12-01 00:00:00 +0000333
334 pb.command("false");
martin2ea07df2009-06-14 14:23:22 -0700335 equal(run(pb).exitValue(), False.exitValue());
duke6e45e102007-12-01 00:00:00 +0000336 }
337
338 if (failed != 0) throw new Error("null PATH");
339 } else if (action.equals("PATH search algorithm")) {
340 equal(System.getenv("PATH"), "dir1:dir2:");
341 check(new File("/bin/true").exists());
342 check(new File("/bin/false").exists());
343 String[] cmd = {"prog"};
344 ProcessBuilder pb1 = new ProcessBuilder(cmd);
345 ProcessBuilder pb2 = new ProcessBuilder(cmd);
346 ProcessBuilder pb3 = new ProcessBuilder(cmd);
347 pb2.environment().put("PATH", "anyOldPathIgnoredAnyways");
348 pb3.environment().remove("PATH");
349
350 for (final ProcessBuilder pb :
351 new ProcessBuilder[] {pb1, pb2, pb3}) {
352 try {
353 // Not on PATH at all; directories don't exist
354 try {
355 pb.start();
356 fail("Expected IOException not thrown");
357 } catch (IOException e) {
358 String m = e.getMessage();
359 if (EnglishUnix.is() &&
360 ! matches(m, "No such file"))
361 unexpected(e);
362 } catch (Throwable t) { unexpected(t); }
363
364 // Not on PATH at all; directories exist
365 new File("dir1").mkdirs();
366 new File("dir2").mkdirs();
367 try {
368 pb.start();
369 fail("Expected IOException not thrown");
370 } catch (IOException e) {
371 String m = e.getMessage();
372 if (EnglishUnix.is() &&
373 ! matches(m, "No such file"))
374 unexpected(e);
375 } catch (Throwable t) { unexpected(t); }
376
377 // Can't execute a directory -- permission denied
378 // Report EACCES errno
379 new File("dir1/prog").mkdirs();
martin2ea07df2009-06-14 14:23:22 -0700380 checkPermissionDenied(pb);
duke6e45e102007-12-01 00:00:00 +0000381
382 // continue searching if EACCES
383 copy("/bin/true", "dir2/prog");
martin2ea07df2009-06-14 14:23:22 -0700384 equal(run(pb).exitValue(), True.exitValue());
duke6e45e102007-12-01 00:00:00 +0000385 new File("dir1/prog").delete();
386 new File("dir2/prog").delete();
387
388 new File("dir2/prog").mkdirs();
389 copy("/bin/true", "dir1/prog");
martin2ea07df2009-06-14 14:23:22 -0700390 equal(run(pb).exitValue(), True.exitValue());
duke6e45e102007-12-01 00:00:00 +0000391
martin2ea07df2009-06-14 14:23:22 -0700392 // Check empty PATH component means current directory.
393 //
394 // While we're here, let's test different kinds of
395 // Unix executables, and PATH vs explicit searching.
duke6e45e102007-12-01 00:00:00 +0000396 new File("dir1/prog").delete();
397 new File("dir2/prog").delete();
martin2ea07df2009-06-14 14:23:22 -0700398 for (String[] command :
399 new String[][] {
400 new String[] {"./prog"},
401 cmd}) {
402 pb.command(command);
403 File prog = new File("./prog");
404 // "Normal" binaries
405 copy("/bin/true", "./prog");
406 equal(run(pb).exitValue(),
407 True.exitValue());
408 copy("/bin/false", "./prog");
409 equal(run(pb).exitValue(),
410 False.exitValue());
411 prog.delete();
412 // Interpreter scripts with #!
413 setFileContents(prog, "#!/bin/true\n");
414 prog.setExecutable(true);
415 equal(run(pb).exitValue(),
416 True.exitValue());
417 prog.delete();
418 setFileContents(prog, "#!/bin/false\n");
419 prog.setExecutable(true);
420 equal(run(pb).exitValue(),
421 False.exitValue());
422 // Traditional shell scripts without #!
423 setFileContents(prog, "exec /bin/true\n");
424 prog.setExecutable(true);
425 equal(run(pb).exitValue(),
426 True.exitValue());
427 prog.delete();
428 setFileContents(prog, "exec /bin/false\n");
429 prog.setExecutable(true);
430 equal(run(pb).exitValue(),
431 False.exitValue());
432 prog.delete();
433 }
434
435 // Test Unix interpreter scripts
436 File dir1Prog = new File("dir1/prog");
437 dir1Prog.delete();
438 pb.command(new String[] {"prog", "world"});
439 setFileContents(dir1Prog, "#!/bin/echo hello\n");
440 checkPermissionDenied(pb);
441 dir1Prog.setExecutable(true);
442 equal(run(pb).out(), "hello dir1/prog world\n");
443 equal(run(pb).exitValue(), True.exitValue());
444 dir1Prog.delete();
445 pb.command(cmd);
446
447 // Test traditional shell scripts without #!
448 setFileContents(dir1Prog, "/bin/echo \"$@\"\n");
449 pb.command(new String[] {"prog", "hello", "world"});
450 checkPermissionDenied(pb);
451 dir1Prog.setExecutable(true);
452 equal(run(pb).out(), "hello world\n");
453 equal(run(pb).exitValue(), True.exitValue());
454 dir1Prog.delete();
455 pb.command(cmd);
duke6e45e102007-12-01 00:00:00 +0000456
457 // If prog found on both parent and child's PATH,
458 // parent's is used.
459 new File("dir1/prog").delete();
460 new File("dir2/prog").delete();
461 new File("prog").delete();
462 new File("dir3").mkdirs();
463 copy("/bin/true", "dir1/prog");
464 copy("/bin/false", "dir3/prog");
465 pb.environment().put("PATH","dir3");
martin2ea07df2009-06-14 14:23:22 -0700466 equal(run(pb).exitValue(), True.exitValue());
duke6e45e102007-12-01 00:00:00 +0000467 copy("/bin/true", "dir3/prog");
468 copy("/bin/false", "dir1/prog");
martin2ea07df2009-06-14 14:23:22 -0700469 equal(run(pb).exitValue(), False.exitValue());
duke6e45e102007-12-01 00:00:00 +0000470
471 } finally {
472 // cleanup
473 new File("dir1/prog").delete();
474 new File("dir2/prog").delete();
475 new File("dir3/prog").delete();
476 new File("dir1").delete();
477 new File("dir2").delete();
478 new File("dir3").delete();
479 new File("prog").delete();
480 }
481 }
482
483 if (failed != 0) throw new Error("PATH search algorithm");
484 }
485 else throw new Error("JavaChild invocation error");
486 }
487 }
488
489 private static void copy(String src, String dst) {
490 system("/bin/cp", "-fp", src, dst);
491 }
492
493 private static void system(String... command) {
494 try {
495 ProcessBuilder pb = new ProcessBuilder(command);
496 ProcessResults r = run(pb.start());
497 equal(r.exitValue(), 0);
498 equal(r.out(), "");
499 equal(r.err(), "");
500 } catch (Throwable t) { unexpected(t); }
501 }
502
503 private static String javaChildOutput(ProcessBuilder pb, String...args) {
504 List<String> list = new ArrayList<String>(javaChildArgs);
505 for (String arg : args)
506 list.add(arg);
507 pb.command(list);
508 return commandOutput(pb);
509 }
510
511 private static String getenvInChild(ProcessBuilder pb) {
512 return javaChildOutput(pb, "System.getenv()");
513 }
514
515 private static String getenvInChild1234(ProcessBuilder pb) {
516 return javaChildOutput(pb, "System.getenv(\\u1234)");
517 }
518
519 private static String getenvInChild(ProcessBuilder pb, String name) {
520 return javaChildOutput(pb, "System.getenv(String)", name);
521 }
522
523 private static String pwdInChild(ProcessBuilder pb) {
524 return javaChildOutput(pb, "pwd");
525 }
526
527 private static final String javaExe =
528 System.getProperty("java.home") +
529 File.separator + "bin" + File.separator + "java";
530
531 private static final String classpath =
532 System.getProperty("java.class.path");
533
534 private static final List<String> javaChildArgs =
535 Arrays.asList(new String[]
536 { javaExe, "-classpath", absolutifyPath(classpath),
537 "Basic$JavaChild"});
538
539 private static void testEncoding(String encoding, String tested) {
540 try {
541 // If round trip conversion works, should be able to set env vars
542 // correctly in child.
543 if (new String(tested.getBytes()).equals(tested)) {
544 out.println("Testing " + encoding + " environment values");
545 ProcessBuilder pb = new ProcessBuilder();
546 pb.environment().put("ASCIINAME",tested);
547 equal(getenvInChild(pb,"ASCIINAME"), tested);
548 }
549 } catch (Throwable t) { unexpected(t); }
550 }
551
552 static class Windows {
553 public static boolean is() { return is; }
554 private static final boolean is =
555 System.getProperty("os.name").startsWith("Windows");
556 }
557
558 static class Unix {
559 public static boolean is() { return is; }
560 private static final boolean is =
561 (! Windows.is() &&
562 new File("/bin/sh").exists() &&
563 new File("/bin/true").exists() &&
564 new File("/bin/false").exists());
565 }
566
567 static class UnicodeOS {
568 public static boolean is() { return is; }
569 private static final String osName = System.getProperty("os.name");
570 private static final boolean is =
571 // MacOS X would probably also qualify
572 osName.startsWith("Windows") &&
573 ! osName.startsWith("Windows 9") &&
574 ! osName.equals("Windows Me");
575 }
576
577 static class True {
578 public static int exitValue() { return 0; }
579 }
580
581 private static class False {
582 public static int exitValue() { return exitValue; }
583 private static final int exitValue = exitValue0();
584 private static int exitValue0() {
585 // /bin/false returns an *unspecified* non-zero number.
586 try {
587 if (! Unix.is())
588 return -1;
589 else {
590 int rc = new ProcessBuilder("/bin/false")
591 .start().waitFor();
592 check(rc != 0);
593 return rc;
594 }
595 } catch (Throwable t) { unexpected(t); return -1; }
596 }
597 }
598
599 static class EnglishUnix {
600 private final static Boolean is =
601 (! Windows.is() && isEnglish("LANG") && isEnglish("LC_ALL"));
602
603 private static boolean isEnglish(String envvar) {
604 String val = getenv(envvar);
605 return (val == null) || val.matches("en.*");
606 }
607
608 /** Returns true if we can expect English OS error strings */
609 static boolean is() { return is; }
610 }
611
612 private static boolean matches(String str, String regex) {
613 return Pattern.compile(regex).matcher(str).find();
614 }
615
616 private static String sortByLinesWindowsly(String text) {
617 String[] lines = text.split("\n");
618 Arrays.sort(lines, new WindowsComparator());
619 StringBuilder sb = new StringBuilder();
620 for (String line : lines)
621 sb.append(line).append("\n");
622 return sb.toString();
623 }
624
625 private static void checkMapSanity(Map<String,String> map) {
626 try {
627 Set<String> keySet = map.keySet();
628 Collection<String> values = map.values();
629 Set<Map.Entry<String,String>> entrySet = map.entrySet();
630
631 equal(entrySet.size(), keySet.size());
632 equal(entrySet.size(), values.size());
633
634 StringBuilder s1 = new StringBuilder();
635 for (Map.Entry<String,String> e : entrySet)
636 s1.append(e.getKey() + "=" + e.getValue() + "\n");
637
638 StringBuilder s2 = new StringBuilder();
639 for (String var : keySet)
640 s2.append(var + "=" + map.get(var) + "\n");
641
642 equal(s1.toString(), s2.toString());
643
644 Iterator<String> kIter = keySet.iterator();
645 Iterator<String> vIter = values.iterator();
646 Iterator<Map.Entry<String,String>> eIter = entrySet.iterator();
647
648 while (eIter.hasNext()) {
649 Map.Entry<String,String> entry = eIter.next();
650 String key = kIter.next();
651 String value = vIter.next();
652 check(entrySet.contains(entry));
653 check(keySet.contains(key));
654 check(values.contains(value));
655 check(map.containsKey(key));
656 check(map.containsValue(value));
657 equal(entry.getKey(), key);
658 equal(entry.getValue(), value);
659 }
660 check(! kIter.hasNext() &&
661 ! vIter.hasNext());
662
663 } catch (Throwable t) { unexpected(t); }
664 }
665
666 private static void checkMapEquality(Map<String,String> map1,
667 Map<String,String> map2) {
668 try {
669 equal(map1.size(), map2.size());
670 equal(map1.isEmpty(), map2.isEmpty());
671 for (String key : map1.keySet()) {
672 equal(map1.get(key), map2.get(key));
673 check(map2.keySet().contains(key));
674 }
675 equal(map1, map2);
676 equal(map2, map1);
677 equal(map1.entrySet(), map2.entrySet());
678 equal(map2.entrySet(), map1.entrySet());
679 equal(map1.keySet(), map2.keySet());
680 equal(map2.keySet(), map1.keySet());
681
682 equal(map1.hashCode(), map2.hashCode());
683 equal(map1.entrySet().hashCode(), map2.entrySet().hashCode());
684 equal(map1.keySet().hashCode(), map2.keySet().hashCode());
685 } catch (Throwable t) { unexpected(t); }
686 }
687
martindd2fd9f2008-03-10 14:32:51 -0700688 static void checkRedirects(ProcessBuilder pb,
689 Redirect in, Redirect out, Redirect err) {
690 equal(pb.redirectInput(), in);
691 equal(pb.redirectOutput(), out);
692 equal(pb.redirectError(), err);
693 }
694
695 static void redirectIO(ProcessBuilder pb,
696 Redirect in, Redirect out, Redirect err) {
697 pb.redirectInput(in);
698 pb.redirectOutput(out);
699 pb.redirectError(err);
700 }
701
702 static void setFileContents(File file, String contents) {
703 try {
704 Writer w = new FileWriter(file);
705 w.write(contents);
706 w.close();
707 } catch (Throwable t) { unexpected(t); }
708 }
709
710 static String fileContents(File file) {
711 try {
712 Reader r = new FileReader(file);
713 StringBuilder sb = new StringBuilder();
714 char[] buffer = new char[1024];
715 int n;
716 while ((n = r.read(buffer)) != -1)
717 sb.append(buffer,0,n);
718 r.close();
719 return new String(sb);
720 } catch (Throwable t) { unexpected(t); return ""; }
721 }
722
723 static void testIORedirection() throws Throwable {
724 final File ifile = new File("ifile");
725 final File ofile = new File("ofile");
726 final File efile = new File("efile");
727 ifile.delete();
728 ofile.delete();
729 efile.delete();
730
731 //----------------------------------------------------------------
732 // Check mutual inequality of different types of Redirect
733 //----------------------------------------------------------------
734 Redirect[] redirects =
735 { PIPE,
736 INHERIT,
737 Redirect.from(ifile),
738 Redirect.to(ifile),
739 Redirect.appendTo(ifile),
740 Redirect.from(ofile),
741 Redirect.to(ofile),
742 Redirect.appendTo(ofile),
743 };
744 for (int i = 0; i < redirects.length; i++)
745 for (int j = 0; j < redirects.length; j++)
746 equal(redirects[i].equals(redirects[j]), (i == j));
747
748 //----------------------------------------------------------------
749 // Check basic properties of different types of Redirect
750 //----------------------------------------------------------------
751 equal(PIPE.type(), Redirect.Type.PIPE);
752 equal(PIPE.toString(), "PIPE");
753 equal(PIPE.file(), null);
754
755 equal(INHERIT.type(), Redirect.Type.INHERIT);
756 equal(INHERIT.toString(), "INHERIT");
757 equal(INHERIT.file(), null);
758
759 equal(Redirect.from(ifile).type(), Redirect.Type.READ);
760 equal(Redirect.from(ifile).toString(),
761 "redirect to read from file \"ifile\"");
762 equal(Redirect.from(ifile).file(), ifile);
763 equal(Redirect.from(ifile),
764 Redirect.from(ifile));
765 equal(Redirect.from(ifile).hashCode(),
766 Redirect.from(ifile).hashCode());
767
768 equal(Redirect.to(ofile).type(), Redirect.Type.WRITE);
769 equal(Redirect.to(ofile).toString(),
770 "redirect to write to file \"ofile\"");
771 equal(Redirect.to(ofile).file(), ofile);
772 equal(Redirect.to(ofile),
773 Redirect.to(ofile));
774 equal(Redirect.to(ofile).hashCode(),
775 Redirect.to(ofile).hashCode());
776
777 equal(Redirect.appendTo(ofile).type(), Redirect.Type.APPEND);
778 equal(Redirect.appendTo(efile).toString(),
779 "redirect to append to file \"efile\"");
780 equal(Redirect.appendTo(efile).file(), efile);
781 equal(Redirect.appendTo(efile),
782 Redirect.appendTo(efile));
783 equal(Redirect.appendTo(efile).hashCode(),
784 Redirect.appendTo(efile).hashCode());
785
786 //----------------------------------------------------------------
787 // Check initial values of redirects
788 //----------------------------------------------------------------
789 List<String> childArgs = new ArrayList<String>(javaChildArgs);
790 childArgs.add("testIO");
791 final ProcessBuilder pb = new ProcessBuilder(childArgs);
792 checkRedirects(pb, PIPE, PIPE, PIPE);
793
794 //----------------------------------------------------------------
795 // Check inheritIO
796 //----------------------------------------------------------------
797 pb.inheritIO();
798 checkRedirects(pb, INHERIT, INHERIT, INHERIT);
799
800 //----------------------------------------------------------------
801 // Check setters and getters agree
802 //----------------------------------------------------------------
803 pb.redirectInput(ifile);
804 equal(pb.redirectInput().file(), ifile);
805 equal(pb.redirectInput(), Redirect.from(ifile));
806
807 pb.redirectOutput(ofile);
808 equal(pb.redirectOutput().file(), ofile);
809 equal(pb.redirectOutput(), Redirect.to(ofile));
810
811 pb.redirectError(efile);
812 equal(pb.redirectError().file(), efile);
813 equal(pb.redirectError(), Redirect.to(efile));
814
815 THROWS(IllegalArgumentException.class,
816 new Fun(){void f() {
817 pb.redirectInput(Redirect.to(ofile)); }},
818 new Fun(){void f() {
819 pb.redirectInput(Redirect.appendTo(ofile)); }},
820 new Fun(){void f() {
821 pb.redirectOutput(Redirect.from(ifile)); }},
822 new Fun(){void f() {
823 pb.redirectError(Redirect.from(ifile)); }});
824
825 THROWS(IOException.class,
826 // Input file does not exist
827 new Fun(){void f() throws Throwable { pb.start(); }});
828 setFileContents(ifile, "standard input");
829
830 //----------------------------------------------------------------
831 // Writing to non-existent files
832 //----------------------------------------------------------------
833 {
834 ProcessResults r = run(pb);
835 equal(r.exitValue(), 0);
836 equal(fileContents(ofile), "standard output");
837 equal(fileContents(efile), "standard error");
838 equal(r.out(), "");
839 equal(r.err(), "");
840 ofile.delete();
841 efile.delete();
842 }
843
844 //----------------------------------------------------------------
845 // Both redirectErrorStream + redirectError
846 //----------------------------------------------------------------
847 {
848 pb.redirectErrorStream(true);
849 ProcessResults r = run(pb);
850 equal(r.exitValue(), 0);
851 equal(fileContents(ofile),
852 "standard error" + "standard output");
853 equal(fileContents(efile), "");
854 equal(r.out(), "");
855 equal(r.err(), "");
856 ofile.delete();
857 efile.delete();
858 }
859
860 //----------------------------------------------------------------
861 // Appending to existing files
862 //----------------------------------------------------------------
863 {
864 setFileContents(ofile, "ofile-contents");
865 setFileContents(efile, "efile-contents");
866 pb.redirectOutput(Redirect.appendTo(ofile));
867 pb.redirectError(Redirect.appendTo(efile));
868 pb.redirectErrorStream(false);
869 ProcessResults r = run(pb);
870 equal(r.exitValue(), 0);
871 equal(fileContents(ofile),
872 "ofile-contents" + "standard output");
873 equal(fileContents(efile),
874 "efile-contents" + "standard error");
875 equal(r.out(), "");
876 equal(r.err(), "");
877 ofile.delete();
878 efile.delete();
879 }
880
881 //----------------------------------------------------------------
882 // Replacing existing files
883 //----------------------------------------------------------------
884 {
885 setFileContents(ofile, "ofile-contents");
886 setFileContents(efile, "efile-contents");
887 pb.redirectOutput(ofile);
888 pb.redirectError(Redirect.to(efile));
889 ProcessResults r = run(pb);
890 equal(r.exitValue(), 0);
891 equal(fileContents(ofile), "standard output");
892 equal(fileContents(efile), "standard error");
893 equal(r.out(), "");
894 equal(r.err(), "");
895 ofile.delete();
896 efile.delete();
897 }
898
899 //----------------------------------------------------------------
900 // Appending twice to the same file?
901 //----------------------------------------------------------------
902 {
903 setFileContents(ofile, "ofile-contents");
904 setFileContents(efile, "efile-contents");
905 Redirect appender = Redirect.appendTo(ofile);
906 pb.redirectOutput(appender);
907 pb.redirectError(appender);
908 ProcessResults r = run(pb);
909 equal(r.exitValue(), 0);
910 equal(fileContents(ofile),
911 "ofile-contents" +
912 "standard error" +
913 "standard output");
914 equal(fileContents(efile), "efile-contents");
915 equal(r.out(), "");
916 equal(r.err(), "");
917 ifile.delete();
918 ofile.delete();
919 efile.delete();
920 }
921
922 //----------------------------------------------------------------
923 // Testing INHERIT is harder.
924 // Note that this requires __FOUR__ nested JVMs involved in one test,
925 // if you count the harness JVM.
926 //----------------------------------------------------------------
927 {
928 redirectIO(pb, PIPE, PIPE, PIPE);
929 List<String> command = pb.command();
930 command.set(command.size() - 1, "testInheritIO");
931 Process p = pb.start();
932 new PrintStream(p.getOutputStream()).print("standard input");
933 p.getOutputStream().close();
934 ProcessResults r = run(p);
935 equal(r.exitValue(), 0);
936 equal(r.out(), "standard output");
937 equal(r.err(), "standard error");
938 }
939
940 //----------------------------------------------------------------
941 // Test security implications of I/O redirection
942 //----------------------------------------------------------------
943
944 // Read access to current directory is always granted;
945 // So create a tmpfile for input instead.
946 final File tmpFile = File.createTempFile("Basic", "tmp");
947 setFileContents(tmpFile, "standard input");
948
949 final Policy policy = new Policy();
950 Policy.setPolicy(policy);
951 System.setSecurityManager(new SecurityManager());
952 try {
953 final Permission xPermission
954 = new FilePermission("<<ALL FILES>>", "execute");
955 final Permission rxPermission
956 = new FilePermission("<<ALL FILES>>", "read,execute");
957 final Permission wxPermission
958 = new FilePermission("<<ALL FILES>>", "write,execute");
959 final Permission rwxPermission
960 = new FilePermission("<<ALL FILES>>", "read,write,execute");
961
962 THROWS(SecurityException.class,
963 new Fun() { void f() throws IOException {
964 policy.setPermissions(xPermission);
965 redirectIO(pb, from(tmpFile), PIPE, PIPE);
966 pb.start();}},
967 new Fun() { void f() throws IOException {
968 policy.setPermissions(rxPermission);
969 redirectIO(pb, PIPE, to(ofile), PIPE);
970 pb.start();}},
971 new Fun() { void f() throws IOException {
972 policy.setPermissions(rxPermission);
973 redirectIO(pb, PIPE, PIPE, to(efile));
974 pb.start();}});
975
976 {
977 policy.setPermissions(rxPermission);
978 redirectIO(pb, from(tmpFile), PIPE, PIPE);
979 ProcessResults r = run(pb);
980 equal(r.out(), "standard output");
981 equal(r.err(), "standard error");
982 }
983
984 {
985 policy.setPermissions(wxPermission);
986 redirectIO(pb, PIPE, to(ofile), to(efile));
987 Process p = pb.start();
988 new PrintStream(p.getOutputStream()).print("standard input");
989 p.getOutputStream().close();
990 ProcessResults r = run(p);
991 policy.setPermissions(rwxPermission);
992 equal(fileContents(ofile), "standard output");
993 equal(fileContents(efile), "standard error");
994 }
995
996 {
997 policy.setPermissions(rwxPermission);
998 redirectIO(pb, from(tmpFile), to(ofile), to(efile));
999 ProcessResults r = run(pb);
1000 policy.setPermissions(rwxPermission);
1001 equal(fileContents(ofile), "standard output");
1002 equal(fileContents(efile), "standard error");
1003 }
1004
1005 } finally {
1006 policy.setPermissions(new RuntimePermission("setSecurityManager"));
1007 System.setSecurityManager(null);
1008 tmpFile.delete();
1009 ifile.delete();
1010 ofile.delete();
1011 efile.delete();
1012 }
1013 }
1014
duke6e45e102007-12-01 00:00:00 +00001015 private static void realMain(String[] args) throws Throwable {
1016 if (Windows.is())
1017 System.out.println("This appears to be a Windows system.");
1018 if (Unix.is())
1019 System.out.println("This appears to be a Unix system.");
1020 if (UnicodeOS.is())
1021 System.out.println("This appears to be a Unicode-based OS.");
1022
martindd2fd9f2008-03-10 14:32:51 -07001023 try { testIORedirection(); }
1024 catch (Throwable t) { unexpected(t); }
1025
duke6e45e102007-12-01 00:00:00 +00001026 //----------------------------------------------------------------
1027 // Basic tests for setting, replacing and deleting envvars
1028 //----------------------------------------------------------------
1029 try {
1030 ProcessBuilder pb = new ProcessBuilder();
1031 Map<String,String> environ = pb.environment();
1032
1033 // New env var
1034 environ.put("QUUX", "BAR");
1035 equal(environ.get("QUUX"), "BAR");
1036 equal(getenvInChild(pb,"QUUX"), "BAR");
1037
1038 // Modify env var
1039 environ.put("QUUX","bear");
1040 equal(environ.get("QUUX"), "bear");
1041 equal(getenvInChild(pb,"QUUX"), "bear");
1042 checkMapSanity(environ);
1043
1044 // Remove env var
1045 environ.remove("QUUX");
1046 equal(environ.get("QUUX"), null);
1047 equal(getenvInChild(pb,"QUUX"), "null");
1048 checkMapSanity(environ);
1049
1050 // Remove non-existent env var
1051 environ.remove("QUUX");
1052 equal(environ.get("QUUX"), null);
1053 equal(getenvInChild(pb,"QUUX"), "null");
1054 checkMapSanity(environ);
1055 } catch (Throwable t) { unexpected(t); }
1056
1057 //----------------------------------------------------------------
1058 // Pass Empty environment to child
1059 //----------------------------------------------------------------
1060 try {
1061 ProcessBuilder pb = new ProcessBuilder();
1062 pb.environment().clear();
1063 equal(getenvInChild(pb), "");
1064 } catch (Throwable t) { unexpected(t); }
1065
1066 //----------------------------------------------------------------
1067 // System.getenv() is read-only.
1068 //----------------------------------------------------------------
1069 THROWS(UnsupportedOperationException.class,
1070 new Fun(){void f(){ getenv().put("FOO","BAR");}},
1071 new Fun(){void f(){ getenv().remove("PATH");}},
1072 new Fun(){void f(){ getenv().keySet().remove("PATH");}},
1073 new Fun(){void f(){ getenv().values().remove("someValue");}});
1074
1075 try {
1076 Collection<Map.Entry<String,String>> c = getenv().entrySet();
1077 if (! c.isEmpty())
1078 try {
1079 c.iterator().next().setValue("foo");
1080 fail("Expected UnsupportedOperationException not thrown");
1081 } catch (UnsupportedOperationException e) {} // OK
1082 } catch (Throwable t) { unexpected(t); }
1083
1084 //----------------------------------------------------------------
1085 // System.getenv() always returns the same object in our implementation.
1086 //----------------------------------------------------------------
1087 try {
1088 check(System.getenv() == System.getenv());
1089 } catch (Throwable t) { unexpected(t); }
1090
1091 //----------------------------------------------------------------
1092 // You can't create an env var name containing "=",
1093 // or an env var name or value containing NUL.
1094 //----------------------------------------------------------------
1095 {
1096 final Map<String,String> m = new ProcessBuilder().environment();
1097 THROWS(IllegalArgumentException.class,
1098 new Fun(){void f(){ m.put("FOO=","BAR");}},
1099 new Fun(){void f(){ m.put("FOO\u0000","BAR");}},
1100 new Fun(){void f(){ m.put("FOO","BAR\u0000");}});
1101 }
1102
1103 //----------------------------------------------------------------
1104 // Commands must never be null.
1105 //----------------------------------------------------------------
1106 THROWS(NullPointerException.class,
1107 new Fun(){void f(){
1108 new ProcessBuilder((List<String>)null);}},
1109 new Fun(){void f(){
1110 new ProcessBuilder().command((List<String>)null);}});
1111
1112 //----------------------------------------------------------------
1113 // Put in a command; get the same one back out.
1114 //----------------------------------------------------------------
1115 try {
1116 List<String> command = new ArrayList<String>();
1117 ProcessBuilder pb = new ProcessBuilder(command);
1118 check(pb.command() == command);
1119 List<String> command2 = new ArrayList<String>(2);
1120 command2.add("foo");
1121 command2.add("bar");
1122 pb.command(command2);
1123 check(pb.command() == command2);
1124 pb.command("foo", "bar");
1125 check(pb.command() != command2 && pb.command().equals(command2));
1126 pb.command(command2);
1127 command2.add("baz");
1128 equal(pb.command().get(2), "baz");
1129 } catch (Throwable t) { unexpected(t); }
1130
1131 //----------------------------------------------------------------
1132 // Commands must contain at least one element.
1133 //----------------------------------------------------------------
1134 THROWS(IndexOutOfBoundsException.class,
1135 new Fun() { void f() throws IOException {
1136 new ProcessBuilder().start();}},
1137 new Fun() { void f() throws IOException {
1138 new ProcessBuilder(new ArrayList<String>()).start();}},
1139 new Fun() { void f() throws IOException {
1140 Runtime.getRuntime().exec(new String[]{});}});
1141
1142 //----------------------------------------------------------------
1143 // Commands must not contain null elements at start() time.
1144 //----------------------------------------------------------------
1145 THROWS(NullPointerException.class,
1146 new Fun() { void f() throws IOException {
1147 new ProcessBuilder("foo",null,"bar").start();}},
1148 new Fun() { void f() throws IOException {
1149 new ProcessBuilder((String)null).start();}},
1150 new Fun() { void f() throws IOException {
1151 new ProcessBuilder(new String[]{null}).start();}},
1152 new Fun() { void f() throws IOException {
1153 new ProcessBuilder(new String[]{"foo",null,"bar"}).start();}});
1154
1155 //----------------------------------------------------------------
1156 // Command lists are growable.
1157 //----------------------------------------------------------------
1158 try {
1159 new ProcessBuilder().command().add("foo");
1160 new ProcessBuilder("bar").command().add("foo");
1161 new ProcessBuilder(new String[]{"1","2"}).command().add("3");
1162 } catch (Throwable t) { unexpected(t); }
1163
1164 //----------------------------------------------------------------
1165 // Nulls in environment updates generate NullPointerException
1166 //----------------------------------------------------------------
1167 try {
1168 final Map<String,String> env = new ProcessBuilder().environment();
1169 THROWS(NullPointerException.class,
1170 new Fun(){void f(){ env.put("foo",null);}},
1171 new Fun(){void f(){ env.put(null,"foo");}},
1172 new Fun(){void f(){ env.remove(null);}},
1173 new Fun(){void f(){
1174 for (Map.Entry<String,String> e : env.entrySet())
1175 e.setValue(null);}},
1176 new Fun() { void f() throws IOException {
1177 Runtime.getRuntime().exec(new String[]{"foo"},
1178 new String[]{null});}});
1179 } catch (Throwable t) { unexpected(t); }
1180
1181 //----------------------------------------------------------------
1182 // Non-String types in environment updates generate ClassCastException
1183 //----------------------------------------------------------------
1184 try {
1185 final Map<String,String> env = new ProcessBuilder().environment();
1186 THROWS(ClassCastException.class,
1187 new Fun(){void f(){ env.remove(TRUE);}},
1188 new Fun(){void f(){ env.keySet().remove(TRUE);}},
1189 new Fun(){void f(){ env.values().remove(TRUE);}},
1190 new Fun(){void f(){ env.entrySet().remove(TRUE);}});
1191 } catch (Throwable t) { unexpected(t); }
1192
1193 //----------------------------------------------------------------
1194 // Check query operations on environment maps
1195 //----------------------------------------------------------------
1196 try {
1197 List<Map<String,String>> envs =
1198 new ArrayList<Map<String,String>>(2);
1199 envs.add(System.getenv());
1200 envs.add(new ProcessBuilder().environment());
1201 for (final Map<String,String> env : envs) {
1202 //----------------------------------------------------------------
1203 // Nulls in environment queries are forbidden.
1204 //----------------------------------------------------------------
1205 THROWS(NullPointerException.class,
1206 new Fun(){void f(){ getenv(null);}},
1207 new Fun(){void f(){ env.get(null);}},
1208 new Fun(){void f(){ env.containsKey(null);}},
1209 new Fun(){void f(){ env.containsValue(null);}},
1210 new Fun(){void f(){ env.keySet().contains(null);}},
1211 new Fun(){void f(){ env.values().contains(null);}});
1212
1213 //----------------------------------------------------------------
1214 // Non-String types in environment queries are forbidden.
1215 //----------------------------------------------------------------
1216 THROWS(ClassCastException.class,
1217 new Fun(){void f(){ env.get(TRUE);}},
1218 new Fun(){void f(){ env.containsKey(TRUE);}},
1219 new Fun(){void f(){ env.containsValue(TRUE);}},
1220 new Fun(){void f(){ env.keySet().contains(TRUE);}},
1221 new Fun(){void f(){ env.values().contains(TRUE);}});
1222
1223 //----------------------------------------------------------------
1224 // Illegal String values in environment queries are (grumble) OK
1225 //----------------------------------------------------------------
1226 equal(env.get("\u0000"), null);
1227 check(! env.containsKey("\u0000"));
1228 check(! env.containsValue("\u0000"));
1229 check(! env.keySet().contains("\u0000"));
1230 check(! env.values().contains("\u0000"));
1231 }
1232
1233 } catch (Throwable t) { unexpected(t); }
1234
1235 try {
1236 final Set<Map.Entry<String,String>> entrySet =
1237 new ProcessBuilder().environment().entrySet();
1238 THROWS(NullPointerException.class,
1239 new Fun(){void f(){ entrySet.contains(null);}});
1240 THROWS(ClassCastException.class,
1241 new Fun(){void f(){ entrySet.contains(TRUE);}},
1242 new Fun(){void f(){
1243 entrySet.contains(
1244 new SimpleImmutableEntry<Boolean,String>(TRUE,""));}});
1245
1246 check(! entrySet.contains
1247 (new SimpleImmutableEntry<String,String>("", "")));
1248 } catch (Throwable t) { unexpected(t); }
1249
1250 //----------------------------------------------------------------
1251 // Put in a directory; get the same one back out.
1252 //----------------------------------------------------------------
1253 try {
1254 ProcessBuilder pb = new ProcessBuilder();
1255 File foo = new File("foo");
1256 equal(pb.directory(), null);
1257 equal(pb.directory(foo).directory(), foo);
1258 equal(pb.directory(null).directory(), null);
1259 } catch (Throwable t) { unexpected(t); }
1260
1261 //----------------------------------------------------------------
1262 // If round-trip conversion works, check envvar pass-through to child
1263 //----------------------------------------------------------------
1264 try {
1265 testEncoding("ASCII", "xyzzy");
1266 testEncoding("Latin1", "\u00f1\u00e1");
1267 testEncoding("Unicode", "\u22f1\u11e1");
1268 } catch (Throwable t) { unexpected(t); }
1269
1270 //----------------------------------------------------------------
1271 // A surprisingly large number of ways to delete an environment var.
1272 //----------------------------------------------------------------
1273 testVariableDeleter(new EnvironmentFrobber() {
1274 public void doIt(Map<String,String> environ) {
1275 environ.remove("Foo");}});
1276
1277 testVariableDeleter(new EnvironmentFrobber() {
1278 public void doIt(Map<String,String> environ) {
1279 environ.keySet().remove("Foo");}});
1280
1281 testVariableDeleter(new EnvironmentFrobber() {
1282 public void doIt(Map<String,String> environ) {
1283 environ.values().remove("BAAR");}});
1284
1285 testVariableDeleter(new EnvironmentFrobber() {
1286 public void doIt(Map<String,String> environ) {
1287 // Legally fabricate a ProcessEnvironment.StringEntry,
1288 // even though it's private.
1289 Map<String,String> environ2
1290 = new ProcessBuilder().environment();
1291 environ2.clear();
1292 environ2.put("Foo","BAAR");
1293 // Subtlety alert.
1294 Map.Entry<String,String> e
1295 = environ2.entrySet().iterator().next();
1296 environ.entrySet().remove(e);}});
1297
1298 testVariableDeleter(new EnvironmentFrobber() {
1299 public void doIt(Map<String,String> environ) {
1300 Map.Entry<String,String> victim = null;
1301 for (Map.Entry<String,String> e : environ.entrySet())
1302 if (e.getKey().equals("Foo"))
1303 victim = e;
1304 if (victim != null)
1305 environ.entrySet().remove(victim);}});
1306
1307 testVariableDeleter(new EnvironmentFrobber() {
1308 public void doIt(Map<String,String> environ) {
1309 Iterator<String> it = environ.keySet().iterator();
1310 while (it.hasNext()) {
1311 String val = it.next();
1312 if (val.equals("Foo"))
1313 it.remove();}}});
1314
1315 testVariableDeleter(new EnvironmentFrobber() {
1316 public void doIt(Map<String,String> environ) {
1317 Iterator<Map.Entry<String,String>> it
1318 = environ.entrySet().iterator();
1319 while (it.hasNext()) {
1320 Map.Entry<String,String> e = it.next();
1321 if (e.getKey().equals("Foo"))
1322 it.remove();}}});
1323
1324 testVariableDeleter(new EnvironmentFrobber() {
1325 public void doIt(Map<String,String> environ) {
1326 Iterator<String> it = environ.values().iterator();
1327 while (it.hasNext()) {
1328 String val = it.next();
1329 if (val.equals("BAAR"))
1330 it.remove();}}});
1331
1332 //----------------------------------------------------------------
1333 // A surprisingly small number of ways to add an environment var.
1334 //----------------------------------------------------------------
1335 testVariableAdder(new EnvironmentFrobber() {
1336 public void doIt(Map<String,String> environ) {
1337 environ.put("Foo","Bahrein");}});
1338
1339 //----------------------------------------------------------------
1340 // A few ways to modify an environment var.
1341 //----------------------------------------------------------------
1342 testVariableModifier(new EnvironmentFrobber() {
1343 public void doIt(Map<String,String> environ) {
1344 environ.put("Foo","NewValue");}});
1345
1346 testVariableModifier(new EnvironmentFrobber() {
1347 public void doIt(Map<String,String> environ) {
1348 for (Map.Entry<String,String> e : environ.entrySet())
1349 if (e.getKey().equals("Foo"))
1350 e.setValue("NewValue");}});
1351
1352 //----------------------------------------------------------------
1353 // Fiddle with environment sizes
1354 //----------------------------------------------------------------
1355 try {
1356 Map<String,String> environ = new ProcessBuilder().environment();
1357 int size = environ.size();
1358 checkSizes(environ, size);
1359
1360 environ.put("UnLiKeLYeNVIROmtNam", "someVal");
1361 checkSizes(environ, size+1);
1362
1363 // Check for environment independence
1364 new ProcessBuilder().environment().clear();
1365
1366 environ.put("UnLiKeLYeNVIROmtNam", "someOtherVal");
1367 checkSizes(environ, size+1);
1368
1369 environ.remove("UnLiKeLYeNVIROmtNam");
1370 checkSizes(environ, size);
1371
1372 environ.clear();
1373 checkSizes(environ, 0);
1374
1375 environ.clear();
1376 checkSizes(environ, 0);
1377
1378 environ = new ProcessBuilder().environment();
1379 environ.keySet().clear();
1380 checkSizes(environ, 0);
1381
1382 environ = new ProcessBuilder().environment();
1383 environ.entrySet().clear();
1384 checkSizes(environ, 0);
1385
1386 environ = new ProcessBuilder().environment();
1387 environ.values().clear();
1388 checkSizes(environ, 0);
1389 } catch (Throwable t) { unexpected(t); }
1390
1391 //----------------------------------------------------------------
1392 // Check that various map invariants hold
1393 //----------------------------------------------------------------
1394 checkMapSanity(new ProcessBuilder().environment());
1395 checkMapSanity(System.getenv());
1396 checkMapEquality(new ProcessBuilder().environment(),
1397 new ProcessBuilder().environment());
1398
1399
1400 //----------------------------------------------------------------
1401 // Check effects on external "env" command.
1402 //----------------------------------------------------------------
1403 try {
1404 Set<String> env1 = new HashSet<String>
1405 (Arrays.asList(nativeEnv((String[])null).split("\n")));
1406
1407 ProcessBuilder pb = new ProcessBuilder();
1408 pb.environment().put("QwErTyUiOp","AsDfGhJk");
1409
1410 Set<String> env2 = new HashSet<String>
1411 (Arrays.asList(nativeEnv(pb).split("\n")));
1412
1413 check(env2.size() == env1.size() + 1);
1414 env1.add("QwErTyUiOp=AsDfGhJk");
1415 check(env1.equals(env2));
1416 } catch (Throwable t) { unexpected(t); }
1417
1418 //----------------------------------------------------------------
1419 // Test Runtime.exec(...envp...)
1420 // Check for sort order of environment variables on Windows.
1421 //----------------------------------------------------------------
1422 try {
1423 // '+' < 'A' < 'Z' < '_' < 'a' < 'z' < '~'
1424 String[]envp = {"FOO=BAR","BAZ=GORP","QUUX=",
1425 "+=+", "_=_", "~=~"};
1426 String output = nativeEnv(envp);
1427 String expected = "+=+\nBAZ=GORP\nFOO=BAR\nQUUX=\n_=_\n~=~\n";
1428 // On Windows, Java must keep the environment sorted.
1429 // Order is random on Unix, so this test does the sort.
1430 if (! Windows.is())
1431 output = sortByLinesWindowsly(output);
1432 equal(output, expected);
1433 } catch (Throwable t) { unexpected(t); }
1434
1435 //----------------------------------------------------------------
1436 // System.getenv() must be consistent with System.getenv(String)
1437 //----------------------------------------------------------------
1438 try {
1439 for (Map.Entry<String,String> e : getenv().entrySet())
1440 equal(getenv(e.getKey()), e.getValue());
1441 } catch (Throwable t) { unexpected(t); }
1442
1443 //----------------------------------------------------------------
1444 // Fiddle with working directory in child
1445 //----------------------------------------------------------------
1446 try {
1447 String canonicalUserDir =
1448 new File(System.getProperty("user.dir")).getCanonicalPath();
1449 String[] sdirs = new String[]
1450 {".", "..", "/", "/bin",
1451 "C:", "c:", "C:/", "c:\\", "\\", "\\bin" };
1452 for (String sdir : sdirs) {
1453 File dir = new File(sdir);
1454 if (! (dir.isDirectory() && dir.exists()))
1455 continue;
1456 out.println("Testing directory " + dir);
1457 dir = new File(dir.getCanonicalPath());
1458
1459 ProcessBuilder pb = new ProcessBuilder();
1460 equal(pb.directory(), null);
1461 equal(pwdInChild(pb), canonicalUserDir);
1462
1463 pb.directory(dir);
1464 equal(pb.directory(), dir);
1465 equal(pwdInChild(pb), dir.toString());
1466
1467 pb.directory(null);
1468 equal(pb.directory(), null);
1469 equal(pwdInChild(pb), canonicalUserDir);
1470
1471 pb.directory(dir);
1472 }
1473 } catch (Throwable t) { unexpected(t); }
1474
1475 //----------------------------------------------------------------
1476 // Windows has tricky semi-case-insensitive semantics
1477 //----------------------------------------------------------------
1478 if (Windows.is())
1479 try {
1480 out.println("Running case insensitve variable tests");
1481 for (String[] namePair :
1482 new String[][]
1483 { new String[]{"PATH","PaTh"},
1484 new String[]{"home","HOME"},
1485 new String[]{"SYSTEMROOT","SystemRoot"}}) {
1486 check((getenv(namePair[0]) == null &&
1487 getenv(namePair[1]) == null)
1488 ||
1489 getenv(namePair[0]).equals(getenv(namePair[1])),
1490 "Windows environment variables are not case insensitive");
1491 }
1492 } catch (Throwable t) { unexpected(t); }
1493
1494 //----------------------------------------------------------------
1495 // Test proper Unicode child environment transfer
1496 //----------------------------------------------------------------
1497 if (UnicodeOS.is())
1498 try {
1499 ProcessBuilder pb = new ProcessBuilder();
1500 pb.environment().put("\u1234","\u5678");
1501 pb.environment().remove("PATH");
1502 equal(getenvInChild1234(pb), "\u5678");
1503 } catch (Throwable t) { unexpected(t); }
1504
1505
1506 //----------------------------------------------------------------
1507 // Test Runtime.exec(...envp...) with envstrings with initial `='
1508 //----------------------------------------------------------------
1509 try {
1510 List<String> childArgs = new ArrayList<String>(javaChildArgs);
1511 childArgs.add("System.getenv()");
1512 String[] cmdp = childArgs.toArray(new String[childArgs.size()]);
1513 String[] envp = {"=ExitValue=3", "=C:=\\"};
1514 Process p = Runtime.getRuntime().exec(cmdp, envp);
1515 String expected = Windows.is() ? "=C:=\\,=ExitValue=3," : "=C:=\\,";
1516 equal(commandOutput(p), expected);
1517 if (Windows.is()) {
1518 ProcessBuilder pb = new ProcessBuilder(childArgs);
1519 pb.environment().clear();
1520 pb.environment().put("=ExitValue", "3");
1521 pb.environment().put("=C:", "\\");
1522 equal(commandOutput(pb), expected);
1523 }
1524 } catch (Throwable t) { unexpected(t); }
1525
1526 //----------------------------------------------------------------
1527 // Test Runtime.exec(...envp...) with envstrings without any `='
1528 //----------------------------------------------------------------
1529 try {
1530 String[] cmdp = {"echo"};
1531 String[] envp = {"Hello", "World"}; // Yuck!
1532 Process p = Runtime.getRuntime().exec(cmdp, envp);
1533 equal(commandOutput(p), "\n");
1534 } catch (Throwable t) { unexpected(t); }
1535
1536 //----------------------------------------------------------------
1537 // Test Runtime.exec(...envp...) with envstrings containing NULs
1538 //----------------------------------------------------------------
1539 try {
1540 List<String> childArgs = new ArrayList<String>(javaChildArgs);
1541 childArgs.add("System.getenv()");
1542 String[] cmdp = childArgs.toArray(new String[childArgs.size()]);
1543 String[] envp = {"LC_ALL=C\u0000\u0000", // Yuck!
1544 "FO\u0000=B\u0000R"};
1545 Process p = Runtime.getRuntime().exec(cmdp, envp);
1546 check(commandOutput(p).equals("LC_ALL=C,"),
1547 "Incorrect handling of envstrings containing NULs");
1548 } catch (Throwable t) { unexpected(t); }
1549
1550 //----------------------------------------------------------------
1551 // Test the redirectErrorStream property
1552 //----------------------------------------------------------------
1553 try {
1554 ProcessBuilder pb = new ProcessBuilder();
1555 equal(pb.redirectErrorStream(), false);
1556 equal(pb.redirectErrorStream(true), pb);
1557 equal(pb.redirectErrorStream(), true);
1558 equal(pb.redirectErrorStream(false), pb);
1559 equal(pb.redirectErrorStream(), false);
1560 } catch (Throwable t) { unexpected(t); }
1561
1562 try {
1563 List<String> childArgs = new ArrayList<String>(javaChildArgs);
1564 childArgs.add("OutErr");
1565 ProcessBuilder pb = new ProcessBuilder(childArgs);
1566 {
martin2ea07df2009-06-14 14:23:22 -07001567 ProcessResults r = run(pb);
duke6e45e102007-12-01 00:00:00 +00001568 equal(r.out(), "outout");
1569 equal(r.err(), "errerr");
1570 }
1571 {
1572 pb.redirectErrorStream(true);
martin2ea07df2009-06-14 14:23:22 -07001573 ProcessResults r = run(pb);
duke6e45e102007-12-01 00:00:00 +00001574 equal(r.out(), "outerrouterr");
1575 equal(r.err(), "");
1576 }
1577 } catch (Throwable t) { unexpected(t); }
1578
martin2ea07df2009-06-14 14:23:22 -07001579 if (Unix.is()) {
duke6e45e102007-12-01 00:00:00 +00001580 //----------------------------------------------------------------
1581 // We can find true and false when PATH is null
1582 //----------------------------------------------------------------
1583 try {
1584 List<String> childArgs = new ArrayList<String>(javaChildArgs);
1585 childArgs.add("null PATH");
1586 ProcessBuilder pb = new ProcessBuilder(childArgs);
1587 pb.environment().remove("PATH");
martin2ea07df2009-06-14 14:23:22 -07001588 ProcessResults r = run(pb);
duke6e45e102007-12-01 00:00:00 +00001589 equal(r.out(), "");
1590 equal(r.err(), "");
1591 equal(r.exitValue(), 0);
1592 } catch (Throwable t) { unexpected(t); }
1593
1594 //----------------------------------------------------------------
1595 // PATH search algorithm on Unix
1596 //----------------------------------------------------------------
1597 try {
1598 List<String> childArgs = new ArrayList<String>(javaChildArgs);
1599 childArgs.add("PATH search algorithm");
1600 ProcessBuilder pb = new ProcessBuilder(childArgs);
1601 pb.environment().put("PATH", "dir1:dir2:");
martin2ea07df2009-06-14 14:23:22 -07001602 ProcessResults r = run(pb);
duke6e45e102007-12-01 00:00:00 +00001603 equal(r.out(), "");
1604 equal(r.err(), "");
1605 equal(r.exitValue(), True.exitValue());
1606 } catch (Throwable t) { unexpected(t); }
1607
1608 //----------------------------------------------------------------
1609 // Parent's, not child's PATH is used
1610 //----------------------------------------------------------------
1611 try {
1612 new File("suBdiR").mkdirs();
1613 copy("/bin/true", "suBdiR/unliKely");
1614 final ProcessBuilder pb =
1615 new ProcessBuilder(new String[]{"unliKely"});
1616 pb.environment().put("PATH", "suBdiR");
1617 THROWS(IOException.class,
1618 new Fun() {void f() throws Throwable {pb.start();}});
1619 } catch (Throwable t) { unexpected(t);
1620 } finally {
1621 new File("suBdiR/unliKely").delete();
1622 new File("suBdiR").delete();
1623 }
1624 }
1625
1626 //----------------------------------------------------------------
1627 // Attempt to start bogus program ""
1628 //----------------------------------------------------------------
1629 try {
1630 new ProcessBuilder("").start();
1631 fail("Expected IOException not thrown");
1632 } catch (IOException e) {
1633 String m = e.getMessage();
1634 if (EnglishUnix.is() &&
1635 ! matches(m, "No such file or directory"))
1636 unexpected(e);
1637 } catch (Throwable t) { unexpected(t); }
1638
1639 //----------------------------------------------------------------
1640 // Check that attempt to execute program name with funny
1641 // characters throws an exception containing those characters.
1642 //----------------------------------------------------------------
1643 for (String programName : new String[] {"\u00f0", "\u01f0"})
1644 try {
1645 new ProcessBuilder(programName).start();
1646 fail("Expected IOException not thrown");
1647 } catch (IOException e) {
1648 String m = e.getMessage();
1649 Pattern p = Pattern.compile(programName);
1650 if (! matches(m, programName)
1651 || (EnglishUnix.is()
1652 && ! matches(m, "No such file or directory")))
1653 unexpected(e);
1654 } catch (Throwable t) { unexpected(t); }
1655
1656 //----------------------------------------------------------------
1657 // Attempt to start process in nonexistent directory fails.
1658 //----------------------------------------------------------------
1659 try {
1660 new ProcessBuilder("echo")
1661 .directory(new File("UnLiKeLY"))
1662 .start();
1663 fail("Expected IOException not thrown");
1664 } catch (IOException e) {
1665 String m = e.getMessage();
1666 if (! matches(m, "in directory")
1667 || (EnglishUnix.is() &&
1668 ! matches(m, "No such file or directory")))
1669 unexpected(e);
1670 } catch (Throwable t) { unexpected(t); }
1671
1672 //----------------------------------------------------------------
1673 // This would deadlock, if not for the fact that
1674 // interprocess pipe buffers are at least 4096 bytes.
1675 //----------------------------------------------------------------
1676 try {
1677 List<String> childArgs = new ArrayList<String>(javaChildArgs);
1678 childArgs.add("print4095");
1679 Process p = new ProcessBuilder(childArgs).start();
1680 print4095(p.getOutputStream()); // Might hang!
1681 p.waitFor(); // Might hang!
1682 equal(p.exitValue(), 5);
1683 } catch (Throwable t) { unexpected(t); }
1684
1685 //----------------------------------------------------------------
1686 // Attempt to start process with insufficient permissions fails.
1687 //----------------------------------------------------------------
1688 try {
1689 new File("emptyCommand").delete();
1690 new FileOutputStream("emptyCommand").close();
1691 new File("emptyCommand").setExecutable(false);
1692 new ProcessBuilder("./emptyCommand").start();
1693 fail("Expected IOException not thrown");
1694 } catch (IOException e) {
1695 new File("./emptyCommand").delete();
1696 String m = e.getMessage();
1697 //e.printStackTrace();
1698 if (EnglishUnix.is() &&
1699 ! matches(m, "Permission denied"))
1700 unexpected(e);
1701 } catch (Throwable t) { unexpected(t); }
1702
1703 new File("emptyCommand").delete();
1704
1705 //----------------------------------------------------------------
1706 // Check for correct security permission behavior
1707 //----------------------------------------------------------------
1708 final Policy policy = new Policy();
1709 Policy.setPolicy(policy);
1710 System.setSecurityManager(new SecurityManager());
1711
1712 try {
1713 // No permissions required to CREATE a ProcessBuilder
1714 policy.setPermissions(/* Nothing */);
1715 new ProcessBuilder("env").directory(null).directory();
1716 new ProcessBuilder("env").directory(new File("dir")).directory();
1717 new ProcessBuilder("env").command("??").command();
1718 } catch (Throwable t) { unexpected(t); }
1719
1720 THROWS(SecurityException.class,
1721 new Fun() { void f() throws IOException {
1722 policy.setPermissions(/* Nothing */);
1723 System.getenv("foo");}},
1724 new Fun() { void f() throws IOException {
1725 policy.setPermissions(/* Nothing */);
1726 System.getenv();}},
1727 new Fun() { void f() throws IOException {
1728 policy.setPermissions(/* Nothing */);
1729 new ProcessBuilder("echo").start();}},
1730 new Fun() { void f() throws IOException {
1731 policy.setPermissions(/* Nothing */);
1732 Runtime.getRuntime().exec("echo");}},
1733 new Fun() { void f() throws IOException {
1734 policy.setPermissions(new RuntimePermission("getenv.bar"));
1735 System.getenv("foo");}});
1736
1737 try {
1738 policy.setPermissions(new RuntimePermission("getenv.foo"));
1739 System.getenv("foo");
1740
1741 policy.setPermissions(new RuntimePermission("getenv.*"));
1742 System.getenv("foo");
1743 System.getenv();
1744 new ProcessBuilder().environment();
1745 } catch (Throwable t) { unexpected(t); }
1746
1747
1748 final Permission execPermission
1749 = new FilePermission("<<ALL FILES>>", "execute");
1750
1751 THROWS(SecurityException.class,
1752 new Fun() { void f() throws IOException {
1753 // environment permission by itself insufficient
1754 policy.setPermissions(new RuntimePermission("getenv.*"));
1755 ProcessBuilder pb = new ProcessBuilder("env");
1756 pb.environment().put("foo","bar");
1757 pb.start();}},
1758 new Fun() { void f() throws IOException {
1759 // exec permission by itself insufficient
1760 policy.setPermissions(execPermission);
1761 ProcessBuilder pb = new ProcessBuilder("env");
1762 pb.environment().put("foo","bar");
1763 pb.start();}});
1764
1765 try {
1766 // Both permissions? OK.
1767 policy.setPermissions(new RuntimePermission("getenv.*"),
1768 execPermission);
1769 ProcessBuilder pb = new ProcessBuilder("env");
1770 pb.environment().put("foo","bar");
martindd2fd9f2008-03-10 14:32:51 -07001771 Process p = pb.start();
1772 closeStreams(p);
duke6e45e102007-12-01 00:00:00 +00001773 } catch (IOException e) { // OK
1774 } catch (Throwable t) { unexpected(t); }
1775
1776 try {
1777 // Don't need environment permission unless READING environment
1778 policy.setPermissions(execPermission);
1779 Runtime.getRuntime().exec("env", new String[]{});
1780 } catch (IOException e) { // OK
1781 } catch (Throwable t) { unexpected(t); }
1782
1783 try {
1784 // Don't need environment permission unless READING environment
1785 policy.setPermissions(execPermission);
1786 new ProcessBuilder("env").start();
1787 } catch (IOException e) { // OK
1788 } catch (Throwable t) { unexpected(t); }
1789
1790 // Restore "normal" state without a security manager
1791 policy.setPermissions(new RuntimePermission("setSecurityManager"));
1792 System.setSecurityManager(null);
1793
1794 }
1795
martindd2fd9f2008-03-10 14:32:51 -07001796 static void closeStreams(Process p) {
1797 try {
1798 p.getOutputStream().close();
1799 p.getInputStream().close();
1800 p.getErrorStream().close();
1801 } catch (Throwable t) { unexpected(t); }
1802 }
1803
duke6e45e102007-12-01 00:00:00 +00001804 //----------------------------------------------------------------
1805 // A Policy class designed to make permissions fiddling very easy.
1806 //----------------------------------------------------------------
1807 private static class Policy extends java.security.Policy {
1808 private Permissions perms;
1809
1810 public void setPermissions(Permission...permissions) {
1811 perms = new Permissions();
1812 for (Permission permission : permissions)
1813 perms.add(permission);
1814 }
1815
1816 public Policy() { setPermissions(/* Nothing */); }
1817
1818 public PermissionCollection getPermissions(CodeSource cs) {
1819 return perms;
1820 }
1821
1822 public PermissionCollection getPermissions(ProtectionDomain pd) {
1823 return perms;
1824 }
1825
1826 public boolean implies(ProtectionDomain pd, Permission p) {
1827 return perms.implies(p);
1828 }
1829
1830 public void refresh() {}
1831 }
1832
1833 private static class StreamAccumulator extends Thread {
1834 private final InputStream is;
1835 private final StringBuilder sb = new StringBuilder();
1836 private Throwable throwable = null;
1837
1838 public String result () throws Throwable {
1839 if (throwable != null)
1840 throw throwable;
1841 return sb.toString();
1842 }
1843
1844 StreamAccumulator (InputStream is) {
1845 this.is = is;
1846 }
1847
1848 public void run() {
1849 try {
1850 Reader r = new InputStreamReader(is);
1851 char[] buf = new char[4096];
1852 int n;
1853 while ((n = r.read(buf)) > 0) {
1854 sb.append(buf,0,n);
1855 }
1856 } catch (Throwable t) {
1857 throwable = t;
martindd2fd9f2008-03-10 14:32:51 -07001858 } finally {
1859 try { is.close(); }
1860 catch (Throwable t) { throwable = t; }
duke6e45e102007-12-01 00:00:00 +00001861 }
1862 }
1863 }
1864
martindd2fd9f2008-03-10 14:32:51 -07001865 static ProcessResults run(ProcessBuilder pb) {
1866 try {
1867 return run(pb.start());
1868 } catch (Throwable t) { unexpected(t); return null; }
1869 }
1870
duke6e45e102007-12-01 00:00:00 +00001871 private static ProcessResults run(Process p) {
1872 Throwable throwable = null;
1873 int exitValue = -1;
1874 String out = "";
1875 String err = "";
1876
1877 StreamAccumulator outAccumulator =
1878 new StreamAccumulator(p.getInputStream());
1879 StreamAccumulator errAccumulator =
1880 new StreamAccumulator(p.getErrorStream());
1881
1882 try {
1883 outAccumulator.start();
1884 errAccumulator.start();
1885
1886 exitValue = p.waitFor();
1887
1888 outAccumulator.join();
1889 errAccumulator.join();
1890
1891 out = outAccumulator.result();
1892 err = errAccumulator.result();
1893 } catch (Throwable t) {
1894 throwable = t;
1895 }
1896
1897 return new ProcessResults(out, err, exitValue, throwable);
1898 }
1899
1900 //----------------------------------------------------------------
1901 // Results of a command
1902 //----------------------------------------------------------------
1903 private static class ProcessResults {
1904 private final String out;
1905 private final String err;
1906 private final int exitValue;
1907 private final Throwable throwable;
1908
1909 public ProcessResults(String out,
1910 String err,
1911 int exitValue,
1912 Throwable throwable) {
1913 this.out = out;
1914 this.err = err;
1915 this.exitValue = exitValue;
1916 this.throwable = throwable;
1917 }
1918
1919 public String out() { return out; }
1920 public String err() { return err; }
1921 public int exitValue() { return exitValue; }
1922 public Throwable throwable() { return throwable; }
1923
1924 public String toString() {
1925 StringBuilder sb = new StringBuilder();
1926 sb.append("<STDOUT>\n" + out() + "</STDOUT>\n")
1927 .append("<STDERR>\n" + err() + "</STDERR>\n")
1928 .append("exitValue = " + exitValue + "\n");
1929 if (throwable != null)
1930 sb.append(throwable.getStackTrace());
1931 return sb.toString();
1932 }
1933 }
1934
1935 //--------------------- Infrastructure ---------------------------
1936 static volatile int passed = 0, failed = 0;
1937 static void pass() {passed++;}
1938 static void fail() {failed++; Thread.dumpStack();}
1939 static void fail(String msg) {System.out.println(msg); fail();}
1940 static void unexpected(Throwable t) {failed++; t.printStackTrace();}
1941 static void check(boolean cond) {if (cond) pass(); else fail();}
1942 static void check(boolean cond, String m) {if (cond) pass(); else fail(m);}
1943 static void equal(Object x, Object y) {
1944 if (x == null ? y == null : x.equals(y)) pass();
1945 else fail(x + " not equal to " + y);}
1946 public static void main(String[] args) throws Throwable {
1947 try {realMain(args);} catch (Throwable t) {unexpected(t);}
1948 System.out.printf("%nPassed = %d, failed = %d%n%n", passed, failed);
1949 if (failed > 0) throw new AssertionError("Some tests failed");}
1950 private static abstract class Fun {abstract void f() throws Throwable;}
1951 static void THROWS(Class<? extends Throwable> k, Fun... fs) {
1952 for (Fun f : fs)
1953 try { f.f(); fail("Expected " + k.getName() + " not thrown"); }
1954 catch (Throwable t) {
1955 if (k.isAssignableFrom(t.getClass())) pass();
1956 else unexpected(t);}}
1957}