blob: afb8ea8210e92b7bb8d6d26f3675ea5ee7a18528 [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
martin07f8b422009-09-08 14:33:59 -070028 * 6464154 6523983 6206031 4960438 6631352 6631966 6850957 6850958
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()));
martin07f8b422009-09-08 14:33:59 -0700305 } else if (action.equals("ArrayOOME")) {
306 Object dummy;
307 switch(new Random().nextInt(3)) {
308 case 0: dummy = new Integer[Integer.MAX_VALUE]; break;
309 case 1: dummy = new double[Integer.MAX_VALUE]; break;
310 case 2: dummy = new byte[Integer.MAX_VALUE][]; break;
311 default: throw new InternalError();
312 }
duke6e45e102007-12-01 00:00:00 +0000313 } else if (action.equals("pwd")) {
314 printUTF8(new File(System.getProperty("user.dir"))
315 .getCanonicalPath());
316 } else if (action.equals("print4095")) {
317 print4095(System.out);
318 System.exit(5);
319 } else if (action.equals("OutErr")) {
320 // You might think the system streams would be
321 // buffered, and in fact they are implemented using
322 // BufferedOutputStream, but each and every print
323 // causes immediate operating system I/O.
324 System.out.print("out");
325 System.err.print("err");
326 System.out.print("out");
327 System.err.print("err");
328 } else if (action.equals("null PATH")) {
329 equal(System.getenv("PATH"), null);
330 check(new File("/bin/true").exists());
331 check(new File("/bin/false").exists());
332 ProcessBuilder pb1 = new ProcessBuilder();
333 ProcessBuilder pb2 = new ProcessBuilder();
334 pb2.environment().put("PATH", "anyOldPathIgnoredAnyways");
335 ProcessResults r;
336
337 for (final ProcessBuilder pb :
338 new ProcessBuilder[] {pb1, pb2}) {
339 pb.command("true");
martin2ea07df2009-06-14 14:23:22 -0700340 equal(run(pb).exitValue(), True.exitValue());
duke6e45e102007-12-01 00:00:00 +0000341
342 pb.command("false");
martin2ea07df2009-06-14 14:23:22 -0700343 equal(run(pb).exitValue(), False.exitValue());
duke6e45e102007-12-01 00:00:00 +0000344 }
345
346 if (failed != 0) throw new Error("null PATH");
347 } else if (action.equals("PATH search algorithm")) {
348 equal(System.getenv("PATH"), "dir1:dir2:");
349 check(new File("/bin/true").exists());
350 check(new File("/bin/false").exists());
351 String[] cmd = {"prog"};
352 ProcessBuilder pb1 = new ProcessBuilder(cmd);
353 ProcessBuilder pb2 = new ProcessBuilder(cmd);
354 ProcessBuilder pb3 = new ProcessBuilder(cmd);
355 pb2.environment().put("PATH", "anyOldPathIgnoredAnyways");
356 pb3.environment().remove("PATH");
357
358 for (final ProcessBuilder pb :
359 new ProcessBuilder[] {pb1, pb2, pb3}) {
360 try {
361 // Not on PATH at all; directories don't exist
362 try {
363 pb.start();
364 fail("Expected IOException not thrown");
365 } catch (IOException e) {
366 String m = e.getMessage();
367 if (EnglishUnix.is() &&
368 ! matches(m, "No such file"))
369 unexpected(e);
370 } catch (Throwable t) { unexpected(t); }
371
372 // Not on PATH at all; directories exist
373 new File("dir1").mkdirs();
374 new File("dir2").mkdirs();
375 try {
376 pb.start();
377 fail("Expected IOException not thrown");
378 } catch (IOException e) {
379 String m = e.getMessage();
380 if (EnglishUnix.is() &&
381 ! matches(m, "No such file"))
382 unexpected(e);
383 } catch (Throwable t) { unexpected(t); }
384
385 // Can't execute a directory -- permission denied
386 // Report EACCES errno
387 new File("dir1/prog").mkdirs();
martin2ea07df2009-06-14 14:23:22 -0700388 checkPermissionDenied(pb);
duke6e45e102007-12-01 00:00:00 +0000389
390 // continue searching if EACCES
391 copy("/bin/true", "dir2/prog");
martin2ea07df2009-06-14 14:23:22 -0700392 equal(run(pb).exitValue(), True.exitValue());
duke6e45e102007-12-01 00:00:00 +0000393 new File("dir1/prog").delete();
394 new File("dir2/prog").delete();
395
396 new File("dir2/prog").mkdirs();
397 copy("/bin/true", "dir1/prog");
martin2ea07df2009-06-14 14:23:22 -0700398 equal(run(pb).exitValue(), True.exitValue());
duke6e45e102007-12-01 00:00:00 +0000399
martin2ea07df2009-06-14 14:23:22 -0700400 // Check empty PATH component means current directory.
401 //
402 // While we're here, let's test different kinds of
403 // Unix executables, and PATH vs explicit searching.
duke6e45e102007-12-01 00:00:00 +0000404 new File("dir1/prog").delete();
405 new File("dir2/prog").delete();
martin2ea07df2009-06-14 14:23:22 -0700406 for (String[] command :
407 new String[][] {
408 new String[] {"./prog"},
409 cmd}) {
410 pb.command(command);
411 File prog = new File("./prog");
412 // "Normal" binaries
413 copy("/bin/true", "./prog");
414 equal(run(pb).exitValue(),
415 True.exitValue());
416 copy("/bin/false", "./prog");
417 equal(run(pb).exitValue(),
418 False.exitValue());
419 prog.delete();
420 // Interpreter scripts with #!
421 setFileContents(prog, "#!/bin/true\n");
422 prog.setExecutable(true);
423 equal(run(pb).exitValue(),
424 True.exitValue());
425 prog.delete();
426 setFileContents(prog, "#!/bin/false\n");
427 prog.setExecutable(true);
428 equal(run(pb).exitValue(),
429 False.exitValue());
430 // Traditional shell scripts without #!
431 setFileContents(prog, "exec /bin/true\n");
432 prog.setExecutable(true);
433 equal(run(pb).exitValue(),
434 True.exitValue());
435 prog.delete();
436 setFileContents(prog, "exec /bin/false\n");
437 prog.setExecutable(true);
438 equal(run(pb).exitValue(),
439 False.exitValue());
440 prog.delete();
441 }
442
443 // Test Unix interpreter scripts
444 File dir1Prog = new File("dir1/prog");
445 dir1Prog.delete();
446 pb.command(new String[] {"prog", "world"});
447 setFileContents(dir1Prog, "#!/bin/echo hello\n");
448 checkPermissionDenied(pb);
449 dir1Prog.setExecutable(true);
450 equal(run(pb).out(), "hello dir1/prog world\n");
451 equal(run(pb).exitValue(), True.exitValue());
452 dir1Prog.delete();
453 pb.command(cmd);
454
455 // Test traditional shell scripts without #!
456 setFileContents(dir1Prog, "/bin/echo \"$@\"\n");
457 pb.command(new String[] {"prog", "hello", "world"});
458 checkPermissionDenied(pb);
459 dir1Prog.setExecutable(true);
460 equal(run(pb).out(), "hello world\n");
461 equal(run(pb).exitValue(), True.exitValue());
462 dir1Prog.delete();
463 pb.command(cmd);
duke6e45e102007-12-01 00:00:00 +0000464
465 // If prog found on both parent and child's PATH,
466 // parent's is used.
467 new File("dir1/prog").delete();
468 new File("dir2/prog").delete();
469 new File("prog").delete();
470 new File("dir3").mkdirs();
471 copy("/bin/true", "dir1/prog");
472 copy("/bin/false", "dir3/prog");
473 pb.environment().put("PATH","dir3");
martin2ea07df2009-06-14 14:23:22 -0700474 equal(run(pb).exitValue(), True.exitValue());
duke6e45e102007-12-01 00:00:00 +0000475 copy("/bin/true", "dir3/prog");
476 copy("/bin/false", "dir1/prog");
martin2ea07df2009-06-14 14:23:22 -0700477 equal(run(pb).exitValue(), False.exitValue());
duke6e45e102007-12-01 00:00:00 +0000478
479 } finally {
480 // cleanup
481 new File("dir1/prog").delete();
482 new File("dir2/prog").delete();
483 new File("dir3/prog").delete();
484 new File("dir1").delete();
485 new File("dir2").delete();
486 new File("dir3").delete();
487 new File("prog").delete();
488 }
489 }
490
491 if (failed != 0) throw new Error("PATH search algorithm");
492 }
493 else throw new Error("JavaChild invocation error");
494 }
495 }
496
497 private static void copy(String src, String dst) {
498 system("/bin/cp", "-fp", src, dst);
499 }
500
501 private static void system(String... command) {
502 try {
503 ProcessBuilder pb = new ProcessBuilder(command);
504 ProcessResults r = run(pb.start());
505 equal(r.exitValue(), 0);
506 equal(r.out(), "");
507 equal(r.err(), "");
508 } catch (Throwable t) { unexpected(t); }
509 }
510
511 private static String javaChildOutput(ProcessBuilder pb, String...args) {
512 List<String> list = new ArrayList<String>(javaChildArgs);
513 for (String arg : args)
514 list.add(arg);
515 pb.command(list);
516 return commandOutput(pb);
517 }
518
519 private static String getenvInChild(ProcessBuilder pb) {
520 return javaChildOutput(pb, "System.getenv()");
521 }
522
523 private static String getenvInChild1234(ProcessBuilder pb) {
524 return javaChildOutput(pb, "System.getenv(\\u1234)");
525 }
526
527 private static String getenvInChild(ProcessBuilder pb, String name) {
528 return javaChildOutput(pb, "System.getenv(String)", name);
529 }
530
531 private static String pwdInChild(ProcessBuilder pb) {
532 return javaChildOutput(pb, "pwd");
533 }
534
535 private static final String javaExe =
536 System.getProperty("java.home") +
537 File.separator + "bin" + File.separator + "java";
538
539 private static final String classpath =
540 System.getProperty("java.class.path");
541
542 private static final List<String> javaChildArgs =
543 Arrays.asList(new String[]
544 { javaExe, "-classpath", absolutifyPath(classpath),
545 "Basic$JavaChild"});
546
547 private static void testEncoding(String encoding, String tested) {
548 try {
549 // If round trip conversion works, should be able to set env vars
550 // correctly in child.
551 if (new String(tested.getBytes()).equals(tested)) {
552 out.println("Testing " + encoding + " environment values");
553 ProcessBuilder pb = new ProcessBuilder();
554 pb.environment().put("ASCIINAME",tested);
555 equal(getenvInChild(pb,"ASCIINAME"), tested);
556 }
557 } catch (Throwable t) { unexpected(t); }
558 }
559
560 static class Windows {
561 public static boolean is() { return is; }
562 private static final boolean is =
563 System.getProperty("os.name").startsWith("Windows");
564 }
565
566 static class Unix {
567 public static boolean is() { return is; }
568 private static final boolean is =
569 (! Windows.is() &&
570 new File("/bin/sh").exists() &&
571 new File("/bin/true").exists() &&
572 new File("/bin/false").exists());
573 }
574
575 static class UnicodeOS {
576 public static boolean is() { return is; }
577 private static final String osName = System.getProperty("os.name");
578 private static final boolean is =
579 // MacOS X would probably also qualify
580 osName.startsWith("Windows") &&
581 ! osName.startsWith("Windows 9") &&
582 ! osName.equals("Windows Me");
583 }
584
585 static class True {
586 public static int exitValue() { return 0; }
587 }
588
589 private static class False {
590 public static int exitValue() { return exitValue; }
591 private static final int exitValue = exitValue0();
592 private static int exitValue0() {
593 // /bin/false returns an *unspecified* non-zero number.
594 try {
595 if (! Unix.is())
596 return -1;
597 else {
598 int rc = new ProcessBuilder("/bin/false")
599 .start().waitFor();
600 check(rc != 0);
601 return rc;
602 }
603 } catch (Throwable t) { unexpected(t); return -1; }
604 }
605 }
606
607 static class EnglishUnix {
608 private final static Boolean is =
609 (! Windows.is() && isEnglish("LANG") && isEnglish("LC_ALL"));
610
611 private static boolean isEnglish(String envvar) {
612 String val = getenv(envvar);
613 return (val == null) || val.matches("en.*");
614 }
615
616 /** Returns true if we can expect English OS error strings */
617 static boolean is() { return is; }
618 }
619
620 private static boolean matches(String str, String regex) {
621 return Pattern.compile(regex).matcher(str).find();
622 }
623
624 private static String sortByLinesWindowsly(String text) {
625 String[] lines = text.split("\n");
626 Arrays.sort(lines, new WindowsComparator());
627 StringBuilder sb = new StringBuilder();
628 for (String line : lines)
629 sb.append(line).append("\n");
630 return sb.toString();
631 }
632
633 private static void checkMapSanity(Map<String,String> map) {
634 try {
635 Set<String> keySet = map.keySet();
636 Collection<String> values = map.values();
637 Set<Map.Entry<String,String>> entrySet = map.entrySet();
638
639 equal(entrySet.size(), keySet.size());
640 equal(entrySet.size(), values.size());
641
642 StringBuilder s1 = new StringBuilder();
643 for (Map.Entry<String,String> e : entrySet)
644 s1.append(e.getKey() + "=" + e.getValue() + "\n");
645
646 StringBuilder s2 = new StringBuilder();
647 for (String var : keySet)
648 s2.append(var + "=" + map.get(var) + "\n");
649
650 equal(s1.toString(), s2.toString());
651
652 Iterator<String> kIter = keySet.iterator();
653 Iterator<String> vIter = values.iterator();
654 Iterator<Map.Entry<String,String>> eIter = entrySet.iterator();
655
656 while (eIter.hasNext()) {
657 Map.Entry<String,String> entry = eIter.next();
658 String key = kIter.next();
659 String value = vIter.next();
660 check(entrySet.contains(entry));
661 check(keySet.contains(key));
662 check(values.contains(value));
663 check(map.containsKey(key));
664 check(map.containsValue(value));
665 equal(entry.getKey(), key);
666 equal(entry.getValue(), value);
667 }
668 check(! kIter.hasNext() &&
669 ! vIter.hasNext());
670
671 } catch (Throwable t) { unexpected(t); }
672 }
673
674 private static void checkMapEquality(Map<String,String> map1,
675 Map<String,String> map2) {
676 try {
677 equal(map1.size(), map2.size());
678 equal(map1.isEmpty(), map2.isEmpty());
679 for (String key : map1.keySet()) {
680 equal(map1.get(key), map2.get(key));
681 check(map2.keySet().contains(key));
682 }
683 equal(map1, map2);
684 equal(map2, map1);
685 equal(map1.entrySet(), map2.entrySet());
686 equal(map2.entrySet(), map1.entrySet());
687 equal(map1.keySet(), map2.keySet());
688 equal(map2.keySet(), map1.keySet());
689
690 equal(map1.hashCode(), map2.hashCode());
691 equal(map1.entrySet().hashCode(), map2.entrySet().hashCode());
692 equal(map1.keySet().hashCode(), map2.keySet().hashCode());
693 } catch (Throwable t) { unexpected(t); }
694 }
695
martindd2fd9f2008-03-10 14:32:51 -0700696 static void checkRedirects(ProcessBuilder pb,
697 Redirect in, Redirect out, Redirect err) {
698 equal(pb.redirectInput(), in);
699 equal(pb.redirectOutput(), out);
700 equal(pb.redirectError(), err);
701 }
702
703 static void redirectIO(ProcessBuilder pb,
704 Redirect in, Redirect out, Redirect err) {
705 pb.redirectInput(in);
706 pb.redirectOutput(out);
707 pb.redirectError(err);
708 }
709
710 static void setFileContents(File file, String contents) {
711 try {
712 Writer w = new FileWriter(file);
713 w.write(contents);
714 w.close();
715 } catch (Throwable t) { unexpected(t); }
716 }
717
718 static String fileContents(File file) {
719 try {
720 Reader r = new FileReader(file);
721 StringBuilder sb = new StringBuilder();
722 char[] buffer = new char[1024];
723 int n;
724 while ((n = r.read(buffer)) != -1)
725 sb.append(buffer,0,n);
726 r.close();
727 return new String(sb);
728 } catch (Throwable t) { unexpected(t); return ""; }
729 }
730
731 static void testIORedirection() throws Throwable {
732 final File ifile = new File("ifile");
733 final File ofile = new File("ofile");
734 final File efile = new File("efile");
735 ifile.delete();
736 ofile.delete();
737 efile.delete();
738
739 //----------------------------------------------------------------
740 // Check mutual inequality of different types of Redirect
741 //----------------------------------------------------------------
742 Redirect[] redirects =
743 { PIPE,
744 INHERIT,
745 Redirect.from(ifile),
746 Redirect.to(ifile),
747 Redirect.appendTo(ifile),
748 Redirect.from(ofile),
749 Redirect.to(ofile),
750 Redirect.appendTo(ofile),
751 };
752 for (int i = 0; i < redirects.length; i++)
753 for (int j = 0; j < redirects.length; j++)
754 equal(redirects[i].equals(redirects[j]), (i == j));
755
756 //----------------------------------------------------------------
757 // Check basic properties of different types of Redirect
758 //----------------------------------------------------------------
759 equal(PIPE.type(), Redirect.Type.PIPE);
760 equal(PIPE.toString(), "PIPE");
761 equal(PIPE.file(), null);
762
763 equal(INHERIT.type(), Redirect.Type.INHERIT);
764 equal(INHERIT.toString(), "INHERIT");
765 equal(INHERIT.file(), null);
766
767 equal(Redirect.from(ifile).type(), Redirect.Type.READ);
768 equal(Redirect.from(ifile).toString(),
769 "redirect to read from file \"ifile\"");
770 equal(Redirect.from(ifile).file(), ifile);
771 equal(Redirect.from(ifile),
772 Redirect.from(ifile));
773 equal(Redirect.from(ifile).hashCode(),
774 Redirect.from(ifile).hashCode());
775
776 equal(Redirect.to(ofile).type(), Redirect.Type.WRITE);
777 equal(Redirect.to(ofile).toString(),
778 "redirect to write to file \"ofile\"");
779 equal(Redirect.to(ofile).file(), ofile);
780 equal(Redirect.to(ofile),
781 Redirect.to(ofile));
782 equal(Redirect.to(ofile).hashCode(),
783 Redirect.to(ofile).hashCode());
784
785 equal(Redirect.appendTo(ofile).type(), Redirect.Type.APPEND);
786 equal(Redirect.appendTo(efile).toString(),
787 "redirect to append to file \"efile\"");
788 equal(Redirect.appendTo(efile).file(), efile);
789 equal(Redirect.appendTo(efile),
790 Redirect.appendTo(efile));
791 equal(Redirect.appendTo(efile).hashCode(),
792 Redirect.appendTo(efile).hashCode());
793
794 //----------------------------------------------------------------
795 // Check initial values of redirects
796 //----------------------------------------------------------------
797 List<String> childArgs = new ArrayList<String>(javaChildArgs);
798 childArgs.add("testIO");
799 final ProcessBuilder pb = new ProcessBuilder(childArgs);
800 checkRedirects(pb, PIPE, PIPE, PIPE);
801
802 //----------------------------------------------------------------
803 // Check inheritIO
804 //----------------------------------------------------------------
805 pb.inheritIO();
806 checkRedirects(pb, INHERIT, INHERIT, INHERIT);
807
808 //----------------------------------------------------------------
809 // Check setters and getters agree
810 //----------------------------------------------------------------
811 pb.redirectInput(ifile);
812 equal(pb.redirectInput().file(), ifile);
813 equal(pb.redirectInput(), Redirect.from(ifile));
814
815 pb.redirectOutput(ofile);
816 equal(pb.redirectOutput().file(), ofile);
817 equal(pb.redirectOutput(), Redirect.to(ofile));
818
819 pb.redirectError(efile);
820 equal(pb.redirectError().file(), efile);
821 equal(pb.redirectError(), Redirect.to(efile));
822
823 THROWS(IllegalArgumentException.class,
824 new Fun(){void f() {
825 pb.redirectInput(Redirect.to(ofile)); }},
826 new Fun(){void f() {
827 pb.redirectInput(Redirect.appendTo(ofile)); }},
828 new Fun(){void f() {
829 pb.redirectOutput(Redirect.from(ifile)); }},
830 new Fun(){void f() {
831 pb.redirectError(Redirect.from(ifile)); }});
832
833 THROWS(IOException.class,
834 // Input file does not exist
835 new Fun(){void f() throws Throwable { pb.start(); }});
836 setFileContents(ifile, "standard input");
837
838 //----------------------------------------------------------------
839 // Writing to non-existent files
840 //----------------------------------------------------------------
841 {
842 ProcessResults r = run(pb);
843 equal(r.exitValue(), 0);
844 equal(fileContents(ofile), "standard output");
845 equal(fileContents(efile), "standard error");
846 equal(r.out(), "");
847 equal(r.err(), "");
848 ofile.delete();
849 efile.delete();
850 }
851
852 //----------------------------------------------------------------
853 // Both redirectErrorStream + redirectError
854 //----------------------------------------------------------------
855 {
856 pb.redirectErrorStream(true);
857 ProcessResults r = run(pb);
858 equal(r.exitValue(), 0);
859 equal(fileContents(ofile),
860 "standard error" + "standard output");
861 equal(fileContents(efile), "");
862 equal(r.out(), "");
863 equal(r.err(), "");
864 ofile.delete();
865 efile.delete();
866 }
867
868 //----------------------------------------------------------------
869 // Appending to existing files
870 //----------------------------------------------------------------
871 {
872 setFileContents(ofile, "ofile-contents");
873 setFileContents(efile, "efile-contents");
874 pb.redirectOutput(Redirect.appendTo(ofile));
875 pb.redirectError(Redirect.appendTo(efile));
876 pb.redirectErrorStream(false);
877 ProcessResults r = run(pb);
878 equal(r.exitValue(), 0);
879 equal(fileContents(ofile),
880 "ofile-contents" + "standard output");
881 equal(fileContents(efile),
882 "efile-contents" + "standard error");
883 equal(r.out(), "");
884 equal(r.err(), "");
885 ofile.delete();
886 efile.delete();
887 }
888
889 //----------------------------------------------------------------
890 // Replacing existing files
891 //----------------------------------------------------------------
892 {
893 setFileContents(ofile, "ofile-contents");
894 setFileContents(efile, "efile-contents");
895 pb.redirectOutput(ofile);
896 pb.redirectError(Redirect.to(efile));
897 ProcessResults r = run(pb);
898 equal(r.exitValue(), 0);
899 equal(fileContents(ofile), "standard output");
900 equal(fileContents(efile), "standard error");
901 equal(r.out(), "");
902 equal(r.err(), "");
903 ofile.delete();
904 efile.delete();
905 }
906
907 //----------------------------------------------------------------
908 // Appending twice to the same file?
909 //----------------------------------------------------------------
910 {
911 setFileContents(ofile, "ofile-contents");
912 setFileContents(efile, "efile-contents");
913 Redirect appender = Redirect.appendTo(ofile);
914 pb.redirectOutput(appender);
915 pb.redirectError(appender);
916 ProcessResults r = run(pb);
917 equal(r.exitValue(), 0);
918 equal(fileContents(ofile),
919 "ofile-contents" +
920 "standard error" +
921 "standard output");
922 equal(fileContents(efile), "efile-contents");
923 equal(r.out(), "");
924 equal(r.err(), "");
925 ifile.delete();
926 ofile.delete();
927 efile.delete();
928 }
929
930 //----------------------------------------------------------------
931 // Testing INHERIT is harder.
932 // Note that this requires __FOUR__ nested JVMs involved in one test,
933 // if you count the harness JVM.
934 //----------------------------------------------------------------
935 {
936 redirectIO(pb, PIPE, PIPE, PIPE);
937 List<String> command = pb.command();
938 command.set(command.size() - 1, "testInheritIO");
939 Process p = pb.start();
940 new PrintStream(p.getOutputStream()).print("standard input");
941 p.getOutputStream().close();
942 ProcessResults r = run(p);
943 equal(r.exitValue(), 0);
944 equal(r.out(), "standard output");
945 equal(r.err(), "standard error");
946 }
947
948 //----------------------------------------------------------------
949 // Test security implications of I/O redirection
950 //----------------------------------------------------------------
951
952 // Read access to current directory is always granted;
953 // So create a tmpfile for input instead.
954 final File tmpFile = File.createTempFile("Basic", "tmp");
955 setFileContents(tmpFile, "standard input");
956
957 final Policy policy = new Policy();
958 Policy.setPolicy(policy);
959 System.setSecurityManager(new SecurityManager());
960 try {
961 final Permission xPermission
962 = new FilePermission("<<ALL FILES>>", "execute");
963 final Permission rxPermission
964 = new FilePermission("<<ALL FILES>>", "read,execute");
965 final Permission wxPermission
966 = new FilePermission("<<ALL FILES>>", "write,execute");
967 final Permission rwxPermission
968 = new FilePermission("<<ALL FILES>>", "read,write,execute");
969
970 THROWS(SecurityException.class,
971 new Fun() { void f() throws IOException {
972 policy.setPermissions(xPermission);
973 redirectIO(pb, from(tmpFile), PIPE, PIPE);
974 pb.start();}},
975 new Fun() { void f() throws IOException {
976 policy.setPermissions(rxPermission);
977 redirectIO(pb, PIPE, to(ofile), PIPE);
978 pb.start();}},
979 new Fun() { void f() throws IOException {
980 policy.setPermissions(rxPermission);
981 redirectIO(pb, PIPE, PIPE, to(efile));
982 pb.start();}});
983
984 {
985 policy.setPermissions(rxPermission);
986 redirectIO(pb, from(tmpFile), PIPE, PIPE);
987 ProcessResults r = run(pb);
988 equal(r.out(), "standard output");
989 equal(r.err(), "standard error");
990 }
991
992 {
993 policy.setPermissions(wxPermission);
994 redirectIO(pb, PIPE, to(ofile), to(efile));
995 Process p = pb.start();
996 new PrintStream(p.getOutputStream()).print("standard input");
997 p.getOutputStream().close();
998 ProcessResults r = run(p);
999 policy.setPermissions(rwxPermission);
1000 equal(fileContents(ofile), "standard output");
1001 equal(fileContents(efile), "standard error");
1002 }
1003
1004 {
1005 policy.setPermissions(rwxPermission);
1006 redirectIO(pb, from(tmpFile), to(ofile), to(efile));
1007 ProcessResults r = run(pb);
1008 policy.setPermissions(rwxPermission);
1009 equal(fileContents(ofile), "standard output");
1010 equal(fileContents(efile), "standard error");
1011 }
1012
1013 } finally {
1014 policy.setPermissions(new RuntimePermission("setSecurityManager"));
1015 System.setSecurityManager(null);
1016 tmpFile.delete();
1017 ifile.delete();
1018 ofile.delete();
1019 efile.delete();
1020 }
1021 }
1022
duke6e45e102007-12-01 00:00:00 +00001023 private static void realMain(String[] args) throws Throwable {
1024 if (Windows.is())
1025 System.out.println("This appears to be a Windows system.");
1026 if (Unix.is())
1027 System.out.println("This appears to be a Unix system.");
1028 if (UnicodeOS.is())
1029 System.out.println("This appears to be a Unicode-based OS.");
1030
martindd2fd9f2008-03-10 14:32:51 -07001031 try { testIORedirection(); }
1032 catch (Throwable t) { unexpected(t); }
1033
duke6e45e102007-12-01 00:00:00 +00001034 //----------------------------------------------------------------
1035 // Basic tests for setting, replacing and deleting envvars
1036 //----------------------------------------------------------------
1037 try {
1038 ProcessBuilder pb = new ProcessBuilder();
1039 Map<String,String> environ = pb.environment();
1040
1041 // New env var
1042 environ.put("QUUX", "BAR");
1043 equal(environ.get("QUUX"), "BAR");
1044 equal(getenvInChild(pb,"QUUX"), "BAR");
1045
1046 // Modify env var
1047 environ.put("QUUX","bear");
1048 equal(environ.get("QUUX"), "bear");
1049 equal(getenvInChild(pb,"QUUX"), "bear");
1050 checkMapSanity(environ);
1051
1052 // Remove env var
1053 environ.remove("QUUX");
1054 equal(environ.get("QUUX"), null);
1055 equal(getenvInChild(pb,"QUUX"), "null");
1056 checkMapSanity(environ);
1057
1058 // Remove non-existent env var
1059 environ.remove("QUUX");
1060 equal(environ.get("QUUX"), null);
1061 equal(getenvInChild(pb,"QUUX"), "null");
1062 checkMapSanity(environ);
1063 } catch (Throwable t) { unexpected(t); }
1064
1065 //----------------------------------------------------------------
1066 // Pass Empty environment to child
1067 //----------------------------------------------------------------
1068 try {
1069 ProcessBuilder pb = new ProcessBuilder();
1070 pb.environment().clear();
1071 equal(getenvInChild(pb), "");
1072 } catch (Throwable t) { unexpected(t); }
1073
1074 //----------------------------------------------------------------
1075 // System.getenv() is read-only.
1076 //----------------------------------------------------------------
1077 THROWS(UnsupportedOperationException.class,
1078 new Fun(){void f(){ getenv().put("FOO","BAR");}},
1079 new Fun(){void f(){ getenv().remove("PATH");}},
1080 new Fun(){void f(){ getenv().keySet().remove("PATH");}},
1081 new Fun(){void f(){ getenv().values().remove("someValue");}});
1082
1083 try {
1084 Collection<Map.Entry<String,String>> c = getenv().entrySet();
1085 if (! c.isEmpty())
1086 try {
1087 c.iterator().next().setValue("foo");
1088 fail("Expected UnsupportedOperationException not thrown");
1089 } catch (UnsupportedOperationException e) {} // OK
1090 } catch (Throwable t) { unexpected(t); }
1091
1092 //----------------------------------------------------------------
1093 // System.getenv() always returns the same object in our implementation.
1094 //----------------------------------------------------------------
1095 try {
1096 check(System.getenv() == System.getenv());
1097 } catch (Throwable t) { unexpected(t); }
1098
1099 //----------------------------------------------------------------
1100 // You can't create an env var name containing "=",
1101 // or an env var name or value containing NUL.
1102 //----------------------------------------------------------------
1103 {
1104 final Map<String,String> m = new ProcessBuilder().environment();
1105 THROWS(IllegalArgumentException.class,
1106 new Fun(){void f(){ m.put("FOO=","BAR");}},
1107 new Fun(){void f(){ m.put("FOO\u0000","BAR");}},
1108 new Fun(){void f(){ m.put("FOO","BAR\u0000");}});
1109 }
1110
1111 //----------------------------------------------------------------
1112 // Commands must never be null.
1113 //----------------------------------------------------------------
1114 THROWS(NullPointerException.class,
1115 new Fun(){void f(){
1116 new ProcessBuilder((List<String>)null);}},
1117 new Fun(){void f(){
1118 new ProcessBuilder().command((List<String>)null);}});
1119
1120 //----------------------------------------------------------------
1121 // Put in a command; get the same one back out.
1122 //----------------------------------------------------------------
1123 try {
1124 List<String> command = new ArrayList<String>();
1125 ProcessBuilder pb = new ProcessBuilder(command);
1126 check(pb.command() == command);
1127 List<String> command2 = new ArrayList<String>(2);
1128 command2.add("foo");
1129 command2.add("bar");
1130 pb.command(command2);
1131 check(pb.command() == command2);
1132 pb.command("foo", "bar");
1133 check(pb.command() != command2 && pb.command().equals(command2));
1134 pb.command(command2);
1135 command2.add("baz");
1136 equal(pb.command().get(2), "baz");
1137 } catch (Throwable t) { unexpected(t); }
1138
1139 //----------------------------------------------------------------
1140 // Commands must contain at least one element.
1141 //----------------------------------------------------------------
1142 THROWS(IndexOutOfBoundsException.class,
1143 new Fun() { void f() throws IOException {
1144 new ProcessBuilder().start();}},
1145 new Fun() { void f() throws IOException {
1146 new ProcessBuilder(new ArrayList<String>()).start();}},
1147 new Fun() { void f() throws IOException {
1148 Runtime.getRuntime().exec(new String[]{});}});
1149
1150 //----------------------------------------------------------------
1151 // Commands must not contain null elements at start() time.
1152 //----------------------------------------------------------------
1153 THROWS(NullPointerException.class,
1154 new Fun() { void f() throws IOException {
1155 new ProcessBuilder("foo",null,"bar").start();}},
1156 new Fun() { void f() throws IOException {
1157 new ProcessBuilder((String)null).start();}},
1158 new Fun() { void f() throws IOException {
1159 new ProcessBuilder(new String[]{null}).start();}},
1160 new Fun() { void f() throws IOException {
1161 new ProcessBuilder(new String[]{"foo",null,"bar"}).start();}});
1162
1163 //----------------------------------------------------------------
1164 // Command lists are growable.
1165 //----------------------------------------------------------------
1166 try {
1167 new ProcessBuilder().command().add("foo");
1168 new ProcessBuilder("bar").command().add("foo");
1169 new ProcessBuilder(new String[]{"1","2"}).command().add("3");
1170 } catch (Throwable t) { unexpected(t); }
1171
1172 //----------------------------------------------------------------
1173 // Nulls in environment updates generate NullPointerException
1174 //----------------------------------------------------------------
1175 try {
1176 final Map<String,String> env = new ProcessBuilder().environment();
1177 THROWS(NullPointerException.class,
1178 new Fun(){void f(){ env.put("foo",null);}},
1179 new Fun(){void f(){ env.put(null,"foo");}},
1180 new Fun(){void f(){ env.remove(null);}},
1181 new Fun(){void f(){
1182 for (Map.Entry<String,String> e : env.entrySet())
1183 e.setValue(null);}},
1184 new Fun() { void f() throws IOException {
1185 Runtime.getRuntime().exec(new String[]{"foo"},
1186 new String[]{null});}});
1187 } catch (Throwable t) { unexpected(t); }
1188
1189 //----------------------------------------------------------------
1190 // Non-String types in environment updates generate ClassCastException
1191 //----------------------------------------------------------------
1192 try {
1193 final Map<String,String> env = new ProcessBuilder().environment();
1194 THROWS(ClassCastException.class,
1195 new Fun(){void f(){ env.remove(TRUE);}},
1196 new Fun(){void f(){ env.keySet().remove(TRUE);}},
1197 new Fun(){void f(){ env.values().remove(TRUE);}},
1198 new Fun(){void f(){ env.entrySet().remove(TRUE);}});
1199 } catch (Throwable t) { unexpected(t); }
1200
1201 //----------------------------------------------------------------
1202 // Check query operations on environment maps
1203 //----------------------------------------------------------------
1204 try {
1205 List<Map<String,String>> envs =
1206 new ArrayList<Map<String,String>>(2);
1207 envs.add(System.getenv());
1208 envs.add(new ProcessBuilder().environment());
1209 for (final Map<String,String> env : envs) {
1210 //----------------------------------------------------------------
1211 // Nulls in environment queries are forbidden.
1212 //----------------------------------------------------------------
1213 THROWS(NullPointerException.class,
1214 new Fun(){void f(){ getenv(null);}},
1215 new Fun(){void f(){ env.get(null);}},
1216 new Fun(){void f(){ env.containsKey(null);}},
1217 new Fun(){void f(){ env.containsValue(null);}},
1218 new Fun(){void f(){ env.keySet().contains(null);}},
1219 new Fun(){void f(){ env.values().contains(null);}});
1220
1221 //----------------------------------------------------------------
1222 // Non-String types in environment queries are forbidden.
1223 //----------------------------------------------------------------
1224 THROWS(ClassCastException.class,
1225 new Fun(){void f(){ env.get(TRUE);}},
1226 new Fun(){void f(){ env.containsKey(TRUE);}},
1227 new Fun(){void f(){ env.containsValue(TRUE);}},
1228 new Fun(){void f(){ env.keySet().contains(TRUE);}},
1229 new Fun(){void f(){ env.values().contains(TRUE);}});
1230
1231 //----------------------------------------------------------------
1232 // Illegal String values in environment queries are (grumble) OK
1233 //----------------------------------------------------------------
1234 equal(env.get("\u0000"), null);
1235 check(! env.containsKey("\u0000"));
1236 check(! env.containsValue("\u0000"));
1237 check(! env.keySet().contains("\u0000"));
1238 check(! env.values().contains("\u0000"));
1239 }
1240
1241 } catch (Throwable t) { unexpected(t); }
1242
1243 try {
1244 final Set<Map.Entry<String,String>> entrySet =
1245 new ProcessBuilder().environment().entrySet();
1246 THROWS(NullPointerException.class,
1247 new Fun(){void f(){ entrySet.contains(null);}});
1248 THROWS(ClassCastException.class,
1249 new Fun(){void f(){ entrySet.contains(TRUE);}},
1250 new Fun(){void f(){
1251 entrySet.contains(
1252 new SimpleImmutableEntry<Boolean,String>(TRUE,""));}});
1253
1254 check(! entrySet.contains
1255 (new SimpleImmutableEntry<String,String>("", "")));
1256 } catch (Throwable t) { unexpected(t); }
1257
1258 //----------------------------------------------------------------
1259 // Put in a directory; get the same one back out.
1260 //----------------------------------------------------------------
1261 try {
1262 ProcessBuilder pb = new ProcessBuilder();
1263 File foo = new File("foo");
1264 equal(pb.directory(), null);
1265 equal(pb.directory(foo).directory(), foo);
1266 equal(pb.directory(null).directory(), null);
1267 } catch (Throwable t) { unexpected(t); }
1268
1269 //----------------------------------------------------------------
1270 // If round-trip conversion works, check envvar pass-through to child
1271 //----------------------------------------------------------------
1272 try {
1273 testEncoding("ASCII", "xyzzy");
1274 testEncoding("Latin1", "\u00f1\u00e1");
1275 testEncoding("Unicode", "\u22f1\u11e1");
1276 } catch (Throwable t) { unexpected(t); }
1277
1278 //----------------------------------------------------------------
1279 // A surprisingly large number of ways to delete an environment var.
1280 //----------------------------------------------------------------
1281 testVariableDeleter(new EnvironmentFrobber() {
1282 public void doIt(Map<String,String> environ) {
1283 environ.remove("Foo");}});
1284
1285 testVariableDeleter(new EnvironmentFrobber() {
1286 public void doIt(Map<String,String> environ) {
1287 environ.keySet().remove("Foo");}});
1288
1289 testVariableDeleter(new EnvironmentFrobber() {
1290 public void doIt(Map<String,String> environ) {
1291 environ.values().remove("BAAR");}});
1292
1293 testVariableDeleter(new EnvironmentFrobber() {
1294 public void doIt(Map<String,String> environ) {
1295 // Legally fabricate a ProcessEnvironment.StringEntry,
1296 // even though it's private.
1297 Map<String,String> environ2
1298 = new ProcessBuilder().environment();
1299 environ2.clear();
1300 environ2.put("Foo","BAAR");
1301 // Subtlety alert.
1302 Map.Entry<String,String> e
1303 = environ2.entrySet().iterator().next();
1304 environ.entrySet().remove(e);}});
1305
1306 testVariableDeleter(new EnvironmentFrobber() {
1307 public void doIt(Map<String,String> environ) {
1308 Map.Entry<String,String> victim = null;
1309 for (Map.Entry<String,String> e : environ.entrySet())
1310 if (e.getKey().equals("Foo"))
1311 victim = e;
1312 if (victim != null)
1313 environ.entrySet().remove(victim);}});
1314
1315 testVariableDeleter(new EnvironmentFrobber() {
1316 public void doIt(Map<String,String> environ) {
1317 Iterator<String> it = environ.keySet().iterator();
1318 while (it.hasNext()) {
1319 String val = it.next();
1320 if (val.equals("Foo"))
1321 it.remove();}}});
1322
1323 testVariableDeleter(new EnvironmentFrobber() {
1324 public void doIt(Map<String,String> environ) {
1325 Iterator<Map.Entry<String,String>> it
1326 = environ.entrySet().iterator();
1327 while (it.hasNext()) {
1328 Map.Entry<String,String> e = it.next();
1329 if (e.getKey().equals("Foo"))
1330 it.remove();}}});
1331
1332 testVariableDeleter(new EnvironmentFrobber() {
1333 public void doIt(Map<String,String> environ) {
1334 Iterator<String> it = environ.values().iterator();
1335 while (it.hasNext()) {
1336 String val = it.next();
1337 if (val.equals("BAAR"))
1338 it.remove();}}});
1339
1340 //----------------------------------------------------------------
1341 // A surprisingly small number of ways to add an environment var.
1342 //----------------------------------------------------------------
1343 testVariableAdder(new EnvironmentFrobber() {
1344 public void doIt(Map<String,String> environ) {
1345 environ.put("Foo","Bahrein");}});
1346
1347 //----------------------------------------------------------------
1348 // A few ways to modify an environment var.
1349 //----------------------------------------------------------------
1350 testVariableModifier(new EnvironmentFrobber() {
1351 public void doIt(Map<String,String> environ) {
1352 environ.put("Foo","NewValue");}});
1353
1354 testVariableModifier(new EnvironmentFrobber() {
1355 public void doIt(Map<String,String> environ) {
1356 for (Map.Entry<String,String> e : environ.entrySet())
1357 if (e.getKey().equals("Foo"))
1358 e.setValue("NewValue");}});
1359
1360 //----------------------------------------------------------------
1361 // Fiddle with environment sizes
1362 //----------------------------------------------------------------
1363 try {
1364 Map<String,String> environ = new ProcessBuilder().environment();
1365 int size = environ.size();
1366 checkSizes(environ, size);
1367
1368 environ.put("UnLiKeLYeNVIROmtNam", "someVal");
1369 checkSizes(environ, size+1);
1370
1371 // Check for environment independence
1372 new ProcessBuilder().environment().clear();
1373
1374 environ.put("UnLiKeLYeNVIROmtNam", "someOtherVal");
1375 checkSizes(environ, size+1);
1376
1377 environ.remove("UnLiKeLYeNVIROmtNam");
1378 checkSizes(environ, size);
1379
1380 environ.clear();
1381 checkSizes(environ, 0);
1382
1383 environ.clear();
1384 checkSizes(environ, 0);
1385
1386 environ = new ProcessBuilder().environment();
1387 environ.keySet().clear();
1388 checkSizes(environ, 0);
1389
1390 environ = new ProcessBuilder().environment();
1391 environ.entrySet().clear();
1392 checkSizes(environ, 0);
1393
1394 environ = new ProcessBuilder().environment();
1395 environ.values().clear();
1396 checkSizes(environ, 0);
1397 } catch (Throwable t) { unexpected(t); }
1398
1399 //----------------------------------------------------------------
1400 // Check that various map invariants hold
1401 //----------------------------------------------------------------
1402 checkMapSanity(new ProcessBuilder().environment());
1403 checkMapSanity(System.getenv());
1404 checkMapEquality(new ProcessBuilder().environment(),
1405 new ProcessBuilder().environment());
1406
1407
1408 //----------------------------------------------------------------
1409 // Check effects on external "env" command.
1410 //----------------------------------------------------------------
1411 try {
1412 Set<String> env1 = new HashSet<String>
1413 (Arrays.asList(nativeEnv((String[])null).split("\n")));
1414
1415 ProcessBuilder pb = new ProcessBuilder();
1416 pb.environment().put("QwErTyUiOp","AsDfGhJk");
1417
1418 Set<String> env2 = new HashSet<String>
1419 (Arrays.asList(nativeEnv(pb).split("\n")));
1420
1421 check(env2.size() == env1.size() + 1);
1422 env1.add("QwErTyUiOp=AsDfGhJk");
1423 check(env1.equals(env2));
1424 } catch (Throwable t) { unexpected(t); }
1425
1426 //----------------------------------------------------------------
1427 // Test Runtime.exec(...envp...)
1428 // Check for sort order of environment variables on Windows.
1429 //----------------------------------------------------------------
1430 try {
1431 // '+' < 'A' < 'Z' < '_' < 'a' < 'z' < '~'
1432 String[]envp = {"FOO=BAR","BAZ=GORP","QUUX=",
1433 "+=+", "_=_", "~=~"};
1434 String output = nativeEnv(envp);
1435 String expected = "+=+\nBAZ=GORP\nFOO=BAR\nQUUX=\n_=_\n~=~\n";
1436 // On Windows, Java must keep the environment sorted.
1437 // Order is random on Unix, so this test does the sort.
1438 if (! Windows.is())
1439 output = sortByLinesWindowsly(output);
1440 equal(output, expected);
1441 } catch (Throwable t) { unexpected(t); }
1442
1443 //----------------------------------------------------------------
1444 // System.getenv() must be consistent with System.getenv(String)
1445 //----------------------------------------------------------------
1446 try {
1447 for (Map.Entry<String,String> e : getenv().entrySet())
1448 equal(getenv(e.getKey()), e.getValue());
1449 } catch (Throwable t) { unexpected(t); }
1450
1451 //----------------------------------------------------------------
1452 // Fiddle with working directory in child
1453 //----------------------------------------------------------------
1454 try {
1455 String canonicalUserDir =
1456 new File(System.getProperty("user.dir")).getCanonicalPath();
1457 String[] sdirs = new String[]
1458 {".", "..", "/", "/bin",
1459 "C:", "c:", "C:/", "c:\\", "\\", "\\bin" };
1460 for (String sdir : sdirs) {
1461 File dir = new File(sdir);
1462 if (! (dir.isDirectory() && dir.exists()))
1463 continue;
1464 out.println("Testing directory " + dir);
1465 dir = new File(dir.getCanonicalPath());
1466
1467 ProcessBuilder pb = new ProcessBuilder();
1468 equal(pb.directory(), null);
1469 equal(pwdInChild(pb), canonicalUserDir);
1470
1471 pb.directory(dir);
1472 equal(pb.directory(), dir);
1473 equal(pwdInChild(pb), dir.toString());
1474
1475 pb.directory(null);
1476 equal(pb.directory(), null);
1477 equal(pwdInChild(pb), canonicalUserDir);
1478
1479 pb.directory(dir);
1480 }
1481 } catch (Throwable t) { unexpected(t); }
1482
1483 //----------------------------------------------------------------
martin07f8b422009-09-08 14:33:59 -07001484 // OOME in child allocating maximally sized array
1485 // Test for hotspot/jvmti bug 6850957
1486 //----------------------------------------------------------------
1487 try {
1488 List<String> list = new ArrayList<String>(javaChildArgs);
1489 list.add(1, String.format("-XX:OnOutOfMemoryError=%s -version",
1490 javaExe));
1491 list.add("ArrayOOME");
1492 ProcessResults r = run(new ProcessBuilder(list));
1493 check(r.out().contains("java.lang.OutOfMemoryError:"));
1494 check(r.out().contains(javaExe));
1495 check(r.err().contains(System.getProperty("java.version")));
1496 equal(r.exitValue(), 1);
1497 } catch (Throwable t) { unexpected(t); }
1498
1499 //----------------------------------------------------------------
duke6e45e102007-12-01 00:00:00 +00001500 // Windows has tricky semi-case-insensitive semantics
1501 //----------------------------------------------------------------
1502 if (Windows.is())
1503 try {
1504 out.println("Running case insensitve variable tests");
1505 for (String[] namePair :
1506 new String[][]
1507 { new String[]{"PATH","PaTh"},
1508 new String[]{"home","HOME"},
1509 new String[]{"SYSTEMROOT","SystemRoot"}}) {
1510 check((getenv(namePair[0]) == null &&
1511 getenv(namePair[1]) == null)
1512 ||
1513 getenv(namePair[0]).equals(getenv(namePair[1])),
1514 "Windows environment variables are not case insensitive");
1515 }
1516 } catch (Throwable t) { unexpected(t); }
1517
1518 //----------------------------------------------------------------
1519 // Test proper Unicode child environment transfer
1520 //----------------------------------------------------------------
1521 if (UnicodeOS.is())
1522 try {
1523 ProcessBuilder pb = new ProcessBuilder();
1524 pb.environment().put("\u1234","\u5678");
1525 pb.environment().remove("PATH");
1526 equal(getenvInChild1234(pb), "\u5678");
1527 } catch (Throwable t) { unexpected(t); }
1528
1529
1530 //----------------------------------------------------------------
1531 // Test Runtime.exec(...envp...) with envstrings with initial `='
1532 //----------------------------------------------------------------
1533 try {
1534 List<String> childArgs = new ArrayList<String>(javaChildArgs);
1535 childArgs.add("System.getenv()");
1536 String[] cmdp = childArgs.toArray(new String[childArgs.size()]);
1537 String[] envp = {"=ExitValue=3", "=C:=\\"};
1538 Process p = Runtime.getRuntime().exec(cmdp, envp);
1539 String expected = Windows.is() ? "=C:=\\,=ExitValue=3," : "=C:=\\,";
1540 equal(commandOutput(p), expected);
1541 if (Windows.is()) {
1542 ProcessBuilder pb = new ProcessBuilder(childArgs);
1543 pb.environment().clear();
1544 pb.environment().put("=ExitValue", "3");
1545 pb.environment().put("=C:", "\\");
1546 equal(commandOutput(pb), expected);
1547 }
1548 } catch (Throwable t) { unexpected(t); }
1549
1550 //----------------------------------------------------------------
1551 // Test Runtime.exec(...envp...) with envstrings without any `='
1552 //----------------------------------------------------------------
1553 try {
1554 String[] cmdp = {"echo"};
1555 String[] envp = {"Hello", "World"}; // Yuck!
1556 Process p = Runtime.getRuntime().exec(cmdp, envp);
1557 equal(commandOutput(p), "\n");
1558 } catch (Throwable t) { unexpected(t); }
1559
1560 //----------------------------------------------------------------
1561 // Test Runtime.exec(...envp...) with envstrings containing NULs
1562 //----------------------------------------------------------------
1563 try {
1564 List<String> childArgs = new ArrayList<String>(javaChildArgs);
1565 childArgs.add("System.getenv()");
1566 String[] cmdp = childArgs.toArray(new String[childArgs.size()]);
1567 String[] envp = {"LC_ALL=C\u0000\u0000", // Yuck!
1568 "FO\u0000=B\u0000R"};
1569 Process p = Runtime.getRuntime().exec(cmdp, envp);
1570 check(commandOutput(p).equals("LC_ALL=C,"),
1571 "Incorrect handling of envstrings containing NULs");
1572 } catch (Throwable t) { unexpected(t); }
1573
1574 //----------------------------------------------------------------
1575 // Test the redirectErrorStream property
1576 //----------------------------------------------------------------
1577 try {
1578 ProcessBuilder pb = new ProcessBuilder();
1579 equal(pb.redirectErrorStream(), false);
1580 equal(pb.redirectErrorStream(true), pb);
1581 equal(pb.redirectErrorStream(), true);
1582 equal(pb.redirectErrorStream(false), pb);
1583 equal(pb.redirectErrorStream(), false);
1584 } catch (Throwable t) { unexpected(t); }
1585
1586 try {
1587 List<String> childArgs = new ArrayList<String>(javaChildArgs);
1588 childArgs.add("OutErr");
1589 ProcessBuilder pb = new ProcessBuilder(childArgs);
1590 {
martin2ea07df2009-06-14 14:23:22 -07001591 ProcessResults r = run(pb);
duke6e45e102007-12-01 00:00:00 +00001592 equal(r.out(), "outout");
1593 equal(r.err(), "errerr");
1594 }
1595 {
1596 pb.redirectErrorStream(true);
martin2ea07df2009-06-14 14:23:22 -07001597 ProcessResults r = run(pb);
duke6e45e102007-12-01 00:00:00 +00001598 equal(r.out(), "outerrouterr");
1599 equal(r.err(), "");
1600 }
1601 } catch (Throwable t) { unexpected(t); }
1602
martin2ea07df2009-06-14 14:23:22 -07001603 if (Unix.is()) {
duke6e45e102007-12-01 00:00:00 +00001604 //----------------------------------------------------------------
1605 // We can find true and false when PATH is null
1606 //----------------------------------------------------------------
1607 try {
1608 List<String> childArgs = new ArrayList<String>(javaChildArgs);
1609 childArgs.add("null PATH");
1610 ProcessBuilder pb = new ProcessBuilder(childArgs);
1611 pb.environment().remove("PATH");
martin2ea07df2009-06-14 14:23:22 -07001612 ProcessResults r = run(pb);
duke6e45e102007-12-01 00:00:00 +00001613 equal(r.out(), "");
1614 equal(r.err(), "");
1615 equal(r.exitValue(), 0);
1616 } catch (Throwable t) { unexpected(t); }
1617
1618 //----------------------------------------------------------------
1619 // PATH search algorithm on Unix
1620 //----------------------------------------------------------------
1621 try {
1622 List<String> childArgs = new ArrayList<String>(javaChildArgs);
1623 childArgs.add("PATH search algorithm");
1624 ProcessBuilder pb = new ProcessBuilder(childArgs);
1625 pb.environment().put("PATH", "dir1:dir2:");
martin2ea07df2009-06-14 14:23:22 -07001626 ProcessResults r = run(pb);
duke6e45e102007-12-01 00:00:00 +00001627 equal(r.out(), "");
1628 equal(r.err(), "");
1629 equal(r.exitValue(), True.exitValue());
1630 } catch (Throwable t) { unexpected(t); }
1631
1632 //----------------------------------------------------------------
1633 // Parent's, not child's PATH is used
1634 //----------------------------------------------------------------
1635 try {
1636 new File("suBdiR").mkdirs();
1637 copy("/bin/true", "suBdiR/unliKely");
1638 final ProcessBuilder pb =
1639 new ProcessBuilder(new String[]{"unliKely"});
1640 pb.environment().put("PATH", "suBdiR");
1641 THROWS(IOException.class,
1642 new Fun() {void f() throws Throwable {pb.start();}});
1643 } catch (Throwable t) { unexpected(t);
1644 } finally {
1645 new File("suBdiR/unliKely").delete();
1646 new File("suBdiR").delete();
1647 }
1648 }
1649
1650 //----------------------------------------------------------------
1651 // Attempt to start bogus program ""
1652 //----------------------------------------------------------------
1653 try {
1654 new ProcessBuilder("").start();
1655 fail("Expected IOException not thrown");
1656 } catch (IOException e) {
1657 String m = e.getMessage();
1658 if (EnglishUnix.is() &&
1659 ! matches(m, "No such file or directory"))
1660 unexpected(e);
1661 } catch (Throwable t) { unexpected(t); }
1662
1663 //----------------------------------------------------------------
1664 // Check that attempt to execute program name with funny
1665 // characters throws an exception containing those characters.
1666 //----------------------------------------------------------------
1667 for (String programName : new String[] {"\u00f0", "\u01f0"})
1668 try {
1669 new ProcessBuilder(programName).start();
1670 fail("Expected IOException not thrown");
1671 } catch (IOException e) {
1672 String m = e.getMessage();
1673 Pattern p = Pattern.compile(programName);
1674 if (! matches(m, programName)
1675 || (EnglishUnix.is()
1676 && ! matches(m, "No such file or directory")))
1677 unexpected(e);
1678 } catch (Throwable t) { unexpected(t); }
1679
1680 //----------------------------------------------------------------
1681 // Attempt to start process in nonexistent directory fails.
1682 //----------------------------------------------------------------
1683 try {
1684 new ProcessBuilder("echo")
1685 .directory(new File("UnLiKeLY"))
1686 .start();
1687 fail("Expected IOException not thrown");
1688 } catch (IOException e) {
1689 String m = e.getMessage();
1690 if (! matches(m, "in directory")
1691 || (EnglishUnix.is() &&
1692 ! matches(m, "No such file or directory")))
1693 unexpected(e);
1694 } catch (Throwable t) { unexpected(t); }
1695
1696 //----------------------------------------------------------------
1697 // This would deadlock, if not for the fact that
1698 // interprocess pipe buffers are at least 4096 bytes.
1699 //----------------------------------------------------------------
1700 try {
1701 List<String> childArgs = new ArrayList<String>(javaChildArgs);
1702 childArgs.add("print4095");
1703 Process p = new ProcessBuilder(childArgs).start();
1704 print4095(p.getOutputStream()); // Might hang!
1705 p.waitFor(); // Might hang!
1706 equal(p.exitValue(), 5);
1707 } catch (Throwable t) { unexpected(t); }
1708
1709 //----------------------------------------------------------------
1710 // Attempt to start process with insufficient permissions fails.
1711 //----------------------------------------------------------------
1712 try {
1713 new File("emptyCommand").delete();
1714 new FileOutputStream("emptyCommand").close();
1715 new File("emptyCommand").setExecutable(false);
1716 new ProcessBuilder("./emptyCommand").start();
1717 fail("Expected IOException not thrown");
1718 } catch (IOException e) {
1719 new File("./emptyCommand").delete();
1720 String m = e.getMessage();
1721 //e.printStackTrace();
1722 if (EnglishUnix.is() &&
1723 ! matches(m, "Permission denied"))
1724 unexpected(e);
1725 } catch (Throwable t) { unexpected(t); }
1726
1727 new File("emptyCommand").delete();
1728
1729 //----------------------------------------------------------------
1730 // Check for correct security permission behavior
1731 //----------------------------------------------------------------
1732 final Policy policy = new Policy();
1733 Policy.setPolicy(policy);
1734 System.setSecurityManager(new SecurityManager());
1735
1736 try {
1737 // No permissions required to CREATE a ProcessBuilder
1738 policy.setPermissions(/* Nothing */);
1739 new ProcessBuilder("env").directory(null).directory();
1740 new ProcessBuilder("env").directory(new File("dir")).directory();
1741 new ProcessBuilder("env").command("??").command();
1742 } catch (Throwable t) { unexpected(t); }
1743
1744 THROWS(SecurityException.class,
1745 new Fun() { void f() throws IOException {
1746 policy.setPermissions(/* Nothing */);
1747 System.getenv("foo");}},
1748 new Fun() { void f() throws IOException {
1749 policy.setPermissions(/* Nothing */);
1750 System.getenv();}},
1751 new Fun() { void f() throws IOException {
1752 policy.setPermissions(/* Nothing */);
1753 new ProcessBuilder("echo").start();}},
1754 new Fun() { void f() throws IOException {
1755 policy.setPermissions(/* Nothing */);
1756 Runtime.getRuntime().exec("echo");}},
1757 new Fun() { void f() throws IOException {
1758 policy.setPermissions(new RuntimePermission("getenv.bar"));
1759 System.getenv("foo");}});
1760
1761 try {
1762 policy.setPermissions(new RuntimePermission("getenv.foo"));
1763 System.getenv("foo");
1764
1765 policy.setPermissions(new RuntimePermission("getenv.*"));
1766 System.getenv("foo");
1767 System.getenv();
1768 new ProcessBuilder().environment();
1769 } catch (Throwable t) { unexpected(t); }
1770
1771
1772 final Permission execPermission
1773 = new FilePermission("<<ALL FILES>>", "execute");
1774
1775 THROWS(SecurityException.class,
1776 new Fun() { void f() throws IOException {
1777 // environment permission by itself insufficient
1778 policy.setPermissions(new RuntimePermission("getenv.*"));
1779 ProcessBuilder pb = new ProcessBuilder("env");
1780 pb.environment().put("foo","bar");
1781 pb.start();}},
1782 new Fun() { void f() throws IOException {
1783 // exec permission by itself insufficient
1784 policy.setPermissions(execPermission);
1785 ProcessBuilder pb = new ProcessBuilder("env");
1786 pb.environment().put("foo","bar");
1787 pb.start();}});
1788
1789 try {
1790 // Both permissions? OK.
1791 policy.setPermissions(new RuntimePermission("getenv.*"),
1792 execPermission);
1793 ProcessBuilder pb = new ProcessBuilder("env");
1794 pb.environment().put("foo","bar");
martindd2fd9f2008-03-10 14:32:51 -07001795 Process p = pb.start();
1796 closeStreams(p);
duke6e45e102007-12-01 00:00:00 +00001797 } catch (IOException e) { // OK
1798 } catch (Throwable t) { unexpected(t); }
1799
1800 try {
1801 // Don't need environment permission unless READING environment
1802 policy.setPermissions(execPermission);
1803 Runtime.getRuntime().exec("env", new String[]{});
1804 } catch (IOException e) { // OK
1805 } catch (Throwable t) { unexpected(t); }
1806
1807 try {
1808 // Don't need environment permission unless READING environment
1809 policy.setPermissions(execPermission);
1810 new ProcessBuilder("env").start();
1811 } catch (IOException e) { // OK
1812 } catch (Throwable t) { unexpected(t); }
1813
1814 // Restore "normal" state without a security manager
1815 policy.setPermissions(new RuntimePermission("setSecurityManager"));
1816 System.setSecurityManager(null);
1817
1818 }
1819
martindd2fd9f2008-03-10 14:32:51 -07001820 static void closeStreams(Process p) {
1821 try {
1822 p.getOutputStream().close();
1823 p.getInputStream().close();
1824 p.getErrorStream().close();
1825 } catch (Throwable t) { unexpected(t); }
1826 }
1827
duke6e45e102007-12-01 00:00:00 +00001828 //----------------------------------------------------------------
1829 // A Policy class designed to make permissions fiddling very easy.
1830 //----------------------------------------------------------------
1831 private static class Policy extends java.security.Policy {
1832 private Permissions perms;
1833
1834 public void setPermissions(Permission...permissions) {
1835 perms = new Permissions();
1836 for (Permission permission : permissions)
1837 perms.add(permission);
1838 }
1839
1840 public Policy() { setPermissions(/* Nothing */); }
1841
1842 public PermissionCollection getPermissions(CodeSource cs) {
1843 return perms;
1844 }
1845
1846 public PermissionCollection getPermissions(ProtectionDomain pd) {
1847 return perms;
1848 }
1849
1850 public boolean implies(ProtectionDomain pd, Permission p) {
1851 return perms.implies(p);
1852 }
1853
1854 public void refresh() {}
1855 }
1856
1857 private static class StreamAccumulator extends Thread {
1858 private final InputStream is;
1859 private final StringBuilder sb = new StringBuilder();
1860 private Throwable throwable = null;
1861
1862 public String result () throws Throwable {
1863 if (throwable != null)
1864 throw throwable;
1865 return sb.toString();
1866 }
1867
1868 StreamAccumulator (InputStream is) {
1869 this.is = is;
1870 }
1871
1872 public void run() {
1873 try {
1874 Reader r = new InputStreamReader(is);
1875 char[] buf = new char[4096];
1876 int n;
1877 while ((n = r.read(buf)) > 0) {
1878 sb.append(buf,0,n);
1879 }
1880 } catch (Throwable t) {
1881 throwable = t;
martindd2fd9f2008-03-10 14:32:51 -07001882 } finally {
1883 try { is.close(); }
1884 catch (Throwable t) { throwable = t; }
duke6e45e102007-12-01 00:00:00 +00001885 }
1886 }
1887 }
1888
martindd2fd9f2008-03-10 14:32:51 -07001889 static ProcessResults run(ProcessBuilder pb) {
1890 try {
1891 return run(pb.start());
1892 } catch (Throwable t) { unexpected(t); return null; }
1893 }
1894
duke6e45e102007-12-01 00:00:00 +00001895 private static ProcessResults run(Process p) {
1896 Throwable throwable = null;
1897 int exitValue = -1;
1898 String out = "";
1899 String err = "";
1900
1901 StreamAccumulator outAccumulator =
1902 new StreamAccumulator(p.getInputStream());
1903 StreamAccumulator errAccumulator =
1904 new StreamAccumulator(p.getErrorStream());
1905
1906 try {
1907 outAccumulator.start();
1908 errAccumulator.start();
1909
1910 exitValue = p.waitFor();
1911
1912 outAccumulator.join();
1913 errAccumulator.join();
1914
1915 out = outAccumulator.result();
1916 err = errAccumulator.result();
1917 } catch (Throwable t) {
1918 throwable = t;
1919 }
1920
1921 return new ProcessResults(out, err, exitValue, throwable);
1922 }
1923
1924 //----------------------------------------------------------------
1925 // Results of a command
1926 //----------------------------------------------------------------
1927 private static class ProcessResults {
1928 private final String out;
1929 private final String err;
1930 private final int exitValue;
1931 private final Throwable throwable;
1932
1933 public ProcessResults(String out,
1934 String err,
1935 int exitValue,
1936 Throwable throwable) {
1937 this.out = out;
1938 this.err = err;
1939 this.exitValue = exitValue;
1940 this.throwable = throwable;
1941 }
1942
1943 public String out() { return out; }
1944 public String err() { return err; }
1945 public int exitValue() { return exitValue; }
1946 public Throwable throwable() { return throwable; }
1947
1948 public String toString() {
1949 StringBuilder sb = new StringBuilder();
1950 sb.append("<STDOUT>\n" + out() + "</STDOUT>\n")
1951 .append("<STDERR>\n" + err() + "</STDERR>\n")
1952 .append("exitValue = " + exitValue + "\n");
1953 if (throwable != null)
1954 sb.append(throwable.getStackTrace());
1955 return sb.toString();
1956 }
1957 }
1958
1959 //--------------------- Infrastructure ---------------------------
1960 static volatile int passed = 0, failed = 0;
1961 static void pass() {passed++;}
1962 static void fail() {failed++; Thread.dumpStack();}
1963 static void fail(String msg) {System.out.println(msg); fail();}
1964 static void unexpected(Throwable t) {failed++; t.printStackTrace();}
1965 static void check(boolean cond) {if (cond) pass(); else fail();}
1966 static void check(boolean cond, String m) {if (cond) pass(); else fail(m);}
1967 static void equal(Object x, Object y) {
1968 if (x == null ? y == null : x.equals(y)) pass();
1969 else fail(x + " not equal to " + y);}
1970 public static void main(String[] args) throws Throwable {
1971 try {realMain(args);} catch (Throwable t) {unexpected(t);}
1972 System.out.printf("%nPassed = %d, failed = %d%n%n", passed, failed);
1973 if (failed > 0) throw new AssertionError("Some tests failed");}
1974 private static abstract class Fun {abstract void f() throws Throwable;}
1975 static void THROWS(Class<? extends Throwable> k, Fun... fs) {
1976 for (Fun f : fs)
1977 try { f.f(); fail("Expected " + k.getName() + " not thrown"); }
1978 catch (Throwable t) {
1979 if (k.isAssignableFrom(t.getClass())) pass();
1980 else unexpected(t);}}
1981}