ScriptingFunctions.java revision 1340:d95394322204
1/*
2 * Copyright (c) 2010, 2015, Oracle and/or its affiliates. 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.  Oracle designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Oracle in the LICENSE file that accompanied this code.
10 *
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
23 * questions.
24 */
25
26package jdk.nashorn.internal.runtime;
27
28import static jdk.nashorn.internal.lookup.Lookup.MH;
29import static jdk.nashorn.internal.runtime.ECMAErrors.typeError;
30import static jdk.nashorn.internal.runtime.ScriptRuntime.UNDEFINED;
31
32import java.io.BufferedReader;
33import java.io.File;
34import java.io.IOException;
35import java.io.InputStreamReader;
36import java.io.OutputStreamWriter;
37import java.io.StreamTokenizer;
38import java.io.StringReader;
39import java.lang.invoke.MethodHandle;
40import java.lang.invoke.MethodHandles;
41import java.util.ArrayList;
42import java.util.Arrays;
43import java.util.List;
44import java.util.Map;
45import jdk.nashorn.internal.objects.NativeArray;
46
47/**
48 * Global functions supported only in scripting mode.
49 */
50public final class ScriptingFunctions {
51
52    /** Handle to implementation of {@link ScriptingFunctions#readLine} - Nashorn extension */
53    public static final MethodHandle READLINE = findOwnMH("readLine", Object.class, Object.class, Object.class);
54
55    /** Handle to implementation of {@link ScriptingFunctions#readFully} - Nashorn extension */
56    public static final MethodHandle READFULLY = findOwnMH("readFully",     Object.class, Object.class, Object.class);
57
58    /** Handle to implementation of {@link ScriptingFunctions#exec} - Nashorn extension */
59    public static final MethodHandle EXEC = findOwnMH("exec",     Object.class, Object.class, Object[].class);
60
61    /** EXEC name - special property used by $EXEC API. */
62    public static final String EXEC_NAME = "$EXEC";
63
64    /** OUT name - special property used by $EXEC API. */
65    public static final String OUT_NAME  = "$OUT";
66
67    /** ERR name - special property used by $EXEC API. */
68    public static final String ERR_NAME  = "$ERR";
69
70    /** EXIT name - special property used by $EXEC API. */
71    public static final String EXIT_NAME = "$EXIT";
72
73    /** Names of special properties used by $ENV API. */
74    public  static final String ENV_NAME  = "$ENV";
75
76    /** Name of the environment variable for the current working directory. */
77    public static final String PWD_NAME  = "PWD";
78
79    private ScriptingFunctions() {
80    }
81
82    /**
83     * Nashorn extension: global.readLine (scripting-mode-only)
84     * Read one line of input from the standard input.
85     *
86     * @param self   self reference
87     * @param prompt String used as input prompt
88     *
89     * @return line that was read
90     *
91     * @throws IOException if an exception occurs
92     */
93    public static Object readLine(final Object self, final Object prompt) throws IOException {
94        if (prompt != UNDEFINED) {
95            System.out.print(JSType.toString(prompt));
96        }
97        final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
98        return reader.readLine();
99    }
100
101    /**
102     * Nashorn extension: Read the entire contents of a text file and return as String.
103     *
104     * @param self self reference
105     * @param file The input file whose content is read.
106     *
107     * @return String content of the input file.
108     *
109     * @throws IOException if an exception occurs
110     */
111    public static Object readFully(final Object self, final Object file) throws IOException {
112        File f = null;
113
114        if (file instanceof File) {
115            f = (File)file;
116        } else if (JSType.isString(file)) {
117            f = new java.io.File(((CharSequence)file).toString());
118        }
119
120        if (f == null || !f.isFile()) {
121            throw typeError("not.a.file", ScriptRuntime.safeToString(file));
122        }
123
124        return new String(Source.readFully(f));
125    }
126
127    /**
128     * Nashorn extension: exec a string in a separate process.
129     *
130     * @param self   self reference
131     * @param args   string to execute, input and additional arguments, to be appended to {@code string}. Additional
132     *               arguments can be passed as either one JavaScript array, whose elements will be converted to
133     *               strings; or as a sequence of varargs, each of which will be converted to a string.
134     *
135     * @return output string from the request
136     *
137     * @throws IOException           if any stream access fails
138     * @throws InterruptedException  if execution is interrupted
139     */
140    public static Object exec(final Object self, final Object... args) throws IOException, InterruptedException {
141        // Current global is need to fetch additional inputs and for additional results.
142        final ScriptObject global = Context.getGlobal();
143        final Object string = args.length > 0? args[0] : UNDEFINED;
144        final Object input = args.length > 1? args[1] : UNDEFINED;
145        final Object[] argv = (args.length > 2)? Arrays.copyOfRange(args, 2, args.length) : ScriptRuntime.EMPTY_ARRAY;
146        // Assemble command line, process additional arguments.
147        final List<String> cmdLine = tokenizeString(JSType.toString(string));
148        final Object[] additionalArgs = argv.length == 1 && argv[0] instanceof NativeArray ?
149                ((NativeArray) argv[0]).asObjectArray() :
150                argv;
151        for (Object arg : additionalArgs) {
152            cmdLine.add(JSType.toString(arg));
153        }
154
155        // Set up initial process.
156        final ProcessBuilder processBuilder = new ProcessBuilder(cmdLine);
157
158        // Current ENV property state.
159        final Object env = global.get(ENV_NAME);
160        if (env instanceof ScriptObject) {
161            final ScriptObject envProperties = (ScriptObject)env;
162
163            // If a working directory is present, use it.
164            final Object pwd = envProperties.get(PWD_NAME);
165            if (pwd != UNDEFINED) {
166                processBuilder.directory(new File(JSType.toString(pwd)));
167            }
168
169            // Set up ENV variables.
170            final Map<String, String> environment = processBuilder.environment();
171            environment.clear();
172            for (final Map.Entry<Object, Object> entry : envProperties.entrySet()) {
173                environment.put(JSType.toString(entry.getKey()), JSType.toString(entry.getValue()));
174            }
175        }
176
177        // Start the process.
178        final Process process = processBuilder.start();
179        final IOException exception[] = new IOException[2];
180
181        // Collect output.
182        final StringBuilder outBuffer = new StringBuilder();
183        final Thread outThread = new Thread(new Runnable() {
184            @Override
185            public void run() {
186                final char buffer[] = new char[1024];
187                try (final InputStreamReader inputStream = new InputStreamReader(process.getInputStream())) {
188                    for (int length; (length = inputStream.read(buffer, 0, buffer.length)) != -1; ) {
189                        outBuffer.append(buffer, 0, length);
190                    }
191                } catch (final IOException ex) {
192                    exception[0] = ex;
193                }
194            }
195        }, "$EXEC output");
196
197        // Collect errors.
198        final StringBuilder errBuffer = new StringBuilder();
199        final Thread errThread = new Thread(new Runnable() {
200            @Override
201            public void run() {
202                final char buffer[] = new char[1024];
203                try (final InputStreamReader inputStream = new InputStreamReader(process.getErrorStream())) {
204                    for (int length; (length = inputStream.read(buffer, 0, buffer.length)) != -1; ) {
205                        errBuffer.append(buffer, 0, length);
206                    }
207                } catch (final IOException ex) {
208                    exception[1] = ex;
209                }
210            }
211        }, "$EXEC error");
212
213        // Start gathering output.
214        outThread.start();
215        errThread.start();
216
217        // If input is present, pass on to process.
218        if (!JSType.nullOrUndefined(input)) {
219            try (OutputStreamWriter outputStream = new OutputStreamWriter(process.getOutputStream())) {
220                final String in = JSType.toString(input);
221                outputStream.write(in, 0, in.length());
222            } catch (final IOException ex) {
223                // Process was not expecting input.  May be normal state of affairs.
224            }
225        }
226
227        // Wait for the process to complete.
228        final int exit = process.waitFor();
229        outThread.join();
230        errThread.join();
231
232        final String out = outBuffer.toString();
233        final String err = errBuffer.toString();
234
235        // Set globals for secondary results.
236        global.set(OUT_NAME, out, 0);
237        global.set(ERR_NAME, err, 0);
238        global.set(EXIT_NAME, exit, 0);
239
240        // Propagate exception if present.
241        for (final IOException element : exception) {
242            if (element != null) {
243                throw element;
244            }
245        }
246
247        // Return the result from stdout.
248        return out;
249    }
250
251    private static MethodHandle findOwnMH(final String name, final Class<?> rtype, final Class<?>... types) {
252        return MH.findStatic(MethodHandles.lookup(), ScriptingFunctions.class, name, MH.type(rtype, types));
253    }
254
255    /**
256     * Break a string into tokens, honoring quoted arguments and escaped spaces.
257     *
258     * @param str a {@link String} to tokenize.
259     * @return a {@link List} of {@link String}s representing the tokens that
260     * constitute the string.
261     * @throws IOException in case {@link StreamTokenizer#nextToken()} raises it.
262     */
263    public static List<String> tokenizeString(final String str) throws IOException {
264        final StreamTokenizer tokenizer = new StreamTokenizer(new StringReader(str));
265        tokenizer.resetSyntax();
266        tokenizer.wordChars(0, 255);
267        tokenizer.whitespaceChars(0, ' ');
268        tokenizer.commentChar('#');
269        tokenizer.quoteChar('"');
270        tokenizer.quoteChar('\'');
271        final List<String> tokenList = new ArrayList<>();
272        final StringBuilder toAppend = new StringBuilder();
273        while (tokenizer.nextToken() != StreamTokenizer.TT_EOF) {
274            final String s = tokenizer.sval;
275            // The tokenizer understands about honoring quoted strings and recognizes
276            // them as one token that possibly contains multiple space-separated words.
277            // It does not recognize quoted spaces, though, and will split after the
278            // escaping \ character. This is handled here.
279            if (s.endsWith("\\")) {
280                // omit trailing \, append space instead
281                toAppend.append(s.substring(0, s.length() - 1)).append(' ');
282            } else {
283                tokenList.add(toAppend.append(s).toString());
284                toAppend.setLength(0);
285            }
286        }
287        if (toAppend.length() != 0) {
288            tokenList.add(toAppend.toString());
289        }
290        return tokenList;
291    }
292}
293