src/jdk/nashorn/internal/runtime/ScriptingFunctions.java

Fri, 05 Jun 2015 12:38:53 +0200

author
mhaupt
date
Fri, 05 Jun 2015 12:38:53 +0200
changeset 1398
2f1b9f4daec1
parent 1388
d03088193a17
child 1403
b39a918a34a4
permissions
-rw-r--r--

8080087: Nashorn $ENV.PWD is originally undefined
Summary: On Windows, the PWD environment variable does not exist and cannot be imported in scripting mode, so it is set explicitly.
Reviewed-by: lagergren, sundar

     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  */
    26 package jdk.nashorn.internal.runtime;
    28 import static jdk.nashorn.internal.lookup.Lookup.MH;
    29 import static jdk.nashorn.internal.runtime.ECMAErrors.typeError;
    30 import static jdk.nashorn.internal.runtime.ScriptRuntime.UNDEFINED;
    32 import java.io.BufferedReader;
    33 import java.io.File;
    34 import java.io.IOException;
    35 import java.io.InputStreamReader;
    36 import java.io.OutputStreamWriter;
    37 import java.io.StreamTokenizer;
    38 import java.io.StringReader;
    39 import java.lang.invoke.MethodHandle;
    40 import java.lang.invoke.MethodHandles;
    41 import java.util.ArrayList;
    42 import java.util.List;
    43 import java.util.Map;
    45 /**
    46  * Global functions supported only in scripting mode.
    47  */
    48 public final class ScriptingFunctions {
    50     /** Handle to implementation of {@link ScriptingFunctions#readLine} - Nashorn extension */
    51     public static final MethodHandle READLINE = findOwnMH("readLine", Object.class, Object.class, Object.class);
    53     /** Handle to implementation of {@link ScriptingFunctions#readFully} - Nashorn extension */
    54     public static final MethodHandle READFULLY = findOwnMH("readFully",     Object.class, Object.class, Object.class);
    56     /** Handle to implementation of {@link ScriptingFunctions#exec} - Nashorn extension */
    57     public static final MethodHandle EXEC = findOwnMH("exec",     Object.class, Object.class, Object.class, Object.class);
    59     /** EXEC name - special property used by $EXEC API. */
    60     public static final String EXEC_NAME = "$EXEC";
    62     /** OUT name - special property used by $EXEC API. */
    63     public static final String OUT_NAME  = "$OUT";
    65     /** ERR name - special property used by $EXEC API. */
    66     public static final String ERR_NAME  = "$ERR";
    68     /** EXIT name - special property used by $EXEC API. */
    69     public static final String EXIT_NAME = "$EXIT";
    71     /** Names of special properties used by $ENV API. */
    72     public  static final String ENV_NAME  = "$ENV";
    74     /** Name of the environment variable for the current working directory. */
    75     public static final String PWD_NAME  = "PWD";
    77     private ScriptingFunctions() {
    78     }
    80     /**
    81      * Nashorn extension: global.readLine (scripting-mode-only)
    82      * Read one line of input from the standard input.
    83      *
    84      * @param self   self reference
    85      * @param prompt String used as input prompt
    86      *
    87      * @return line that was read
    88      *
    89      * @throws IOException if an exception occurs
    90      */
    91     public static Object readLine(final Object self, final Object prompt) throws IOException {
    92         if (prompt != UNDEFINED) {
    93             System.out.print(JSType.toString(prompt));
    94         }
    95         final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    96         return reader.readLine();
    97     }
    99     /**
   100      * Nashorn extension: Read the entire contents of a text file and return as String.
   101      *
   102      * @param self self reference
   103      * @param file The input file whose content is read.
   104      *
   105      * @return String content of the input file.
   106      *
   107      * @throws IOException if an exception occurs
   108      */
   109     public static Object readFully(final Object self, final Object file) throws IOException {
   110         File f = null;
   112         if (file instanceof File) {
   113             f = (File)file;
   114         } else if (JSType.isString(file)) {
   115             f = new java.io.File(((CharSequence)file).toString());
   116         }
   118         if (f == null || !f.isFile()) {
   119             throw typeError("not.a.file", ScriptRuntime.safeToString(file));
   120         }
   122         return new String(Source.readFully(f));
   123     }
   125     /**
   126      * Nashorn extension: exec a string in a separate process.
   127      *
   128      * @param self   self reference
   129      * @param string string to execute
   130      * @param input  input
   131      *
   132      * @return output string from the request
   133      * @throws IOException           if any stream access fails
   134      * @throws InterruptedException  if execution is interrupted
   135      */
   136     public static Object exec(final Object self, final Object string, final Object input) throws IOException, InterruptedException {
   137         // Current global is need to fetch additional inputs and for additional results.
   138         final ScriptObject global = Context.getGlobal();
   140         // Set up initial process.
   141         final ProcessBuilder processBuilder = new ProcessBuilder(tokenizeString(JSType.toString(string)));
   143         // Current ENV property state.
   144         final Object env = global.get(ENV_NAME);
   145         if (env instanceof ScriptObject) {
   146             final ScriptObject envProperties = (ScriptObject)env;
   148             // If a working directory is present, use it.
   149             final Object pwd = envProperties.get(PWD_NAME);
   150             if (pwd != UNDEFINED) {
   151                 processBuilder.directory(new File(JSType.toString(pwd)));
   152             }
   154             // Set up ENV variables.
   155             final Map<String, String> environment = processBuilder.environment();
   156             environment.clear();
   157             for (final Map.Entry<Object, Object> entry : envProperties.entrySet()) {
   158                 environment.put(JSType.toString(entry.getKey()), JSType.toString(entry.getValue()));
   159             }
   160         }
   162         // Start the process.
   163         final Process process = processBuilder.start();
   164         final IOException exception[] = new IOException[2];
   166         // Collect output.
   167         final StringBuilder outBuffer = new StringBuilder();
   168         final Thread outThread = new Thread(new Runnable() {
   169             @Override
   170             public void run() {
   171                 final char buffer[] = new char[1024];
   172                 try (final InputStreamReader inputStream = new InputStreamReader(process.getInputStream())) {
   173                     for (int length; (length = inputStream.read(buffer, 0, buffer.length)) != -1; ) {
   174                         outBuffer.append(buffer, 0, length);
   175                     }
   176                 } catch (final IOException ex) {
   177                     exception[0] = ex;
   178                 }
   179             }
   180         }, "$EXEC output");
   182         // Collect errors.
   183         final StringBuilder errBuffer = new StringBuilder();
   184         final Thread errThread = new Thread(new Runnable() {
   185             @Override
   186             public void run() {
   187                 final char buffer[] = new char[1024];
   188                 try (final InputStreamReader inputStream = new InputStreamReader(process.getErrorStream())) {
   189                     for (int length; (length = inputStream.read(buffer, 0, buffer.length)) != -1; ) {
   190                         errBuffer.append(buffer, 0, length);
   191                     }
   192                 } catch (final IOException ex) {
   193                     exception[1] = ex;
   194                 }
   195             }
   196         }, "$EXEC error");
   198         // Start gathering output.
   199         outThread.start();
   200         errThread.start();
   202         // If input is present, pass on to process.
   203         try (OutputStreamWriter outputStream = new OutputStreamWriter(process.getOutputStream())) {
   204             if (input != UNDEFINED) {
   205                 final String in = JSType.toString(input);
   206                 outputStream.write(in, 0, in.length());
   207             }
   208         } catch (final IOException ex) {
   209             // Process was not expecting input.  May be normal state of affairs.
   210         }
   212         // Wait for the process to complete.
   213         final int exit = process.waitFor();
   214         outThread.join();
   215         errThread.join();
   217         final String out = outBuffer.toString();
   218         final String err = errBuffer.toString();
   220         // Set globals for secondary results.
   221         global.set(OUT_NAME, out, 0);
   222         global.set(ERR_NAME, err, 0);
   223         global.set(EXIT_NAME, exit, 0);
   225         // Propagate exception if present.
   226         for (final IOException element : exception) {
   227             if (element != null) {
   228                 throw element;
   229             }
   230         }
   232         // Return the result from stdout.
   233         return out;
   234     }
   236     private static MethodHandle findOwnMH(final String name, final Class<?> rtype, final Class<?>... types) {
   237         return MH.findStatic(MethodHandles.lookup(), ScriptingFunctions.class, name, MH.type(rtype, types));
   238     }
   240     /**
   241      * Break a string into tokens, honoring quoted arguments and escaped spaces.
   242      *
   243      * @param str a {@link String} to tokenize.
   244      * @return a {@link List} of {@link String}s representing the tokens that
   245      * constitute the string.
   246      * @throws IOException in case {@link StreamTokenizer#nextToken()} raises it.
   247      */
   248     public static List<String> tokenizeString(final String str) throws IOException {
   249         final StreamTokenizer tokenizer = new StreamTokenizer(new StringReader(str));
   250         tokenizer.resetSyntax();
   251         tokenizer.wordChars(0, 255);
   252         tokenizer.whitespaceChars(0, ' ');
   253         tokenizer.commentChar('#');
   254         tokenizer.quoteChar('"');
   255         tokenizer.quoteChar('\'');
   256         final List<String> tokenList = new ArrayList<>();
   257         final StringBuilder toAppend = new StringBuilder();
   258         while (tokenizer.nextToken() != StreamTokenizer.TT_EOF) {
   259             final String s = tokenizer.sval;
   260             // The tokenizer understands about honoring quoted strings and recognizes
   261             // them as one token that possibly contains multiple space-separated words.
   262             // It does not recognize quoted spaces, though, and will split after the
   263             // escaping \ character. This is handled here.
   264             if (s.endsWith("\\")) {
   265                 // omit trailing \, append space instead
   266                 toAppend.append(s.substring(0, s.length() - 1)).append(' ');
   267             } else {
   268                 tokenList.add(toAppend.append(s).toString());
   269                 toAppend.setLength(0);
   270             }
   271         }
   272         if (toAppend.length() != 0) {
   273             tokenList.add(toAppend.toString());
   274         }
   275         return tokenList;
   276     }
   277 }

mercurial