Debian Codegraph @

rhino/toolsrc/org/mozilla/javascript/tools/shell/Main.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.File;
10 import java.io.FileNotFoundException;
11 import java.io.IOException;
12 import java.io.InputStream;
13 import java.io.PrintStream;
14 import java.io.UnsupportedEncodingException;
15 import java.lang.ref.ReferenceQueue;
16 import java.lang.ref.SoftReference;
17 import java.net.URI;
18 import java.net.URISyntaxException;
19 import java.nio.charset.Charset;
20 import java.security.MessageDigest;
21 import java.security.NoSuchAlgorithmException;
22 import java.util.ArrayList;
23 import java.util.Arrays;
24 import java.util.LinkedHashMap;
25 import java.util.List;
26 import java.util.Map;
27
28 import org.mozilla.javascript.Context;
29 import org.mozilla.javascript.ContextAction;
30 import org.mozilla.javascript.Function;
31 import org.mozilla.javascript.GeneratedClassLoader;
32 import org.mozilla.javascript.Kit;
33 import org.mozilla.javascript.NativeArray;
34 import org.mozilla.javascript.RhinoException;
35 import org.mozilla.javascript.Script;
36 import org.mozilla.javascript.Scriptable;
37 import org.mozilla.javascript.ScriptableObject;
38 import org.mozilla.javascript.SecurityController;
39 import org.mozilla.javascript.commonjs.module.ModuleScope;
40 import org.mozilla.javascript.commonjs.module.Require;
41 import org.mozilla.javascript.tools.SourceReader;
42 import org.mozilla.javascript.tools.ToolErrorReporter;
43
44 /**
45 * The shell program.
46 *
47 * Can execute scripts interactively or in batch mode at the command line.
48 * An example of controlling the JavaScript engine.
49 *
50 * @author Norris Boyd
51 */
52 public class Main
53 {
54 public static ShellContextFactory
55 shellContextFactory = new ShellContextFactory();
56
57 public static Global global = new Global();
58 static protected ToolErrorReporter errorReporter;
59 static protected int exitCode = 0;
60 static private final int EXITCODE_RUNTIME_ERROR = 3;
61 static private final int EXITCODE_FILE_NOT_FOUND = 4;
62 static boolean processStdin = true;
63 static List<String> fileList = new ArrayList<String>();
64 static List<String> modulePath;
65 static String mainModule;
66 static boolean sandboxed = false;
67 static boolean useRequire = false;
68 static Require require;
69 private static SecurityProxy securityImpl;
70 private final static ScriptCache scriptCache = new ScriptCache(32);
71
72 static {
73 global.initQuitAction(new IProxy(IProxy.SYSTEM_EXIT));
74 }
75
76 /**
77 * Proxy class to avoid proliferation of anonymous classes.
78 */
79 private static class IProxy implements ContextAction, QuitAction
80 {
81 private static final int PROCESS_FILES = 1;
82 private static final int EVAL_INLINE_SCRIPT = 2;
83 private static final int SYSTEM_EXIT = 3;
84
85 private int type;
86 String[] args;
87 String scriptText;
88
89 IProxy(int type)
90 {
91 this.type = type;
92 }
93
94 public Object run(Context cx)
95 {
96 if (useRequire) {
97 require = global.installRequire(cx, modulePath, sandboxed);
98 }
99 if (type == PROCESS_FILES) {
100 processFiles(cx, args);
101 } else if (type == EVAL_INLINE_SCRIPT) {
102 evalInlineScript(cx, scriptText);
103 } else {
104 throw Kit.codeBug();
105 }
106 return null;
107 }
108
109 public void quit(Context cx, int exitCode)
110 {
111 if (type == SYSTEM_EXIT) {
112 System.exit(exitCode);
113 return;
114 }
115 throw Kit.codeBug();
116 }
117 }
118
119 /**
120 * Main entry point.
121 *
122 * Process arguments as would a normal Java program. Also
123 * create a new Context and associate it with the current thread.
124 * Then set up the execution environment and begin to
125 * execute scripts.
126 */
127 public static void main(String args[]) {
128 try {
129 if (Boolean.getBoolean("rhino.use_java_policy_security")) {
130 initJavaPolicySecuritySupport();
131 }
132 } catch (SecurityException ex) {
133 ex.printStackTrace(System.err);
134 }
135
136 int result = exec(args);
137 if (result != 0) {
138 System.exit(result);
139 }
140 }
141
142 /**
143 * Execute the given arguments, but don't System.exit at the end.
144 */
145 public static int exec(String origArgs[])
146 {
147 errorReporter = new ToolErrorReporter(false, global.getErr());
148 shellContextFactory.setErrorReporter(errorReporter);
149 String[] args = processOptions(origArgs);
150 if (exitCode > 0) {
151 return exitCode;
152 }
153 if (processStdin) {
154 fileList.add(null);
155 }
156 if (!global.initialized) {
157 global.init(shellContextFactory);
158 }
159 IProxy iproxy = new IProxy(IProxy.PROCESS_FILES);
160 iproxy.args = args;
161 shellContextFactory.call(iproxy);
162
163 return exitCode;
164 }
165
166 static void processFiles(Context cx, String[] args)
167 {
168 // define "arguments" array in the top-level object:
169 // need to allocate new array since newArray requires instances
170 // of exactly Object[], not ObjectSubclass[]
171 Object[] array = new Object[args.length];
172 System.arraycopy(args, 0, array, 0, args.length);
173 Scriptable argsObj = cx.newArray(global, array);
174 global.defineProperty("arguments", argsObj,
175 ScriptableObject.DONTENUM);
176
177 for (String file: fileList) {
178 try {
179 processSource(cx, file);
180 } catch (IOException ioex) {
181 Context.reportError(ToolErrorReporter.getMessage(
182 "msg.couldnt.read.source", file, ioex.getMessage()));
183 exitCode = EXITCODE_FILE_NOT_FOUND;
184 } catch (RhinoException rex) {
185 ToolErrorReporter.reportException(
186 cx.getErrorReporter(), rex);
187 exitCode = EXITCODE_RUNTIME_ERROR;
188 } catch (VirtualMachineError ex) {
189 // Treat StackOverflow and OutOfMemory as runtime errors
190 ex.printStackTrace();
191 String msg = ToolErrorReporter.getMessage(
192 "msg.uncaughtJSException", ex.toString());
193 Context.reportError(msg);
194 exitCode = EXITCODE_RUNTIME_ERROR;
195 }
196 }
197 }
198
199 static void evalInlineScript(Context cx, String scriptText) {
200 try {
201 Script script = cx.compileString(scriptText, "<command>", 1, null);
202 if (script != null) {
203 script.exec(cx, getShellScope());
204 }
205 } catch (RhinoException rex) {
206 ToolErrorReporter.reportException(
207 cx.getErrorReporter(), rex);
208 exitCode = EXITCODE_RUNTIME_ERROR;
209 } catch (VirtualMachineError ex) {
210 // Treat StackOverflow and OutOfMemory as runtime errors
211 ex.printStackTrace();
212 String msg = ToolErrorReporter.getMessage(
213 "msg.uncaughtJSException", ex.toString());
214 Context.reportError(msg);
215 exitCode = EXITCODE_RUNTIME_ERROR;
216 }
217 }
218
219 public static Global getGlobal()
220 {
221 return global;
222 }
223
224 static Scriptable getShellScope() {
225 return getScope(null);
226 }
227
228 static Scriptable getScope(String path) {
229 if (useRequire) {
230 // If CommonJS modules are enabled use a module scope that resolves
231 // relative ids relative to the current URL, file or working directory.
232 URI uri;
233 if (path == null) {
234 // use current directory for shell and -e switch
235 uri = new File(System.getProperty("user.dir")).toURI();
236 } else {
237 // find out whether this is a file path or a URL
238 if (SourceReader.toUrl(path) != null) {
239 try {
240 uri = new URI(path);
241 } catch (URISyntaxException x) {
242 // fall back to file uri
243 uri = new File(path).toURI();
244 }
245 } else {
246 uri = new File(path).toURI();
247 }
248 }
249 return new ModuleScope(global, uri, null);
250 } else {
251 return global;
252 }
253 }
254
255 /**
256 * Parse arguments.
257 */
258 public static String[] processOptions(String args[])
259 {
260 String usageError;
261 goodUsage: for (int i = 0; ; ++i) {
262 if (i == args.length) {
263 return new String[0];
264 }
265 String arg = args[i];
266 if (!arg.startsWith("-")) {
267 processStdin = false;
268 fileList.add(arg);
269 mainModule = arg;
270 String[] result = new String[args.length - i - 1];
271 System.arraycopy(args, i+1, result, 0, args.length - i - 1);
272 return result;
273 }
274 if (arg.equals("-version")) {
275 if (++i == args.length) {
276 usageError = arg;
277 break goodUsage;
278 }
279 int version;
280 try {
281 version = Integer.parseInt(args[i]);
282 } catch (NumberFormatException ex) {
283 usageError = args[i];
284 break goodUsage;
285 }
286 if (!Context.isValidLanguageVersion(version)) {
287 usageError = args[i];
288 break goodUsage;
289 }
290 shellContextFactory.setLanguageVersion(version);
291 continue;
292 }
293 if (arg.equals("-opt") || arg.equals("-O")) {
294 if (++i == args.length) {
295 usageError = arg;
296 break goodUsage;
297 }
298 int opt;
299 try {
300 opt = Integer.parseInt(args[i]);
301 } catch (NumberFormatException ex) {
302 usageError = args[i];
303 break goodUsage;
304 }
305 if (opt == -2) {
306 // Compatibility with Cocoon Rhino fork
307 opt = -1;
308 } else if (!Context.isValidOptimizationLevel(opt)) {
309 usageError = args[i];
310 break goodUsage;
311 }
312 shellContextFactory.setOptimizationLevel(opt);
313 continue;
314 }
315 if (arg.equals("-encoding")) {
316 if (++i == args.length) {
317 usageError = arg;
318 break goodUsage;
319 }
320 String enc = args[i];
321 shellContextFactory.setCharacterEncoding(enc);
322 continue;
323 }
324 if (arg.equals("-strict")) {
325 shellContextFactory.setStrictMode(true);
326 shellContextFactory.setAllowReservedKeywords(false);
327 errorReporter.setIsReportingWarnings(true);
328 continue;
329 }
330 if (arg.equals("-fatal-warnings")) {
331 shellContextFactory.setWarningAsError(true);
332 continue;
333 }
334 if (arg.equals("-e")) {
335 processStdin = false;
336 if (++i == args.length) {
337 usageError = arg;
338 break goodUsage;
339 }
340 if (!global.initialized) {
341 global.init(shellContextFactory);
342 }
343 IProxy iproxy = new IProxy(IProxy.EVAL_INLINE_SCRIPT);
344 iproxy.scriptText = args[i];
345 shellContextFactory.call(iproxy);
346 continue;
347 }
348 if (arg.equals("-require")) {
349 useRequire = true;
350 continue;
351 }
352 if (arg.equals("-sandbox")) {
353 sandboxed = true;
354 useRequire = true;
355 continue;
356 }
357 if (arg.equals("-modules")) {
358 if (++i == args.length) {
359 usageError = arg;
360 break goodUsage;
361 }
362 if (modulePath == null) {
363 modulePath = new ArrayList<String>();
364 }
365 modulePath.add(args[i]);
366 useRequire = true;
367 continue;
368 }
369 if (arg.equals("-w")) {
370 errorReporter.setIsReportingWarnings(true);
371 continue;
372 }
373 if (arg.equals("-f")) {
374 processStdin = false;
375 if (++i == args.length) {
376 usageError = arg;
377 break goodUsage;
378 }
379 if (args[i].equals("-")) {
380 fileList.add(null);
381 } else {
382 fileList.add(args[i]);
383 mainModule = args[i];
384 }
385 continue;
386 }
387 if (arg.equals("-sealedlib")) {
388 global.setSealedStdLib(true);
389 continue;
390 }
391 if (arg.equals("-debug")) {
392 shellContextFactory.setGeneratingDebug(true);
393 continue;
394 }
395 if (arg.equals("-?") ||
396 arg.equals("-help")) {
397 // print usage message
398 global.getOut().println(
399 ToolErrorReporter.getMessage("msg.shell.usage", Main.class.getName()));
400 exitCode = 1;
401 return null;
402 }
403 usageError = arg;
404 break goodUsage;
405 }
406 // print error and usage message
407 global.getOut().println(
408 ToolErrorReporter.getMessage("msg.shell.invalid", usageError));
409 global.getOut().println(
410 ToolErrorReporter.getMessage("msg.shell.usage", Main.class.getName()));
411 exitCode = 1;
412 return null;
413 }
414
415 private static void initJavaPolicySecuritySupport()
416 {
417 Throwable exObj;
418 try {
419 Class<?> cl = Class.forName
420 ("org.mozilla.javascript.tools.shell.JavaPolicySecurity");
421 securityImpl = (SecurityProxy)cl.newInstance();
422 SecurityController.initGlobal(securityImpl);
423 return;
424 } catch (ClassNotFoundException ex) {
425 exObj = ex;
426 } catch (IllegalAccessException ex) {
427 exObj = ex;
428 } catch (InstantiationException ex) {
429 exObj = ex;
430 } catch (LinkageError ex) {
431 exObj = ex;
432 }
433 throw Kit.initCause(new IllegalStateException(
434 "Can not load security support: "+exObj), exObj);
435 }
436
437 /**
438 * Evaluate JavaScript source.
439 *
440 * @param cx the current context
441 * @param filename the name of the file to compile, or null
442 * for interactive mode.
443 * @throws IOException if the source could not be read
444 * @throws RhinoException thrown during evaluation of source
445 */
446 public static void processSource(Context cx, String filename)
447 throws IOException
448 {
449 if (filename == null || filename.equals("-")) {
450 Scriptable scope = getShellScope();
451 Charset cs;
452 String charEnc = shellContextFactory.getCharacterEncoding();
453 if (charEnc != null) {
454 cs = Charset.forName(charEnc);
455 } else {
456 cs = Charset.defaultCharset();
457 }
458 ShellConsole console = global.getConsole(cs);
459 if (filename == null) {
460 // print implementation version
461 console.println(cx.getImplementationVersion());
462 }
463
464 int lineno = 1;
465 boolean hitEOF = false;
466 while (!hitEOF) {
467 String[] prompts = global.getPrompts(cx);
468 String prompt = null;
469 if (filename == null)
470 prompt = prompts[0];
471 console.flush();
472 String source = "";
473
474 // Collect lines of source to compile.
475 while (true) {
476 String newline;
477 try {
478 newline = console.readLine(prompt);
479 }
480 catch (IOException ioe) {
481 console.println(ioe.toString());
482 break;
483 }
484 if (newline == null) {
485 hitEOF = true;
486 break;
487 }
488 source = source + newline + "\n";
489 lineno++;
490 if (cx.stringIsCompilableUnit(source))
491 break;
492 prompt = prompts[1];
493 }
494 try {
495 Script script = cx.compileString(source, "<stdin>", lineno, null);
496 if (script != null) {
497 Object result = script.exec(cx, scope);
498 // Avoid printing out undefined or function definitions.
499 if (result != Context.getUndefinedValue() &&
500 !(result instanceof Function &&
501 source.trim().startsWith("function")))
502 {
503 try {
504 console.println(Context.toString(result));
505 } catch (RhinoException rex) {
506 ToolErrorReporter.reportException(
507 cx.getErrorReporter(), rex);
508 }
509 }
510 NativeArray h = global.history;
511 h.put((int)h.getLength(), h, source);
512 }
513 } catch (RhinoException rex) {
514 ToolErrorReporter.reportException(
515 cx.getErrorReporter(), rex);
516 exitCode = EXITCODE_RUNTIME_ERROR;
517 } catch (VirtualMachineError ex) {
518 // Treat StackOverflow and OutOfMemory as runtime errors
519 ex.printStackTrace();
520 String msg = ToolErrorReporter.getMessage(
521 "msg.uncaughtJSException", ex.toString());
522 Context.reportError(msg);
523 exitCode = EXITCODE_RUNTIME_ERROR;
524 }
525 }
526 console.println();
527 console.flush();
528 } else if (useRequire && filename.equals(mainModule)) {
529 require.requireMain(cx, filename);
530 } else {
531 processFile(cx, getScope(filename), filename);
532 }
533 }
534
535 public static void processFileNoThrow(Context cx, Scriptable scope, String filename) {
536 try {
537 processFile(cx, scope, filename);
538 } catch (IOException ioex) {
539 Context.reportError(ToolErrorReporter.getMessage(
540 "msg.couldnt.read.source", filename, ioex.getMessage()));
541 exitCode = EXITCODE_FILE_NOT_FOUND;
542 } catch (RhinoException rex) {
543 ToolErrorReporter.reportException(
544 cx.getErrorReporter(), rex);
545 exitCode = EXITCODE_RUNTIME_ERROR;
546 } catch (VirtualMachineError ex) {
547 // Treat StackOverflow and OutOfMemory as runtime errors
548 ex.printStackTrace();
549 String msg = ToolErrorReporter.getMessage(
550 "msg.uncaughtJSException", ex.toString());
551 Context.reportError(msg);
552 exitCode = EXITCODE_RUNTIME_ERROR;
553 }
554 }
555
556 public static void processFile(Context cx, Scriptable scope, String filename)
557 throws IOException
558 {
559 if (securityImpl == null) {
560 processFileSecure(cx, scope, filename, null);
561 } else {
562 securityImpl.callProcessFileSecure(cx, scope, filename);
563 }
564 }
565
566 static void processFileSecure(Context cx, Scriptable scope,
567 String path, Object securityDomain)
568 throws IOException {
569
570 boolean isClass = path.endsWith(".class");
571 Object source = readFileOrUrl(path, !isClass);
572
573 byte[] digest = getDigest(source);
574 String key = path + "_" + cx.getOptimizationLevel();
575 ScriptReference ref = scriptCache.get(key, digest);
576 Script script = ref != null ? ref.get() : null;
577
578 if (script == null) {
579 if (isClass) {
580 script = loadCompiledScript(cx, path, (byte[])source, securityDomain);
581 } else {
582 String strSrc = (String) source;
583 // Support the executable script #! syntax: If
584 // the first line begins with a '#', treat the whole
585 // line as a comment.
586 if (strSrc.length() > 0 && strSrc.charAt(0) == '#') {
587 for (int i = 1; i != strSrc.length(); ++i) {
588 int c = strSrc.charAt(i);
589 if (c == '\n' || c == '\r') {
590 strSrc = strSrc.substring(i);
591 break;
592 }
593 }
594 }
595 script = cx.compileString(strSrc, path, 1, securityDomain);
596 }
597 scriptCache.put(key, digest, script);
598 }
599
600 if (script != null) {
601 script.exec(cx, scope);
602 }
603 }
604
605 private static byte[] getDigest(Object source) {
606 byte[] bytes, digest = null;
607
608 if (source != null) {
609 if (source instanceof String) {
610 try {
611 bytes = ((String)source).getBytes("UTF-8");
612 } catch (UnsupportedEncodingException ue) {
613 bytes = ((String)source).getBytes();
614 }
615 } else {
616 bytes = (byte[])source;
617 }
618 try {
619 MessageDigest md = MessageDigest.getInstance("MD5");
620 digest = md.digest(bytes);
621 } catch (NoSuchAlgorithmException nsa) {
622 // Should not happen
623 throw new RuntimeException(nsa);
624 }
625 }
626
627 return digest;
628 }
629
630 private static Script loadCompiledScript(Context cx, String path,
631 byte[] data, Object securityDomain)
632 throws FileNotFoundException
633 {
634 if (data == null) {
635 throw new FileNotFoundException(path);
636 }
637 // XXX: For now extract class name of compiled Script from path
638 // instead of parsing class bytes
639 int nameStart = path.lastIndexOf('/');
640 if (nameStart < 0) {
641 nameStart = 0;
642 } else {
643 ++nameStart;
644 }
645 int nameEnd = path.lastIndexOf('.');
646 if (nameEnd < nameStart) {
647 // '.' does not exist in path (nameEnd < 0)
648 // or it comes before nameStart
649 nameEnd = path.length();
650 }
651 String name = path.substring(nameStart, nameEnd);
652 try {
653 GeneratedClassLoader loader = SecurityController.createLoader(cx.getApplicationClassLoader(), securityDomain);
654 Class<?> clazz = loader.defineClass(name, data);
655 loader.linkClass(clazz);
656 if (!Script.class.isAssignableFrom(clazz)) {
657 throw Context.reportRuntimeError("msg.must.implement.Script");
658 }
659 return (Script) clazz.newInstance();
660 } catch (IllegalAccessException iaex) {
661 Context.reportError(iaex.toString());
662 throw new RuntimeException(iaex);
663 } catch (InstantiationException inex) {
664 Context.reportError(inex.toString());
665 throw new RuntimeException(inex);
666 }
667 }
668
669 public static InputStream getIn() {
670 return getGlobal().getIn();
671 }
672
673 public static void setIn(InputStream in) {
674 getGlobal().setIn(in);
675 }
676
677 public static PrintStream getOut() {
678 return getGlobal().getOut();
679 }
680
681 public static void setOut(PrintStream out) {
682 getGlobal().setOut(out);
683 }
684
685 public static PrintStream getErr() {
686 return getGlobal().getErr();
687 }
688
689 public static void setErr(PrintStream err) {
690 getGlobal().setErr(err);
691 }
692
693 /**
694 * Read file or url specified by <tt>path</tt>.
695 * @return file or url content as <tt>byte[]</tt> or as <tt>String</tt> if
696 * <tt>convertToString</tt> is true.
697 */
698 private static Object readFileOrUrl(String path, boolean convertToString)
699 throws IOException
700 {
701 return SourceReader.readFileOrUrl(path, convertToString,
702 shellContextFactory.getCharacterEncoding());
703 }
704
705 static class ScriptReference extends SoftReference<Script> {
706 String path;
707 byte[] digest;
708
709 ScriptReference(String path, byte[] digest,
710 Script script, ReferenceQueue<Script> queue) {
711 super(script, queue);
712 this.path = path;
713 this.digest = digest;
714 }
715 }
716
717 static class ScriptCache extends LinkedHashMap<String, ScriptReference> {
718 ReferenceQueue<Script> queue;
719 int capacity;
720
721 ScriptCache(int capacity) {
722 super(capacity + 1, 2f, true);
723 this.capacity = capacity;
724 queue = new ReferenceQueue<Script>();
725 }
726
727 @Override
728 protected boolean removeEldestEntry(Map.Entry<String, ScriptReference> eldest) {
729 return size() > capacity;
730 }
731
732 ScriptReference get(String path, byte[] digest) {
733 ScriptReference ref;
734 while((ref = (ScriptReference) queue.poll()) != null) {
735 remove(ref.path);
736 }
737 ref = get(path);
738 if (ref != null && !Arrays.equals(digest, ref.digest)) {
739 remove(ref.path);
740 ref = null;
741 }
742 return ref;
743 }
744
745 void put(String path, byte[] digest, Script script) {
746 put(path, new ScriptReference(path, digest, script, queue));
747 }
748
749 }
750 }