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