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