Debian Codegraph @

rhino/toolsrc/org/mozilla/javascript/tools/shell/Global.java

raw symbols SCIP
1 /* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
2 *
3 * This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6
7 package org.mozilla.javascript.tools.shell;
8
9 import java.io.*;
10 import java.net.*;
11 import java.nio.charset.Charset;
12 import java.lang.reflect.*;
13 import java.util.ArrayList;
14 import java.util.HashMap;
15 import java.util.List;
16 import java.util.Map;
17 import java.util.regex.Pattern;
18 import java.util.regex.Matcher;
19 import org.mozilla.javascript.*;
20 import org.mozilla.javascript.commonjs.module.Require;
21 import org.mozilla.javascript.commonjs.module.RequireBuilder;
22 import org.mozilla.javascript.commonjs.module.provider.SoftCachingModuleScriptProvider;
23 import org.mozilla.javascript.commonjs.module.provider.UrlModuleSourceProvider;
24 import org.mozilla.javascript.tools.ToolErrorReporter;
25 import org.mozilla.javascript.serialize.*;
26
27 /**
28 * This class provides for sharing functions across multiple threads.
29 * This is of particular interest to server applications.
30 *
31 * @author Norris Boyd
32 */
33 public class Global extends ImporterTopLevel
34 {
35 static final long serialVersionUID = 4029130780977538005L;
36
37 NativeArray history;
38 boolean attemptedJLineLoad;
39 private ShellConsole console;
40 private InputStream inStream;
41 private PrintStream outStream;
42 private PrintStream errStream;
43 private boolean sealedStdLib = false;
44 boolean initialized;
45 private QuitAction quitAction;
46 private String[] prompts = { "js> ", " > " };
47 private HashMap<String,String> doctestCanonicalizations;
48
49 public Global()
50 {
51 }
52
53 public Global(Context cx)
54 {
55 init(cx);
56 }
57
58 public boolean isInitialized() {
59 return initialized;
60 }
61
62 /**
63 * Set the action to call from quit().
64 */
65 public void initQuitAction(QuitAction quitAction)
66 {
67 if (quitAction == null)
68 throw new IllegalArgumentException("quitAction is null");
69 if (this.quitAction != null)
70 throw new IllegalArgumentException("The method is once-call.");
71
72 this.quitAction = quitAction;
73 }
74
75 public void init(ContextFactory factory)
76 {
77 factory.call(new ContextAction() {
78 public Object run(Context cx)
79 {
80 init(cx);
81 return null;
82 }
83 });
84 }
85
86 public void init(Context cx)
87 {
88 // Define some global functions particular to the shell. Note
89 // that these functions are not part of ECMA.
90 initStandardObjects(cx, sealedStdLib);
91 String[] names = {
92 "defineClass",
93 "deserialize",
94 "doctest",
95 "gc",
96 "help",
97 "load",
98 "loadClass",
99 "print",
100 "quit",
101 "readline",
102 "readFile",
103 "readUrl",
104 "runCommand",
105 "seal",
106 "serialize",
107 "spawn",
108 "sync",
109 "toint32",
110 "version",
111 "write"
112 };
113 defineFunctionProperties(names, Global.class,
114 ScriptableObject.DONTENUM);
115
116 // Set up "environment" in the global scope to provide access to the
117 // System environment variables.
118 Environment.defineClass(this);
119 Environment environment = new Environment(this);
120 defineProperty("environment", environment,
121 ScriptableObject.DONTENUM);
122
123 history = (NativeArray) cx.newArray(this, 0);
124 defineProperty("history", history, ScriptableObject.DONTENUM);
125
126 initialized = true;
127 }
128
129 public Require installRequire(Context cx, List<String> modulePath,
130 boolean sandboxed) {
131 RequireBuilder rb = new RequireBuilder();
132 rb.setSandboxed(sandboxed);
133 List<URI> uris = new ArrayList<URI>();
134 if (modulePath != null) {
135 for (String path : modulePath) {
136 try {
137 URI uri = new URI(path);
138 if (!uri.isAbsolute()) {
139 // call resolve("") to canonify the path
140 uri = new File(path).toURI().resolve("");
141 }
142 if (!uri.toString().endsWith("/")) {
143 // make sure URI always terminates with slash to
144 // avoid loading from unintended locations
145 uri = new URI(uri + "/");
146 }
147 uris.add(uri);
148 } catch (URISyntaxException usx) {
149 throw new RuntimeException(usx);
150 }
151 }
152 }
153 rb.setModuleScriptProvider(
154 new SoftCachingModuleScriptProvider(
155 new UrlModuleSourceProvider(uris, null)));
156 Require require = rb.createRequire(cx, this);
157 require.install(this);
158 return require;
159 }
160
161 /**
162 * Print a help message.
163 *
164 * This method is defined as a JavaScript function.
165 */
166 public static void help(Context cx, Scriptable thisObj,
167 Object[] args, Function funObj)
168 {
169 PrintStream out = getInstance(funObj).getOut();
170 out.println(ToolErrorReporter.getMessage("msg.help"));
171 }
172
173 public static void gc(Context cx, Scriptable thisObj,
174 Object[] args, Function funObj)
175 {
176 System.gc();
177 }
178
179
180 /**
181 * Print the string values of its arguments.
182 *
183 * This method is defined as a JavaScript function.
184 * Note that its arguments are of the "varargs" form, which
185 * allows it to handle an arbitrary number of arguments
186 * supplied to the JavaScript function.
187 *
188 */
189 public static Object print(Context cx, Scriptable thisObj,
190 Object[] args, Function funObj)
191 {
192 return doPrint(args, funObj, true);
193 }
194
195 /**
196 * Print just as in "print," but without the trailing newline.
197 */
198 public static Object write(Context cx, Scriptable thisObj,
199 Object[] args, Function funObj)
200 {
201 return doPrint(args, funObj, false);
202 }
203
204 private static Object doPrint(Object[] args, Function funObj, boolean newline)
205 {
206 PrintStream out = getInstance(funObj).getOut();
207 for (int i=0; i < args.length; i++) {
208 if (i > 0)
209 out.print(" ");
210
211 // Convert the arbitrary JavaScript value into a string form.
212 String s = Context.toString(args[i]);
213
214 out.print(s);
215 }
216 if (newline) {
217 out.println();
218 }
219 return Context.getUndefinedValue();
220 }
221
222 /**
223 * Call embedding-specific quit action passing its argument as
224 * int32 exit code.
225 *
226 * This method is defined as a JavaScript function.
227 */
228 public static void quit(Context cx, Scriptable thisObj,
229 Object[] args, Function funObj)
230 {
231 Global global = getInstance(funObj);
232 if (global.quitAction != null) {
233 int exitCode = (args.length == 0 ? 0
234 : ScriptRuntime.toInt32(args[0]));
235 global.quitAction.quit(cx, exitCode);
236 }
237 }
238
239 /**
240 * Get and set the language version.
241 *
242 * This method is defined as a JavaScript function.
243 */
244 public static double version(Context cx, Scriptable thisObj,
245 Object[] args, Function funObj)
246 {
247 double result = cx.getLanguageVersion();
248 if (args.length > 0) {
249 double d = Context.toNumber(args[0]);
250 cx.setLanguageVersion((int) d);
251 }
252 return result;
253 }
254
255 /**
256 * Load and execute a set of JavaScript source files.
257 *
258 * This method is defined as a JavaScript function.
259 *
260 */
261 public static void load(Context cx, Scriptable thisObj,
262 Object[] args, Function funObj)
263 {
264 for (Object arg : args) {
265 String file = Context.toString(arg);
266 try {
267 Main.processFile(cx, thisObj, file);
268 } catch (IOException ioex) {
269 String msg = ToolErrorReporter.getMessage(
270 "msg.couldnt.read.source", file, ioex.getMessage());
271 throw Context.reportRuntimeError(msg);
272 } catch (VirtualMachineError ex) {
273 // Treat StackOverflow and OutOfMemory as runtime errors
274 ex.printStackTrace();
275 String msg = ToolErrorReporter.getMessage(
276 "msg.uncaughtJSException", ex.toString());
277 throw Context.reportRuntimeError(msg);
278 }
279 }
280 }
281
282 /**
283 * Load a Java class that defines a JavaScript object using the
284 * conventions outlined in ScriptableObject.defineClass.
285 * <p>
286 * This method is defined as a JavaScript function.
287 * @exception IllegalAccessException if access is not available
288 * to a reflected class member
289 * @exception InstantiationException if unable to instantiate
290 * the named class
291 * @exception InvocationTargetException if an exception is thrown
292 * during execution of methods of the named class
293 * @see org.mozilla.javascript.ScriptableObject#defineClass(Scriptable,Class)
294 */
295 @SuppressWarnings({"unchecked"})
296 public static void defineClass(Context cx, Scriptable thisObj,
297 Object[] args, Function funObj)
298 throws IllegalAccessException, InstantiationException,
299 InvocationTargetException
300 {
301 Class<?> clazz = getClass(args);
302 if (!Scriptable.class.isAssignableFrom(clazz)) {
303 throw reportRuntimeError("msg.must.implement.Scriptable");
304 }
305 ScriptableObject.defineClass(thisObj, (Class<? extends Scriptable>)clazz);
306 }
307
308 /**
309 * Load and execute a script compiled to a class file.
310 * <p>
311 * This method is defined as a JavaScript function.
312 * When called as a JavaScript function, a single argument is
313 * expected. This argument should be the name of a class that
314 * implements the Script interface, as will any script
315 * compiled by jsc.
316 *
317 * @exception IllegalAccessException if access is not available
318 * to the class
319 * @exception InstantiationException if unable to instantiate
320 * the named class
321 */
322 public static void loadClass(Context cx, Scriptable thisObj,
323 Object[] args, Function funObj)
324 throws IllegalAccessException, InstantiationException
325 {
326 Class<?> clazz = getClass(args);
327 if (!Script.class.isAssignableFrom(clazz)) {
328 throw reportRuntimeError("msg.must.implement.Script");
329 }
330 Script script = (Script) clazz.newInstance();
331 script.exec(cx, thisObj);
332 }
333
334 private static Class<?> getClass(Object[] args) {
335 if (args.length == 0) {
336 throw reportRuntimeError("msg.expected.string.arg");
337 }
338 Object arg0 = args[0];
339 if (arg0 instanceof Wrapper) {
340 Object wrapped = ((Wrapper)arg0).unwrap();
341 if (wrapped instanceof Class)
342 return (Class<?>)wrapped;
343 }
344 String className = Context.toString(args[0]);
345 try {
346 return Class.forName(className);
347 }
348 catch (ClassNotFoundException cnfe) {
349 throw reportRuntimeError("msg.class.not.found", className);
350 }
351 }
352
353 public static void serialize(Context cx, Scriptable thisObj,
354 Object[] args, Function funObj)
355 throws IOException
356 {
357 if (args.length < 2) {
358 throw Context.reportRuntimeError(
359 "Expected an object to serialize and a filename to write " +
360 "the serialization to");
361 }
362 Object obj = args[0];
363 String filename = Context.toString(args[1]);
364 FileOutputStream fos = new FileOutputStream(filename);
365 Scriptable scope = ScriptableObject.getTopLevelScope(thisObj);
366 ScriptableOutputStream out = new ScriptableOutputStream(fos, scope);
367 out.writeObject(obj);
368 out.close();
369 }
370
371 public static Object deserialize(Context cx, Scriptable thisObj,
372 Object[] args, Function funObj)
373 throws IOException, ClassNotFoundException
374 {
375 if (args.length < 1) {
376 throw Context.reportRuntimeError(
377 "Expected a filename to read the serialization from");
378 }
379 String filename = Context.toString(args[0]);
380 FileInputStream fis = new FileInputStream(filename);
381 Scriptable scope = ScriptableObject.getTopLevelScope(thisObj);
382 ObjectInputStream in = new ScriptableInputStream(fis, scope);
383 Object deserialized = in.readObject();
384 in.close();
385 return Context.toObject(deserialized, scope);
386 }
387
388 public String[] getPrompts(Context cx) {
389 if (ScriptableObject.hasProperty(this, "prompts")) {
390 Object promptsJS = ScriptableObject.getProperty(this,
391 "prompts");
392 if (promptsJS instanceof Scriptable) {
393 Scriptable s = (Scriptable) promptsJS;
394 if (ScriptableObject.hasProperty(s, 0) &&
395 ScriptableObject.hasProperty(s, 1))
396 {
397 Object elem0 = ScriptableObject.getProperty(s, 0);
398 if (elem0 instanceof Function) {
399 elem0 = ((Function) elem0).call(cx, this, s,
400 new Object[0]);
401 }
402 prompts[0] = Context.toString(elem0);
403 Object elem1 = ScriptableObject.getProperty(s, 1);
404 if (elem1 instanceof Function) {
405 elem1 = ((Function) elem1).call(cx, this, s,
406 new Object[0]);
407 }
408 prompts[1] = Context.toString(elem1);
409 }
410 }
411 }
412 return prompts;
413 }
414
415 /**
416 * Example: doctest("js> function f() {\n > return 3;\n > }\njs> f();\n3\n"); returns 2
417 * (since 2 tests were executed).
418 */
419 public static Object doctest(Context cx, Scriptable thisObj,
420 Object[] args, Function funObj) {
421 if (args.length == 0) {
422 return Boolean.FALSE;
423 }
424 String session = Context.toString(args[0]);
425 Global global = getInstance(funObj);
426 return new Integer(global.runDoctest(cx, global, session, null, 0));
427 }
428
429 public int runDoctest(Context cx, Scriptable scope, String session,
430 String sourceName, int lineNumber) {
431 doctestCanonicalizations = new HashMap<String, String>();
432 String[] lines = session.split("\r\n?|\n");
433 String prompt0 = this.prompts[0].trim();
434 String prompt1 = this.prompts[1].trim();
435 int testCount = 0;
436 int i = 0;
437 while (i < lines.length && !lines[i].trim().startsWith(prompt0)) {
438 i++; // skip lines that don't look like shell sessions
439 }
440 while (i < lines.length) {
441 String inputString = lines[i].trim().substring(prompt0.length());
442 inputString += "\n";
443 i++;
444 while (i < lines.length && lines[i].trim().startsWith(prompt1)) {
445 inputString += lines[i].trim().substring(prompt1.length());
446 inputString += "\n";
447 i++;
448 }
449 String expectedString = "";
450 while (i < lines.length &&
451 !lines[i].trim().startsWith(prompt0)) {
452 expectedString += lines[i] + "\n";
453 i++;
454 }
455 PrintStream savedOut = this.getOut();
456 PrintStream savedErr = this.getErr();
457 ByteArrayOutputStream out = new ByteArrayOutputStream();
458 ByteArrayOutputStream err = new ByteArrayOutputStream();
459 this.setOut(new PrintStream(out));
460 this.setErr(new PrintStream(err));
461 String resultString = "";
462 ErrorReporter savedErrorReporter = cx.getErrorReporter();
463 cx.setErrorReporter(new ToolErrorReporter(false, this.getErr()));
464 try {
465 testCount++;
466 Object result = cx.evaluateString(scope, inputString,
467 "doctest input", 1, null);
468 if (result != Context.getUndefinedValue() &&
469 !(result instanceof Function &&
470 inputString.trim().startsWith("function"))) {
471 resultString = Context.toString(result);
472 }
473 } catch (RhinoException e) {
474 ToolErrorReporter.reportException(cx.getErrorReporter(), e);
475 } finally {
476 this.setOut(savedOut);
477 this.setErr(savedErr);
478 cx.setErrorReporter(savedErrorReporter);
479 resultString += err.toString() + out.toString();
480 }
481 if (!doctestOutputMatches(expectedString, resultString)) {
482 String message = "doctest failure running:\n" +
483 inputString +
484 "expected: " + expectedString +
485 "actual: " + resultString + "\n";
486 if (sourceName != null) {
487 throw Context.reportRuntimeError(message, sourceName,
488 lineNumber + i - 1, null, 0);
489 } else {
490 throw Context.reportRuntimeError(message);
491 }
492 }
493 }
494 return testCount;
495 }
496
497 /**
498 * Compare actual result of doctest to expected, modulo some
499 * acceptable differences. Currently just trims the strings
500 * before comparing, but should ignore differences in line numbers
501 * for error messages for example.
502 *
503 * @param expected the expected string
504 * @param actual the actual string
505 * @return true iff actual matches expected modulo some acceptable
506 * differences
507 */
508 private boolean doctestOutputMatches(String expected, String actual) {
509 expected = expected.trim();
510 actual = actual.trim().replace("\r\n", "\n");
511 if (expected.equals(actual))
512 return true;
513 for (Map.Entry<String,String> entry: doctestCanonicalizations.entrySet()) {
514 expected = expected.replace(entry.getKey(), entry.getValue());
515 }
516 if (expected.equals(actual))
517 return true;
518 // java.lang.Object.toString() prints out a unique hex number associated
519 // with each object. This number changes from run to run, so we want to
520 // ignore differences between these numbers in the output. We search for a
521 // regexp that matches the hex number preceded by '@', then enter mappings into
522 // "doctestCanonicalizations" so that we ensure that the mappings are
523 // consistent within a session.
524 Pattern p = Pattern.compile("@[0-9a-fA-F]+");
525 Matcher expectedMatcher = p.matcher(expected);
526 Matcher actualMatcher = p.matcher(actual);
527 for (;;) {
528 if (!expectedMatcher.find())
529 return false;
530 if (!actualMatcher.find())
531 return false;
532 if (actualMatcher.start() != expectedMatcher.start())
533 return false;
534 int start = expectedMatcher.start();
535 if (!expected.substring(0, start).equals(actual.substring(0, start)))
536 return false;
537 String expectedGroup = expectedMatcher.group();
538 String actualGroup = actualMatcher.group();
539 String mapping = doctestCanonicalizations.get(expectedGroup);
540 if (mapping == null) {
541 doctestCanonicalizations.put(expectedGroup, actualGroup);
542 expected = expected.replace(expectedGroup, actualGroup);
543 } else if (!actualGroup.equals(mapping)) {
544 return false; // wrong object!
545 }
546 if (expected.equals(actual))
547 return true;
548 }
549 }
550
551 /**
552 * The spawn function runs a given function or script in a different
553 * thread.
554 *
555 * js> function g() { a = 7; }
556 * js> a = 3;
557 * 3
558 * js> spawn(g)
559 * Thread[Thread-1,5,main]
560 * js> a
561 * 3
562 */
563 public static Object spawn(Context cx, Scriptable thisObj, Object[] args,
564 Function funObj)
565 {
566 Scriptable scope = funObj.getParentScope();
567 Runner runner;
568 if (args.length != 0 && args[0] instanceof Function) {
569 Object[] newArgs = null;
570 if (args.length > 1 && args[1] instanceof Scriptable) {
571 newArgs = cx.getElements((Scriptable) args[1]);
572 }
573 if (newArgs == null) { newArgs = ScriptRuntime.emptyArgs; }
574 runner = new Runner(scope, (Function) args[0], newArgs);
575 } else if (args.length != 0 && args[0] instanceof Script) {
576 runner = new Runner(scope, (Script) args[0]);
577 } else {
578 throw reportRuntimeError("msg.spawn.args");
579 }
580 runner.factory = cx.getFactory();
581 Thread thread = new Thread(runner);
582 thread.start();
583 return thread;
584 }
585
586 /**
587 * The sync function creates a synchronized function (in the sense
588 * of a Java synchronized method) from an existing function. The
589 * new function synchronizes on the the second argument if it is
590 * defined, or otherwise the <code>this</code> object of
591 * its invocation.
592 * js> var o = { f : sync(function(x) {
593 * print("entry");
594 * Packages.java.lang.Thread.sleep(x*1000);
595 * print("exit");
596 * })};
597 * js> spawn(function() {o.f(5);});
598 * Thread[Thread-0,5,main]
599 * entry
600 * js> spawn(function() {o.f(5);});
601 * Thread[Thread-1,5,main]
602 * js>
603 * exit
604 * entry
605 * exit
606 */
607 public static Object sync(Context cx, Scriptable thisObj, Object[] args,
608 Function funObj)
609 {
610 if (args.length >= 1 && args.length <= 2 && args[0] instanceof Function) {
611 Object syncObject = null;
612 if (args.length == 2 && args[1] != Undefined.instance) {
613 syncObject = args[1];
614 }
615 return new Synchronizer((Function)args[0], syncObject);
616 }
617 else {
618 throw reportRuntimeError("msg.sync.args");
619 }
620 }
621
622 /**
623 * Execute the specified command with the given argument and options
624 * as a separate process and return the exit status of the process.
625 * <p>
626 * Usage:
627 * <pre>
628 * runCommand(command)
629 * runCommand(command, arg1, ..., argN)
630 * runCommand(command, arg1, ..., argN, options)
631 * </pre>
632 * All except the last arguments to runCommand are converted to strings
633 * and denote command name and its arguments. If the last argument is a
634 * JavaScript object, it is an option object. Otherwise it is converted to
635 * string denoting the last argument and options objects assumed to be
636 * empty.
637 * The following properties of the option object are processed:
638 * <ul>
639 * <li><tt>args</tt> - provides an array of additional command arguments
640 * <li><tt>env</tt> - explicit environment object. All its enumerable
641 * properties define the corresponding environment variable names.
642 * <li><tt>input</tt> - the process input. If it is not
643 * java.io.InputStream, it is converted to string and sent to the process
644 * as its input. If not specified, no input is provided to the process.
645 * <li><tt>output</tt> - the process output instead of
646 * java.lang.System.out. If it is not instance of java.io.OutputStream,
647 * the process output is read, converted to a string, appended to the
648 * output property value converted to string and put as the new value of
649 * the output property.
650 * <li><tt>err</tt> - the process error output instead of
651 * java.lang.System.err. If it is not instance of java.io.OutputStream,
652 * the process error output is read, converted to a string, appended to
653 * the err property value converted to string and put as the new
654 * value of the err property.
655 * <li><tt>dir</tt> - the working direcotry to run the commands.
656 * </ul>
657 */
658 public static Object runCommand(Context cx, Scriptable thisObj,
659 Object[] args, Function funObj)
660 throws IOException
661 {
662 int L = args.length;
663 if (L == 0 || (L == 1 && args[0] instanceof Scriptable)) {
664 throw reportRuntimeError("msg.runCommand.bad.args");
665 }
666 File wd = null;
667 InputStream in = null;
668 OutputStream out = null, err = null;
669 ByteArrayOutputStream outBytes = null, errBytes = null;
670 Object outObj = null, errObj = null;
671 String[] environment = null;
672 Scriptable params = null;
673 Object[] addArgs = null;
674 if (args[L - 1] instanceof Scriptable) {
675 params = (Scriptable)args[L - 1];
676 --L;
677 Object envObj = ScriptableObject.getProperty(params, "env");
678 if (envObj != Scriptable.NOT_FOUND) {
679 if (envObj == null) {
680 environment = new String[0];
681 } else {
682 if (!(envObj instanceof Scriptable)) {
683 throw reportRuntimeError("msg.runCommand.bad.env");
684 }
685 Scriptable envHash = (Scriptable)envObj;
686 Object[] ids = ScriptableObject.getPropertyIds(envHash);
687 environment = new String[ids.length];
688 for (int i = 0; i != ids.length; ++i) {
689 Object keyObj = ids[i], val;
690 String key;
691 if (keyObj instanceof String) {
692 key = (String)keyObj;
693 val = ScriptableObject.getProperty(envHash, key);
694 } else {
695 int ikey = ((Number)keyObj).intValue();
696 key = Integer.toString(ikey);
697 val = ScriptableObject.getProperty(envHash, ikey);
698 }
699 if (val == ScriptableObject.NOT_FOUND) {
700 val = Undefined.instance;
701 }
702 environment[i] = key+'='+ScriptRuntime.toString(val);
703 }
704 }
705 }
706 Object wdObj = ScriptableObject.getProperty(params, "dir");
707 if(wdObj != Scriptable.NOT_FOUND){
708 wd = new File(ScriptRuntime.toString(wdObj));
709 }
710
711 Object inObj = ScriptableObject.getProperty(params, "input");
712 if (inObj != Scriptable.NOT_FOUND) {
713 in = toInputStream(inObj);
714 }
715 outObj = ScriptableObject.getProperty(params, "output");
716 if (outObj != Scriptable.NOT_FOUND) {
717 out = toOutputStream(outObj);
718 if (out == null) {
719 outBytes = new ByteArrayOutputStream();
720 out = outBytes;
721 }
722 }
723 errObj = ScriptableObject.getProperty(params, "err");
724 if (errObj != Scriptable.NOT_FOUND) {
725 err = toOutputStream(errObj);
726 if (err == null) {
727 errBytes = new ByteArrayOutputStream();
728 err = errBytes;
729 }
730 }
731 Object addArgsObj = ScriptableObject.getProperty(params, "args");
732 if (addArgsObj != Scriptable.NOT_FOUND) {
733 Scriptable s = Context.toObject(addArgsObj,
734 getTopLevelScope(thisObj));
735 addArgs = cx.getElements(s);
736 }
737 }
738 Global global = getInstance(funObj);
739 if (out == null) {
740 out = (global != null) ? global.getOut() : System.out;
741 }
742 if (err == null) {
743 err = (global != null) ? global.getErr() : System.err;
744 }
745 // If no explicit input stream, do not send any input to process,
746 // in particular, do not use System.in to avoid deadlocks
747 // when waiting for user input to send to process which is already
748 // terminated as it is not always possible to interrupt read method.
749
750 String[] cmd = new String[(addArgs == null) ? L : L + addArgs.length];
751 for (int i = 0; i != L; ++i) {
752 cmd[i] = ScriptRuntime.toString(args[i]);
753 }
754 if (addArgs != null) {
755 for (int i = 0; i != addArgs.length; ++i) {
756 cmd[L + i] = ScriptRuntime.toString(addArgs[i]);
757 }
758 }
759
760 int exitCode = runProcess(cmd, environment, wd, in, out, err);
761 if (outBytes != null) {
762 String s = ScriptRuntime.toString(outObj) + outBytes.toString();
763 ScriptableObject.putProperty(params, "output", s);
764 }
765 if (errBytes != null) {
766 String s = ScriptRuntime.toString(errObj) + errBytes.toString();
767 ScriptableObject.putProperty(params, "err", s);
768 }
769
770 return new Integer(exitCode);
771 }
772
773 /**
774 * The seal function seals all supplied arguments.
775 */
776 public static void seal(Context cx, Scriptable thisObj, Object[] args,
777 Function funObj)
778 {
779 for (int i = 0; i != args.length; ++i) {
780 Object arg = args[i];
781 if (!(arg instanceof ScriptableObject) || arg == Undefined.instance)
782 {
783 if (!(arg instanceof Scriptable) || arg == Undefined.instance)
784 {
785 throw reportRuntimeError("msg.shell.seal.not.object");
786 } else {
787 throw reportRuntimeError("msg.shell.seal.not.scriptable");
788 }
789 }
790 }
791
792 for (int i = 0; i != args.length; ++i) {
793 Object arg = args[i];
794 ((ScriptableObject)arg).sealObject();
795 }
796 }
797
798 /**
799 * The readFile reads the given file content and convert it to a string
800 * using the specified character coding or default character coding if
801 * explicit coding argument is not given.
802 * <p>
803 * Usage:
804 * <pre>
805 * readFile(filePath)
806 * readFile(filePath, charCoding)
807 * </pre>
808 * The first form converts file's context to string using the default
809 * character coding.
810 */
811 public static Object readFile(Context cx, Scriptable thisObj, Object[] args,
812 Function funObj)
813 throws IOException
814 {
815 if (args.length == 0) {
816 throw reportRuntimeError("msg.shell.readFile.bad.args");
817 }
818 String path = ScriptRuntime.toString(args[0]);
819 String charCoding = null;
820 if (args.length >= 2) {
821 charCoding = ScriptRuntime.toString(args[1]);
822 }
823
824 return readUrl(path, charCoding, true);
825 }
826
827 /**
828 * The readUrl opens connection to the given URL, read all its data
829 * and converts them to a string
830 * using the specified character coding or default character coding if
831 * explicit coding argument is not given.
832 * <p>
833 * Usage:
834 * <pre>
835 * readUrl(url)
836 * readUrl(url, charCoding)
837 * </pre>
838 * The first form converts file's context to string using the default
839 * charCoding.
840 */
841 public static Object readUrl(Context cx, Scriptable thisObj, Object[] args,
842 Function funObj)
843 throws IOException
844 {
845 if (args.length == 0) {
846 throw reportRuntimeError("msg.shell.readUrl.bad.args");
847 }
848 String url = ScriptRuntime.toString(args[0]);
849 String charCoding = null;
850 if (args.length >= 2) {
851 charCoding = ScriptRuntime.toString(args[1]);
852 }
853
854 return readUrl(url, charCoding, false);
855 }
856
857 /**
858 * Convert the argument to int32 number.
859 */
860 public static Object toint32(Context cx, Scriptable thisObj, Object[] args,
861 Function funObj)
862 {
863 Object arg = (args.length != 0 ? args[0] : Undefined.instance);
864 if (arg instanceof Integer)
865 return arg;
866 return ScriptRuntime.wrapInt(ScriptRuntime.toInt32(arg));
867 }
868
869 private boolean loadJLine(Charset cs) {
870 if (!attemptedJLineLoad) {
871 // Check if we can use JLine for better command line handling
872 attemptedJLineLoad = true;
873 console = ShellConsole.getConsole(this, cs);
874 }
875 return console != null;
876 }
877
878 public ShellConsole getConsole(Charset cs) {
879 if (!loadJLine(cs)) {
880 console = ShellConsole.getConsole(getIn(), getErr(), cs);
881 }
882 return console;
883 }
884
885 public InputStream getIn() {
886 if (inStream == null && !attemptedJLineLoad) {
887 if (loadJLine(Charset.defaultCharset())) {
888 inStream = console.getIn();
889 }
890 }
891 return inStream == null ? System.in : inStream;
892 }
893
894 public void setIn(InputStream in) {
895 inStream = in;
896 }
897
898 public PrintStream getOut() {
899 return outStream == null ? System.out : outStream;
900 }
901
902 public void setOut(PrintStream out) {
903 outStream = out;
904 }
905
906 public PrintStream getErr() {
907 return errStream == null ? System.err : errStream;
908 }
909
910 public void setErr(PrintStream err) {
911 errStream = err;
912 }
913
914 public void setSealedStdLib(boolean value)
915 {
916 sealedStdLib = value;
917 }
918
919 private static Global getInstance(Function function)
920 {
921 Scriptable scope = function.getParentScope();
922 if (!(scope instanceof Global))
923 throw reportRuntimeError("msg.bad.shell.function.scope",
924 String.valueOf(scope));
925 return (Global)scope;
926 }
927
928 /**
929 * Runs the given process using Runtime.exec().
930 * If any of in, out, err is null, the corresponding process stream will
931 * be closed immediately, otherwise it will be closed as soon as
932 * all data will be read from/written to process
933 *
934 * @return Exit value of process.
935 * @throws IOException If there was an error executing the process.
936 */
937 private static int runProcess(String[] cmd, String[] environment,
938 File wd, InputStream in, OutputStream out,
939 OutputStream err)
940 throws IOException
941 {
942 Process p;
943 if (environment == null) {
944 p = Runtime.getRuntime().exec(cmd,null,wd);
945 } else {
946 p = Runtime.getRuntime().exec(cmd, environment,wd);
947 }
948
949 try {
950 PipeThread inThread = null;
951 if (in != null) {
952 inThread = new PipeThread(false, in, p.getOutputStream());
953 inThread.start();
954 } else {
955 p.getOutputStream().close();
956 }
957
958 PipeThread outThread = null;
959 if (out != null) {
960 outThread = new PipeThread(true, p.getInputStream(), out);
961 outThread.start();
962 } else {
963 p.getInputStream().close();
964 }
965
966 PipeThread errThread = null;
967 if (err != null) {
968 errThread = new PipeThread(true, p.getErrorStream(), err);
969 errThread.start();
970 } else {
971 p.getErrorStream().close();
972 }
973
974 // wait for process completion
975 for (;;) {
976 try {
977 p.waitFor();
978 if (outThread != null) {
979 outThread.join();
980 }
981 if (inThread != null) {
982 inThread.join();
983 }
984 if (errThread != null) {
985 errThread.join();
986 }
987 break;
988 } catch (InterruptedException ignore) {
989 }
990 }
991
992 return p.exitValue();
993 } finally {
994 p.destroy();
995 }
996 }
997
998 static void pipe(boolean fromProcess, InputStream from, OutputStream to)
999 throws IOException
1000 {
1001 try {
1002 final int SIZE = 4096;
1003 byte[] buffer = new byte[SIZE];
1004 for (;;) {
1005 int n;
1006 if (!fromProcess) {
1007 n = from.read(buffer, 0, SIZE);
1008 } else {
1009 try {
1010 n = from.read(buffer, 0, SIZE);
1011 } catch (IOException ex) {
1012 // Ignore exception as it can be cause by closed pipe
1013 break;
1014 }
1015 }
1016 if (n < 0) { break; }
1017 if (fromProcess) {
1018 to.write(buffer, 0, n);
1019 to.flush();
1020 } else {
1021 try {
1022 to.write(buffer, 0, n);
1023 to.flush();
1024 } catch (IOException ex) {
1025 // Ignore exception as it can be cause by closed pipe
1026 break;
1027 }
1028 }
1029 }
1030 } finally {
1031 try {
1032 if (fromProcess) {
1033 from.close();
1034 } else {
1035 to.close();
1036 }
1037 } catch (IOException ex) {
1038 // Ignore errors on close. On Windows JVM may throw invalid
1039 // refrence exception if process terminates too fast.
1040 }
1041 }
1042 }
1043
1044 private static InputStream toInputStream(Object value)
1045 throws IOException
1046 {
1047 InputStream is = null;
1048 String s = null;
1049 if (value instanceof Wrapper) {
1050 Object unwrapped = ((Wrapper)value).unwrap();
1051 if (unwrapped instanceof InputStream) {
1052 is = (InputStream)unwrapped;
1053 } else if (unwrapped instanceof byte[]) {
1054 is = new ByteArrayInputStream((byte[])unwrapped);
1055 } else if (unwrapped instanceof Reader) {
1056 s = readReader((Reader)unwrapped);
1057 } else if (unwrapped instanceof char[]) {
1058 s = new String((char[])unwrapped);
1059 }
1060 }
1061 if (is == null) {
1062 if (s == null) { s = ScriptRuntime.toString(value); }
1063 is = new ByteArrayInputStream(s.getBytes());
1064 }
1065 return is;
1066 }
1067
1068 private static OutputStream toOutputStream(Object value) {
1069 OutputStream os = null;
1070 if (value instanceof Wrapper) {
1071 Object unwrapped = ((Wrapper)value).unwrap();
1072 if (unwrapped instanceof OutputStream) {
1073 os = (OutputStream)unwrapped;
1074 }
1075 }
1076 return os;
1077 }
1078
1079 private static String readUrl(String filePath, String charCoding,
1080 boolean urlIsFile)
1081 throws IOException
1082 {
1083 int chunkLength;
1084 InputStream is = null;
1085 try {
1086 if (!urlIsFile) {
1087 URL urlObj = new URL(filePath);
1088 URLConnection uc = urlObj.openConnection();
1089 is = uc.getInputStream();
1090 chunkLength = uc.getContentLength();
1091 if (chunkLength <= 0)
1092 chunkLength = 1024;
1093 if (charCoding == null) {
1094 String type = uc.getContentType();
1095 if (type != null) {
1096 charCoding = getCharCodingFromType(type);
1097 }
1098 }
1099 } else {
1100 File f = new File(filePath);
1101 if (!f.exists()) {
1102 throw new FileNotFoundException("File not found: " + filePath);
1103 } else if (!f.canRead()) {
1104 throw new IOException("Cannot read file: " + filePath);
1105 }
1106 long length = f.length();
1107 chunkLength = (int)length;
1108 if (chunkLength != length)
1109 throw new IOException("Too big file size: "+length);
1110
1111 if (chunkLength == 0) { return ""; }
1112
1113 is = new FileInputStream(f);
1114 }
1115
1116 Reader r;
1117 if (charCoding == null) {
1118 r = new InputStreamReader(is);
1119 } else {
1120 r = new InputStreamReader(is, charCoding);
1121 }
1122 return readReader(r, chunkLength);
1123
1124 } finally {
1125 if (is != null)
1126 is.close();
1127 }
1128 }
1129
1130 /**
1131 * The readline reads one line from the standard input. "Prompt" is optional.
1132 * <p>
1133 * Usage:
1134 * <pre>
1135 * readline(prompt)
1136 * </pre>
1137 */
1138 public static Object readline(Context cx, Scriptable thisObj, Object[] args, Function funObj)
1139 throws IOException
1140 {
1141 Global self = getInstance(funObj);
1142
1143 if (args.length > 0) {
1144 return self.console.readLine(Context.toString(args[0]));
1145 }
1146 return self.console.readLine();
1147 }
1148
1149 private static String getCharCodingFromType(String type)
1150 {
1151 int i = type.indexOf(';');
1152 if (i >= 0) {
1153 int end = type.length();
1154 ++i;
1155 while (i != end && type.charAt(i) <= ' ') {
1156 ++i;
1157 }
1158 String charset = "charset";
1159 if (charset.regionMatches(true, 0, type, i, charset.length()))
1160 {
1161 i += charset.length();
1162 while (i != end && type.charAt(i) <= ' ') {
1163 ++i;
1164 }
1165 if (i != end && type.charAt(i) == '=') {
1166 ++i;
1167 while (i != end && type.charAt(i) <= ' ') {
1168 ++i;
1169 }
1170 if (i != end) {
1171 // i is at the start of non-empty
1172 // charCoding spec
1173 while (type.charAt(end -1) <= ' ') {
1174 --end;
1175 }
1176 return type.substring(i, end);
1177 }
1178 }
1179 }
1180 }
1181 return null;
1182 }
1183
1184 private static String readReader(Reader reader)
1185 throws IOException
1186 {
1187 return readReader(reader, 4096);
1188 }
1189
1190 private static String readReader(Reader reader, int initialBufferSize)
1191 throws IOException
1192 {
1193 char[] buffer = new char[initialBufferSize];
1194 int offset = 0;
1195 for (;;) {
1196 int n = reader.read(buffer, offset, buffer.length - offset);
1197 if (n < 0) { break; }
1198 offset += n;
1199 if (offset == buffer.length) {
1200 char[] tmp = new char[buffer.length * 2];
1201 System.arraycopy(buffer, 0, tmp, 0, offset);
1202 buffer = tmp;
1203 }
1204 }
1205 return new String(buffer, 0, offset);
1206 }
1207
1208 static RuntimeException reportRuntimeError(String msgId) {
1209 String message = ToolErrorReporter.getMessage(msgId);
1210 return Context.reportRuntimeError(message);
1211 }
1212
1213 static RuntimeException reportRuntimeError(String msgId, String msgArg)
1214 {
1215 String message = ToolErrorReporter.getMessage(msgId, msgArg);
1216 return Context.reportRuntimeError(message);
1217 }
1218 }
1219
1220
1221 class Runner implements Runnable, ContextAction {
1222
1223 Runner(Scriptable scope, Function func, Object[] args) {
1224 this.scope = scope;
1225 f = func;
1226 this.args = args;
1227 }
1228
1229 Runner(Scriptable scope, Script script) {
1230 this.scope = scope;
1231 s = script;
1232 }
1233
1234 public void run()
1235 {
1236 factory.call(this);
1237 }
1238
1239 public Object run(Context cx)
1240 {
1241 if (f != null)
1242 return f.call(cx, scope, scope, args);
1243 else
1244 return s.exec(cx, scope);
1245 }
1246
1247 ContextFactory factory;
1248 private Scriptable scope;
1249 private Function f;
1250 private Script s;
1251 private Object[] args;
1252 }
1253
1254 class PipeThread extends Thread {
1255
1256 PipeThread(boolean fromProcess, InputStream from, OutputStream to) {
1257 setDaemon(true);
1258 this.fromProcess = fromProcess;
1259 this.from = from;
1260 this.to = to;
1261 }
1262
1263 @Override
1264 public void run() {
1265 try {
1266 Global.pipe(fromProcess, from, to);
1267 } catch (IOException ex) {
1268 throw Context.throwAsScriptRuntimeEx(ex);
1269 }
1270 }
1271
1272 private boolean fromProcess;
1273 private InputStream from;
1274 private OutputStream to;
1275 }
1276