Debian Codegraph @

src/main/org/h2/util/SourceCompiler.java

raw
1 /*
2 * Copyright 2004-2023 H2 Group. Multiple-Licensed under the MPL 2.0,
3 * and the EPL 1.0 (https://h2database.com/html/license.html).
4 * Initial Developer: H2 Group
5 */
6 package org.h2.util;
7
8 import java.io.BufferedReader;
9 import java.io.ByteArrayOutputStream;
10 import java.io.IOException;
11 import java.io.InputStream;
12 import java.io.OutputStream;
13 import java.io.PrintStream;
14 import java.io.StringReader;
15 import java.io.StringWriter;
16 import java.lang.reflect.Array;
17 import java.lang.reflect.Method;
18 import java.lang.reflect.Modifier;
19 import java.net.URI;
20 import java.nio.charset.StandardCharsets;
21 import java.nio.file.Files;
22 import java.nio.file.Path;
23 import java.nio.file.Paths;
24 import java.security.SecureClassLoader;
25 import java.util.ArrayList;
26 import java.util.HashMap;
27 import java.util.Map;
28
29 import javax.script.Compilable;
30 import javax.script.CompiledScript;
31 import javax.script.ScriptEngineManager;
32 import javax.script.ScriptException;
33 import javax.tools.FileObject;
34 import javax.tools.ForwardingJavaFileManager;
35 import javax.tools.JavaCompiler;
36 import javax.tools.JavaFileManager;
37 import javax.tools.JavaFileObject;
38 import javax.tools.JavaFileObject.Kind;
39 import javax.tools.SimpleJavaFileObject;
40 import javax.tools.StandardJavaFileManager;
41 import javax.tools.ToolProvider;
42
43 import org.h2.api.ErrorCode;
44 import org.h2.engine.SysProperties;
45 import org.h2.message.DbException;
46
47 /**
48 * This class allows to convert source code to a class. It uses one class loader
49 * per class.
50 */
51 public class SourceCompiler {
52
53 /**
54 * The "com.sun.tools.javac.Main" (if available).
55 */
56 static final JavaCompiler JAVA_COMPILER;
57
58 private static final Class<?> JAVAC_SUN;
59
60 private static final String COMPILE_DIR =
61 Utils.getProperty("java.io.tmpdir", ".");
62
63 /**
64 * The class name to source code map.
65 */
66 final HashMap<String, String> sources = new HashMap<>();
67
68 /**
69 * The class name to byte code map.
70 */
71 final HashMap<String, Class<?>> compiled = new HashMap<>();
72
73 /**
74 * The class name to compiled scripts map.
75 */
76 final Map<String, CompiledScript> compiledScripts = new HashMap<>();
77
78 /**
79 * Whether to use the ToolProvider.getSystemJavaCompiler().
80 */
81 boolean useJavaSystemCompiler = SysProperties.JAVA_SYSTEM_COMPILER;
82
83 static {
84 JavaCompiler c;
85 try {
86 c = ToolProvider.getSystemJavaCompiler();
87 } catch (Exception e) {
88 // ignore
89 c = null;
90 }
91 JAVA_COMPILER = c;
92 Class<?> clazz;
93 try {
94 clazz = Class.forName("com.sun.tools.javac.Main");
95 } catch (Exception e) {
96 clazz = null;
97 }
98 JAVAC_SUN = clazz;
99 }
100
101 /**
102 * Set the source code for the specified class.
103 * This will reset all compiled classes.
104 *
105 * @param className the class name
106 * @param source the source code
107 */
108 public void setSource(String className, String source) {
109 sources.put(className, source);
110 compiled.clear();
111 }
112
113 /**
114 * Enable or disable the usage of the Java system compiler.
115 *
116 * @param enabled true to enable
117 */
118 public void setJavaSystemCompiler(boolean enabled) {
119 this.useJavaSystemCompiler = enabled;
120 }
121
122 /**
123 * Get the class object for the given name.
124 *
125 * @param packageAndClassName the class name
126 * @return the class
127 * @throws ClassNotFoundException on failure
128 */
129 public Class<?> getClass(String packageAndClassName)
130 throws ClassNotFoundException {
131
132 Class<?> compiledClass = compiled.get(packageAndClassName);
133 if (compiledClass != null) {
134 return compiledClass;
135 }
136 String source = sources.get(packageAndClassName);
137 if (isGroovySource(source)) {
138 Class<?> clazz = GroovyCompiler.parseClass(source, packageAndClassName);
139 compiled.put(packageAndClassName, clazz);
140 return clazz;
141 }
142
143 ClassLoader classLoader = new ClassLoader(getClass().getClassLoader()) {
144
145 @Override
146 public Class<?> findClass(String name) throws ClassNotFoundException {
147 Class<?> classInstance = compiled.get(name);
148 if (classInstance == null) {
149 String source = sources.get(name);
150 String packageName = null;
151 int idx = name.lastIndexOf('.');
152 String className;
153 if (idx >= 0) {
154 packageName = name.substring(0, idx);
155 className = name.substring(idx + 1);
156 } else {
157 className = name;
158 }
159 String s = getCompleteSourceCode(packageName, className, source);
160 if (JAVA_COMPILER != null && useJavaSystemCompiler) {
161 classInstance = javaxToolsJavac(packageName, className, s);
162 } else {
163 byte[] data = javacCompile(packageName, className, s);
164 if (data == null) {
165 classInstance = findSystemClass(name);
166 } else {
167 classInstance = defineClass(name, data, 0, data.length);
168 }
169 }
170 compiled.put(name, classInstance);
171 }
172 return classInstance;
173 }
174 };
175 return classLoader.loadClass(packageAndClassName);
176 }
177
178 private static boolean isGroovySource(String source) {
179 return source.startsWith("//groovy") || source.startsWith("@groovy");
180 }
181
182 private static boolean isJavascriptSource(String source) {
183 return source.startsWith("//javascript");
184 }
185
186 private static boolean isRubySource(String source) {
187 return source.startsWith("#ruby");
188 }
189
190 /**
191 * Whether the passed source can be compiled using {@link javax.script.ScriptEngineManager}.
192 *
193 * @param source the source to test.
194 * @return <code>true</code> if {@link #getCompiledScript(String)} can be called.
195 */
196 public static boolean isJavaxScriptSource(String source) {
197 return isJavascriptSource(source) || isRubySource(source);
198 }
199
200 /**
201 * Get the compiled script.
202 *
203 * @param packageAndClassName the package and class name
204 * @return the compiled script
205 * @throws ScriptException on failure
206 */
207 public CompiledScript getCompiledScript(String packageAndClassName) throws ScriptException {
208 CompiledScript compiledScript = compiledScripts.get(packageAndClassName);
209 if (compiledScript == null) {
210 String source = sources.get(packageAndClassName);
211 final String lang;
212 if (isJavascriptSource(source)) {
213 lang = "javascript";
214 } else if (isRubySource(source)) {
215 lang = "ruby";
216 } else {
217 throw new IllegalStateException("Unknown language for " + source);
218 }
219
220 final Compilable jsEngine = (Compilable) new ScriptEngineManager().getEngineByName(lang);
221 compiledScript = jsEngine.compile(source);
222 compiledScripts.put(packageAndClassName, compiledScript);
223 }
224 return compiledScript;
225 }
226
227 /**
228 * Get the first public static method of the given class.
229 *
230 * @param className the class name
231 * @return the method name
232 * @throws ClassNotFoundException on failure
233 */
234 public Method getMethod(String className) throws ClassNotFoundException {
235 Class<?> clazz = getClass(className);
236 Method[] methods = clazz.getDeclaredMethods();
237 for (Method m : methods) {
238 int modifiers = m.getModifiers();
239 if (Modifier.isPublic(modifiers) && Modifier.isStatic(modifiers)) {
240 String name = m.getName();
241 if (!name.startsWith("_") && !m.getName().equals("main")) {
242 return m;
243 }
244 }
245 }
246 return null;
247 }
248
249 /**
250 * Compile the given class. This method tries to use the class
251 * "com.sun.tools.javac.Main" if available. If not, it tries to run "javac"
252 * in a separate process.
253 *
254 * @param packageName the package name
255 * @param className the class name
256 * @param source the source code
257 * @return the class file
258 */
259 byte[] javacCompile(String packageName, String className, String source) {
260 Path dir = Paths.get(COMPILE_DIR);
261 if (packageName != null) {
262 dir = dir.resolve(packageName.replace('.', '/'));
263 try {
264 Files.createDirectories(dir);
265 } catch (Exception e) {
266 throw DbException.convert(e);
267 }
268 }
269 Path javaFile = dir.resolve(className + ".java");
270 Path classFile = dir.resolve(className + ".class");
271 try {
272 Files.write(javaFile, source.getBytes(StandardCharsets.UTF_8));
273 Files.deleteIfExists(classFile);
274 if (JAVAC_SUN != null) {
275 javacSun(javaFile);
276 } else {
277 javacProcess(javaFile);
278 }
279 return Files.readAllBytes(classFile);
280 } catch (Exception e) {
281 throw DbException.convert(e);
282 } finally {
283 try {
284 Files.deleteIfExists(javaFile);
285 } catch (IOException e) {
286 }
287 try {
288 Files.deleteIfExists(classFile);
289 } catch (IOException e) {
290 }
291 }
292 }
293
294 /**
295 * Get the complete source code (including package name, imports, and so
296 * on).
297 *
298 * @param packageName the package name
299 * @param className the class name
300 * @param source the (possibly shortened) source code
301 * @return the full source code
302 */
303 static String getCompleteSourceCode(String packageName, String className,
304 String source) {
305 if (source.startsWith("package ")) {
306 return source;
307 }
308 StringBuilder buff = new StringBuilder();
309 if (packageName != null) {
310 buff.append("package ").append(packageName).append(";\n");
311 }
312 int endImport = source.indexOf("@CODE");
313 String importCode =
314 "import java.util.*;\n" +
315 "import java.math.*;\n" +
316 "import java.sql.*;\n";
317 if (endImport >= 0) {
318 importCode = source.substring(0, endImport);
319 source = source.substring("@CODE".length() + endImport);
320 }
321 buff.append(importCode);
322 buff.append("public class ").append(className).append(
323 " {\n" +
324 " public static ").append(source).append("\n" +
325 "}\n");
326 return buff.toString();
327 }
328
329 /**
330 * Compile using the standard java compiler.
331 *
332 * @param packageName the package name
333 * @param className the class name
334 * @param source the source code
335 * @return the class
336 */
337 Class<?> javaxToolsJavac(String packageName, String className, String source) {
338 String fullClassName = packageName + "." + className;
339 StringWriter writer = new StringWriter();
340 try (JavaFileManager fileManager = new
341 ClassFileManager(JAVA_COMPILER
342 .getStandardFileManager(null, null, null))) {
343 ArrayList<JavaFileObject> compilationUnits = new ArrayList<>();
344 compilationUnits.add(new StringJavaFileObject(fullClassName, source));
345 // cannot concurrently compile
346 final boolean ok;
347 synchronized (JAVA_COMPILER) {
348 ok = JAVA_COMPILER.getTask(writer, fileManager, null, null,
349 null, compilationUnits).call();
350 }
351 String output = writer.toString();
352 handleSyntaxError(output, (ok? 0: 1));
353 return fileManager.getClassLoader(null).loadClass(fullClassName);
354 } catch (ClassNotFoundException | IOException e) {
355 throw DbException.convert(e);
356 }
357 }
358
359 private static void javacProcess(Path javaFile) {
360 exec("javac",
361 "-sourcepath", COMPILE_DIR,
362 "-d", COMPILE_DIR,
363 "-encoding", "UTF-8",
364 javaFile.toAbsolutePath().toString());
365 }
366
367 private static int exec(String... args) {
368 ByteArrayOutputStream buff = new ByteArrayOutputStream();
369 try {
370 ProcessBuilder builder = new ProcessBuilder();
371 // The javac executable allows some of it's flags
372 // to be smuggled in via environment variables.
373 // But if it sees those flags, it will write out a message
374 // to stderr, which messes up our parsing of the output.
375 builder.environment().remove("JAVA_TOOL_OPTIONS");
376 builder.command(args);
377
378 Process p = builder.start();
379 copyInThread(p.getInputStream(), buff);
380 copyInThread(p.getErrorStream(), buff);
381 p.waitFor();
382 String output = Utils10.byteArrayOutputStreamToString(buff, StandardCharsets.UTF_8);
383 handleSyntaxError(output, p.exitValue());
384 return p.exitValue();
385 } catch (Exception e) {
386 throw DbException.convert(e);
387 }
388 }
389
390 private static void copyInThread(final InputStream in, final OutputStream out) {
391 new Task() {
392 @Override
393 public void call() throws IOException {
394 IOUtils.copy(in, out);
395 }
396 }.execute();
397 }
398
399 private static synchronized void javacSun(Path javaFile) {
400 PrintStream old = System.err;
401 ByteArrayOutputStream buff = new ByteArrayOutputStream();
402 try {
403 System.setErr(new PrintStream(buff, false, "UTF-8"));
404 Method compile;
405 compile = JAVAC_SUN.getMethod("compile", String[].class);
406 Object javac = JAVAC_SUN.getDeclaredConstructor().newInstance();
407 // Bugfix: Here we should check exit status value instead of parsing javac output text.
408 // Because of the output text is different in different locale environment.
409 // @since 2018-07-20 little-pan
410 final Integer status = (Integer)compile.invoke(javac, (Object) new String[] {
411 "-sourcepath", COMPILE_DIR,
412 // "-Xlint:unchecked",
413 "-d", COMPILE_DIR,
414 "-encoding", "UTF-8",
415 javaFile.toAbsolutePath().toString() });
416 String output = Utils10.byteArrayOutputStreamToString(buff, StandardCharsets.UTF_8);
417 handleSyntaxError(output, status);
418 } catch (Exception e) {
419 throw DbException.convert(e);
420 } finally {
421 System.setErr(old);
422 }
423 }
424
425 private static void handleSyntaxError(String output, int exitStatus) {
426 if(0 == exitStatus){
427 return;
428 }
429 boolean syntaxError = false;
430 final BufferedReader reader = new BufferedReader(new StringReader(output));
431 try {
432 for (String line; (line = reader.readLine()) != null;) {
433 if (line.endsWith("warning") || line.endsWith("warnings")) {
434 // ignore summary line
435 } else if (line.startsWith("Note:")
436 || line.startsWith("warning:")) {
437 // just a warning (e.g. unchecked or unsafe operations)
438 } else {
439 syntaxError = true;
440 break;
441 }
442 }
443 } catch (IOException ignored) {
444 // exception ignored
445 }
446
447 if (syntaxError) {
448 output = StringUtils.replaceAll(output, COMPILE_DIR, "");
449 throw DbException.get(ErrorCode.SYNTAX_ERROR_1, output);
450 }
451 }
452
453
454 /**
455 * Access the Groovy compiler using reflection, so that we do not gain a
456 * compile-time dependency unnecessarily.
457 */
458 private static final class GroovyCompiler {
459
460 private static final Object LOADER;
461 private static final Throwable INIT_FAIL_EXCEPTION;
462
463 static {
464 Object loader = null;
465 Throwable initFailException = null;
466 try {
467 // Create an instance of ImportCustomizer
468 Class<?> importCustomizerClass = Class.forName(
469 "org.codehaus.groovy.control.customizers.ImportCustomizer");
470 Object importCustomizer = Utils.newInstance(
471 "org.codehaus.groovy.control.customizers.ImportCustomizer");
472 // Call the method ImportCustomizer.addImports(String[])
473 String[] importsArray = {
474 "java.sql.Connection",
475 "java.sql.Types",
476 "java.sql.ResultSet",
477 "groovy.sql.Sql",
478 "org.h2.tools.SimpleResultSet"
479 };
480 Utils.callMethod(importCustomizer, "addImports", new Object[] { importsArray });
481
482 // Call the method
483 // CompilerConfiguration.addCompilationCustomizers(
484 // ImportCustomizer...)
485 Object importCustomizerArray = Array.newInstance(importCustomizerClass, 1);
486 Array.set(importCustomizerArray, 0, importCustomizer);
487 Object configuration = Utils.newInstance(
488 "org.codehaus.groovy.control.CompilerConfiguration");
489 Utils.callMethod(configuration,
490 "addCompilationCustomizers", importCustomizerArray);
491
492 ClassLoader parent = GroovyCompiler.class.getClassLoader();
493 loader = Utils.newInstance(
494 "groovy.lang.GroovyClassLoader", parent, configuration);
495 } catch (Exception ex) {
496 initFailException = ex;
497 }
498 LOADER = loader;
499 INIT_FAIL_EXCEPTION = initFailException;
500 }
501
502 public static Class<?> parseClass(String source,
503 String packageAndClassName) {
504 if (LOADER == null) {
505 throw new RuntimeException(
506 "Compile fail: no Groovy jar in the classpath", INIT_FAIL_EXCEPTION);
507 }
508 try {
509 Object codeSource = Utils.newInstance("groovy.lang.GroovyCodeSource",
510 source, packageAndClassName + ".groovy", "UTF-8");
511 Utils.callMethod(codeSource, "setCachable", false);
512 return (Class<?>) Utils.callMethod(
513 LOADER, "parseClass", codeSource);
514 } catch (Exception e) {
515 throw new RuntimeException(e);
516 }
517 }
518 }
519
520 /**
521 * An in-memory java source file object.
522 */
523 static class StringJavaFileObject extends SimpleJavaFileObject {
524
525 private final String sourceCode;
526
527 public StringJavaFileObject(String className, String sourceCode) {
528 super(URI.create("string:///" + className.replace('.', '/')
529 + Kind.SOURCE.extension), Kind.SOURCE);
530 this.sourceCode = sourceCode;
531 }
532
533 @Override
534 public CharSequence getCharContent(boolean ignoreEncodingErrors) {
535 return sourceCode;
536 }
537
538 }
539
540 /**
541 * An in-memory java class object.
542 */
543 static class JavaClassObject extends SimpleJavaFileObject {
544
545 private final ByteArrayOutputStream out = new ByteArrayOutputStream();
546
547 public JavaClassObject(String name, Kind kind) {
548 super(URI.create("string:///" + name.replace('.', '/')
549 + kind.extension), kind);
550 }
551
552 public byte[] getBytes() {
553 return out.toByteArray();
554 }
555
556 @Override
557 public OutputStream openOutputStream() throws IOException {
558 return out;
559 }
560 }
561
562 /**
563 * An in-memory class file manager.
564 */
565 static class ClassFileManager extends
566 ForwardingJavaFileManager<StandardJavaFileManager> {
567
568 /**
569 * We use map because there can be nested, anonymous etc classes.
570 */
571 Map<String, JavaClassObject> classObjectsByName = new HashMap<>();
572
573 private SecureClassLoader classLoader = new SecureClassLoader() {
574
575 @Override
576 protected Class<?> findClass(String name)
577 throws ClassNotFoundException {
578 byte[] bytes = classObjectsByName.get(name).getBytes();
579 return super.defineClass(name, bytes, 0,
580 bytes.length);
581 }
582 };
583
584 public ClassFileManager(StandardJavaFileManager standardManager) {
585 super(standardManager);
586 }
587
588 @Override
589 public ClassLoader getClassLoader(Location location) {
590 return this.classLoader;
591 }
592
593 @Override
594 public JavaFileObject getJavaFileForOutput(Location location,
595 String className, Kind kind, FileObject sibling) throws IOException {
596 JavaClassObject classObject = new JavaClassObject(className, kind);
597 classObjectsByName.put(className, classObject);
598 return classObject;
599 }
600 }
601
602 }