1 /*
  2  * Copyright (c) 2018, 2023, 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.
  8  *
  9  * This code is distributed in the hope that it will be useful, but WITHOUT
 10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 12  * version 2 for more details (a copy is included in the LICENSE file that
 13  * accompanied this code).
 14  *
 15  * You should have received a copy of the GNU General Public License version
 16  * 2 along with this work; if not, write to the Free Software Foundation,
 17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 18  *
 19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 20  * or visit www.oracle.com if you need additional information or have any
 21  * questions.
 22  */
 23 
 24 /*
 25  * @test
 26  * @bug 8192920 8204588 8246774 8248843 8268869 8235876
 27  * @summary Test source launcher
 28  * @library /tools/lib
 29  * @enablePreview
 30  * @modules jdk.compiler/com.sun.tools.javac.api
 31  *          jdk.compiler/com.sun.tools.javac.launcher
 32  *          jdk.compiler/com.sun.tools.javac.main
 33  *          java.base/jdk.internal.classfile.impl
 34  *          java.base/jdk.internal.module
 35  * @build toolbox.JavaTask toolbox.JavacTask toolbox.TestRunner toolbox.ToolBox
 36  * @run main SourceLauncherTest
 37  * @ignore Verifier error
 38  */
 39 
 40 import java.lang.classfile.*;
 41 import java.lang.classfile.attribute.ModuleResolutionAttribute;
 42 import java.io.ByteArrayOutputStream;
 43 import java.io.File;
 44 import java.io.IOException;
 45 import java.io.OutputStream;
 46 import java.io.PrintStream;
 47 import java.io.PrintWriter;
 48 import java.io.StringWriter;
 49 import java.lang.reflect.InvocationTargetException;
 50 import java.nio.file.Files;
 51 import java.nio.file.Path;
 52 import java.nio.file.Paths;
 53 import java.util.ArrayList;
 54 import java.util.Collections;
 55 import java.util.HashMap;
 56 import java.util.Map;
 57 import java.util.List;
 58 import java.util.Properties;
 59 import java.util.regex.Pattern;
 60 import java.util.stream.Collectors;
 61 
 62 import com.sun.tools.javac.launcher.SourceLauncher;
 63 import com.sun.tools.javac.launcher.Fault;
 64 
 65 import toolbox.JavaTask;
 66 import toolbox.JavacTask;
 67 import toolbox.Task;
 68 import toolbox.TestRunner;
 69 import toolbox.ToolBox;
 70 
 71 import static jdk.internal.module.ClassFileConstants.WARN_INCUBATING;
 72 
 73 public class SourceLauncherTest extends TestRunner {
 74     public static void main(String... args) throws Exception {
 75         SourceLauncherTest t = new SourceLauncherTest();
 76         t.runTests(m -> new Object[] { Paths.get(m.getName()) });
 77     }
 78 
 79     SourceLauncherTest() {
 80         super(System.err);
 81         tb = new ToolBox();
 82         System.err.println("version: " + thisVersion);
 83     }
 84 
 85     private final ToolBox tb;
 86     private static final String thisVersion = System.getProperty("java.specification.version");
 87 
 88     /*
 89      * Positive tests.
 90      */
 91 
 92     @Test
 93     public void testHelloWorld(Path base) throws IOException {
 94         tb.writeJavaFiles(base,
 95             "import java.util.Arrays;\n" +
 96             "class HelloWorld {\n" +
 97             "    public static void main(String... args) {\n" +
 98             "        System.out.println(\"Hello World! \" + Arrays.toString(args));\n" +
 99             "    }\n" +
100             "}");
101         testSuccess(base.resolve("HelloWorld.java"), "Hello World! [1, 2, 3]\n");
102     }
103 
104     @Test
105     public void testHelloWorldInPackage(Path base) throws IOException {
106         tb.writeJavaFiles(base,
107             "package hello;\n" +
108             "import java.util.Arrays;\n" +
109             "class World {\n" +
110             "    public static void main(String... args) {\n" +
111             "        System.out.println(\"Hello World! \" + Arrays.toString(args));\n" +
112             "    }\n" +
113             "}");
114         testSuccess(base.resolve("hello").resolve("World.java"), "Hello World! [1, 2, 3]\n");
115     }
116 
117     @Test
118     public void testHelloWorldWithAux(Path base) throws IOException {
119         tb.writeJavaFiles(base,
120             "import java.util.Arrays;\n" +
121             "class HelloWorld {\n" +
122             "    public static void main(String... args) {\n" +
123             "        Aux.write(args);\n" +
124             "    }\n" +
125             "}\n" +
126             "class Aux {\n" +
127             "    static void write(String... args) {\n" +
128             "        System.out.println(\"Hello World! \" + Arrays.toString(args));\n" +
129             "    }\n" +
130             "}");
131         testSuccess(base.resolve("HelloWorld.java"), "Hello World! [1, 2, 3]\n");
132     }
133 
134     @Test
135     public void testHelloWorldWithShebang(Path base) throws IOException {
136         tb.writeJavaFiles(base,
137             "#!/usr/bin/java --source " + thisVersion + "\n" +
138             "import java.util.Arrays;\n" +
139             "class HelloWorld {\n" +
140             "    public static void main(String... args) {\n" +
141             "        System.out.println(\"Hello World! \" + Arrays.toString(args));\n" +
142             "    }\n" +
143             "}");
144         Files.copy(base.resolve("HelloWorld.java"), base.resolve("HelloWorld"));
145         testSuccess(base.resolve("HelloWorld"), "Hello World! [1, 2, 3]\n");
146     }
147 
148     @Test
149     public void testNoAnnoProcessing(Path base) throws IOException {
150         Path annoSrc = base.resolve("annoSrc");
151         tb.writeJavaFiles(annoSrc,
152             "import java.util.*;\n" +
153             "import javax.annotation.processing.*;\n" +
154             "import javax.lang.model.element.*;\n" +
155             "@SupportedAnnotationTypes(\"*\")\n" +
156             "public class AnnoProc extends AbstractProcessor {\n" +
157             "    public boolean process(Set<? extends TypeElement> annos, RoundEnvironment rEnv) {\n" +
158             "        throw new Error(\"Annotation processor should not be invoked\");\n" +
159             "    }\n" +
160             "}\n");
161         Path annoClasses = Files.createDirectories(base.resolve("classes"));
162         new JavacTask(tb)
163                 .outdir(annoClasses)
164                 .files(annoSrc.resolve("AnnoProc.java").toString())
165                 .run();
166         Path serviceFile = annoClasses.resolve("META-INF").resolve("services")
167                 .resolve("javax.annotation.processing.Processor");
168         tb.writeFile(serviceFile, "AnnoProc");
169 
170         Path mainSrc = base.resolve("mainSrc");
171         tb.writeJavaFiles(mainSrc,
172             "import java.util.Arrays;\n" +
173             "class HelloWorld {\n" +
174             "    public static void main(String... args) {\n" +
175             "        System.out.println(\"Hello World! \" + Arrays.toString(args));\n" +
176             "    }\n" +
177             "}");
178 
179         List<String> javacArgs = List.of("-classpath", annoClasses.toString());
180         List<String> classArgs = List.of("1", "2", "3");
181         String expect = "Hello World! [1, 2, 3]\n";
182         Result r = run(mainSrc.resolve("HelloWorld.java"), javacArgs, classArgs);
183         checkEqual("stdout", r.stdOut, expect);
184         checkEmpty("stderr", r.stdErr);
185         checkNull("exception", r.exception);
186     }
187 
188     @Test
189     public void testEnablePreview(Path base) throws IOException {
190         tb.writeJavaFiles(base,
191             "import java.util.Arrays;\n" +
192             "class HelloWorld {\n" +
193             "    public static void main(String... args) {\n" +
194             "        System.out.println(\"Hello World! \" + Arrays.toString(args));\n" +
195             "    }\n" +
196             "}");
197 
198         String log = new JavaTask(tb)
199                 .vmOptions("--enable-preview", "--source", thisVersion)
200                 .className(base.resolve("HelloWorld.java").toString())
201                 .classArgs("1", "2", "3")
202                 .run(Task.Expect.SUCCESS)
203                 .getOutput(Task.OutputKind.STDOUT);
204         checkEqual("stdout", log.trim(), "Hello World! [1, 2, 3]");
205     }
206 
207     @Test
208     public void testCodeSource(Path base) throws IOException {
209         tb.writeJavaFiles(base,
210             "import java.net.URL;\n" +
211             "class ShowCodeSource {\n" +
212             "    public static void main(String... args) {\n" +
213             "        URL u = ShowCodeSource.class.getProtectionDomain().getCodeSource().getLocation();\n" +
214             "        System.out.println(u);\n" +
215             "    }\n" +
216             "}");
217 
218         Path file = base.resolve("ShowCodeSource.java");
219         String log = new JavaTask(tb)
220                 .className(file.toString())
221                 .run(Task.Expect.SUCCESS)
222                 .getOutput(Task.OutputKind.STDOUT);
223         checkEqual("stdout", log.trim(), file.toAbsolutePath().toUri().toURL().toString());
224     }
225 
226     @Test
227     public void testSecurityManager(Path base) throws IOException {
228         Path sourceFile = base.resolve("HelloWorld.java");
229         tb.writeJavaFiles(base,
230                 "class HelloWorld {\n" +
231                         "    public static void main(String... args) {\n" +
232                         "        System.out.println(\"Hello World!\");\n" +
233                         "    }\n" +
234                         "}");
235 
236         String log = new JavaTask(tb)
237                 .vmOptions("-Djava.security.manager=default")
238                 .className(sourceFile.toString())
239                 .run(Task.Expect.FAIL)
240                 .getOutput(Task.OutputKind.STDERR);
241         checkContains("stderr", log,
242                 "error: cannot use source-code launcher with a security manager enabled");
243     }
244 
245     @Test
246     public void testSystemProperty(Path base) throws IOException {
247         tb.writeJavaFiles(base,
248             "class ShowProperty {\n" +
249             "    public static void main(String... args) {\n" +
250             "        System.out.println(System.getProperty(\"jdk.launcher.sourcefile\"));\n" +
251             "    }\n" +
252             "}");
253 
254         Path file = base.resolve("ShowProperty.java");
255         String log = new JavaTask(tb)
256                 .className(file.toString())
257                 .run(Task.Expect.SUCCESS)
258                 .getOutput(Task.OutputKind.STDOUT);
259         checkEqual("stdout", log.trim(), file.toAbsolutePath().toString());
260     }
261 
262     void testSuccess(Path file, String expect) throws IOException {
263         Result r = run(file, Collections.emptyList(), List.of("1", "2", "3"));
264         checkEqual("stdout", r.stdOut, expect);
265         checkEmpty("stderr", r.stdErr);
266         checkNull("exception", r.exception);
267     }
268 
269     /*
270      * Negative tests: such as cannot find or execute main method.
271      */
272 
273     @Test
274     public void testHelloWorldWithShebangJava(Path base) throws IOException {
275         tb.writeJavaFiles(base,
276             "#!/usr/bin/java --source " + thisVersion + "\n" +
277             "import java.util.Arrays;\n" +
278             "class HelloWorld {\n" +
279             "    public static void main(String... args) {\n" +
280             "        System.out.println(\"Hello World! \" + Arrays.toString(args));\n" +
281             "    }\n" +
282             "}");
283         Path file = base.resolve("HelloWorld.java");
284         testError(file,
285             file + ":1: error: illegal character: '#'\n" +
286             "#!/usr/bin/java --source " + thisVersion + "\n" +
287             "^\n" +
288             file + ":1: error: class, interface, enum, or record expected\n" +
289             "#!/usr/bin/java --source " + thisVersion + "\n" +
290             "  ^\n" +
291             "2 errors\n",
292             "error: compilation failed");
293     }
294 
295     @Test
296     public void testNoClass(Path base) throws IOException {
297         var path = Files.createDirectories(base.resolve("p"));
298         Path file = path.resolve("NoClass.java");
299         Files.write(file, List.of("package p;"));
300         testError(file, "", "error: no class declared in source file");
301     }
302 
303     @Test
304     public void testMismatchOfPathAndPackage(Path base) throws IOException {
305         Files.createDirectories(base);
306         Path file = base.resolve("MismatchOfPathAndPackage.java");
307         Files.write(file, List.of("package p;"));
308         testError(file, "", "error: end of path to source file does not match its package name p: " + file);
309     }
310 
311     @Test
312     public void testLoadClass(Path base) throws IOException {
313         Path src1 = base.resolve("src1");
314         Path file1 = src1.resolve("LoadClass.java");
315         tb.writeJavaFiles(src1,
316                 "class LoadClass {\n"
317                 + "    public static void main(String... args) {\n"
318                 + "        System.out.println(\"on classpath\");\n"
319                 + "    };\n"
320                 + "}\n");
321         Path classes1 = Files.createDirectories(base.resolve("classes"));
322         new JavacTask(tb)
323                 .outdir(classes1)
324                 .files(file1)
325                 .run();
326         String log1 = new JavaTask(tb)
327                 .classpath(classes1.toString())
328                 .className("LoadClass")
329                 .run(Task.Expect.SUCCESS)
330                 .getOutput(Task.OutputKind.STDOUT);
331         checkEqual("stdout", log1.trim(),
332                 "on classpath");
333 
334         Path src2 = base.resolve("src2");
335         Path file2 = src2.resolve("LoadClass.java");
336         tb.writeJavaFiles(src2,
337                 "class LoadClass {\n"
338                 + "    public static void main(String... args) {\n"
339                 + "        System.out.println(\"in source file\");\n"
340                 + "    };\n"
341                 + "}\n");
342         String log2 = new JavaTask(tb)
343                 .classpath(classes1.toString())
344                 .className(file2.toString())
345                 .run(Task.Expect.SUCCESS)
346                 .getOutput(Task.OutputKind.STDOUT);
347         checkEqual("stdout", log2.trim(),
348                 "in source file");
349     }
350 
351     @Test
352     public void testGetResource(Path base) throws IOException {
353         Path src = base.resolve("src");
354         Path file = src.resolve("GetResource.java");
355         tb.writeJavaFiles(src,
356                 "class GetResource {\n"
357                 + "    public static void main(String... args) {\n"
358                 + "        System.out.println(GetResource.class.getClassLoader().getResource(\"GetResource.class\"));\n"
359                 + "    };\n"
360                 + "}\n");
361         Path classes = Files.createDirectories(base.resolve("classes"));
362         new JavacTask(tb)
363                 .outdir(classes)
364                 .files(file)
365                 .run();
366 
367         String log = new JavaTask(tb)
368                 .classpath(classes.toString())
369                 .className(file.toString())
370                 .run(Task.Expect.SUCCESS)
371                 .getOutput(Task.OutputKind.STDOUT);
372         checkMatch("stdout", log.trim(),
373                 Pattern.compile("sourcelauncher-memoryclassloader[0-9]+:GetResource.class"));
374     }
375 
376     @Test
377     public void testGetResources(Path base) throws IOException {
378         Path src = base.resolve("src");
379         Path file = src.resolve("GetResources.java");
380         tb.writeJavaFiles(src,
381                 "import java.io.*; import java.net.*; import java.util.*;\n"
382                 + "class GetResources {\n"
383                 + "    public static void main(String... args) throws IOException {\n"
384                 + "        Enumeration<URL> e =\n"
385                 + "            GetResources.class.getClassLoader().getResources(\"GetResources.class\");\n"
386                 + "        while (e.hasMoreElements()) System.out.println(e.nextElement());\n"
387                 + "    };\n"
388                 + "}\n");
389         Path classes = Files.createDirectories(base.resolve("classes"));
390         new JavacTask(tb)
391                 .outdir(classes)
392                 .files(file)
393                 .run();
394 
395         List<String> log = new JavaTask(tb)
396                 .classpath(classes.toString())
397                 .className(file.toString())
398                 .run(Task.Expect.SUCCESS)
399                 .getOutputLines(Task.OutputKind.STDOUT);
400         checkMatch("stdout:0", log.get(0).trim(),
401                 Pattern.compile("sourcelauncher-memoryclassloader[0-9]+:GetResources.class"));
402         checkMatch("stdout:1", log.get(1).trim(),
403                 Pattern.compile("file:/.*/testGetResources/classes/GetResources.class"));
404     }
405 
406     @Test
407     public void testSyntaxErr(Path base) throws IOException {
408         tb.writeJavaFiles(base, "class SyntaxErr {");
409         Path file = base.resolve("SyntaxErr.java");
410         testError(file,
411                 file + ":1: error: reached end of file while parsing\n" +
412                 "class SyntaxErr {\n" +
413                 "                 ^\n" +
414                 "1 error\n",
415                 "error: compilation failed");
416     }
417 
418     @Test
419     public void testNoSourceOnClassPath(Path base) throws IOException {
420         Path extraSrc = base.resolve("extraSrc");
421         tb.writeJavaFiles(extraSrc,
422             "public class Extra {\n" +
423             "    static final String MESSAGE = \"Hello World\";\n" +
424             "}\n");
425 
426         Path mainSrc = base.resolve("mainSrc");
427         tb.writeJavaFiles(mainSrc,
428             "import java.util.Arrays;\n" +
429             "class HelloWorld {\n" +
430             "    public static void main(String... args) {\n" +
431             "        System.out.println(Extra.MESSAGE + Arrays.toString(args));\n" +
432             "    }\n" +
433             "}");
434 
435         List<String> javacArgs = List.of("-classpath", extraSrc.toString());
436         List<String> classArgs = List.of("1", "2", "3");
437         String FS = File.separator;
438         String expectStdErr =
439             "testNoSourceOnClassPath" + FS + "mainSrc" + FS + "HelloWorld.java:4: error: cannot find symbol\n" +
440             "        System.out.println(Extra.MESSAGE + Arrays.toString(args));\n" +
441             "                           ^\n" +
442             "  symbol:   variable Extra\n" +
443             "  location: class HelloWorld\n" +
444             "1 error\n";
445         Result r = run(mainSrc.resolve("HelloWorld.java"), javacArgs, classArgs);
446         checkEmpty("stdout", r.stdOut);
447         checkEqual("stderr", r.stdErr, expectStdErr);
448         checkFault("exception", r.exception, "error: compilation failed");
449     }
450 
451     @Test
452     public void testClassNotFound(Path base) throws IOException {
453         Path src = base.resolve("src");
454         Path file = src.resolve("ClassNotFound.java");
455         tb.writeJavaFiles(src,
456                 "class ClassNotFound {\n"
457                 + "    public static void main(String... args) {\n"
458                 + "        try {\n"
459                 + "            Class.forName(\"NoSuchClass\");\n"
460                 + "            System.out.println(\"no exception\");\n"
461                 + "            System.exit(1);\n"
462                 + "        } catch (ClassNotFoundException e) {\n"
463                 + "            System.out.println(\"Expected exception thrown: \" + e);\n"
464                 + "        }\n"
465                 + "    };\n"
466                 + "}\n");
467         Path classes = Files.createDirectories(base.resolve("classes"));
468         new JavacTask(tb)
469                 .outdir(classes)
470                 .files(file)
471                 .run();
472 
473         String log = new JavaTask(tb)
474                 .classpath(classes.toString())
475                 .className(file.toString())
476                 .run(Task.Expect.SUCCESS)
477                 .getOutput(Task.OutputKind.STDOUT);
478         checkEqual("stdout", log.trim(),
479                 "Expected exception thrown: java.lang.ClassNotFoundException: NoSuchClass");
480     }
481 
482     // For any source file that is invoked through the OS shebang mechanism, invalid shebang
483     // lines will be caught and handled by the OS, before the launcher is even invoked.
484     // However, if such a file is passed directly to the launcher, perhaps using the --source
485     // option, a well-formed shebang line will be removed but a badly-formed one will be not be
486     // removed and will cause compilation errors.
487     @Test
488     public void testBadShebang(Path base) throws IOException {
489         tb.writeJavaFiles(base,
490             "#/usr/bin/java --source " + thisVersion + "\n" +
491             "import java.util.Arrays;\n" +
492             "class HelloWorld {\n" +
493             "    public static void main(String... args) {\n" +
494             "        System.out.println(\"Hello World! \" + Arrays.toString(args));\n" +
495             "    }\n" +
496             "}");
497         Path file = base.resolve("HelloWorld.java");
498         testError(file,
499             file + ":1: error: illegal character: '#'\n" +
500             "#/usr/bin/java --source " + thisVersion + "\n" +
501             "^\n" +
502             file + ":1: error: class, interface, enum, or record expected\n" +
503             "#/usr/bin/java --source " + thisVersion + "\n" +
504             "  ^\n" +
505             "2 errors\n",
506             "error: compilation failed");
507     }
508 
509     @Test
510     public void testBadSourceOpt(Path base) throws IOException {
511         Files.createDirectories(base);
512         Path file = base.resolve("DummyClass.java");
513         Files.write(file, List.of("class DummyClass { }"));
514         Properties sysProps = System.getProperties();
515         Properties p = new Properties(sysProps);
516         p.setProperty("jdk.internal.javac.source", "<BAD>");
517         System.setProperties(p);
518         try {
519             testError(file, "", "error: invalid value for --source option: <BAD>");
520         } finally {
521             System.setProperties(sysProps);
522         }
523     }
524 
525     @Test
526     public void testEnablePreviewNoSource(Path base) throws IOException {
527         tb.writeJavaFiles(base,
528             "import java.util.Arrays;\n" +
529             "class HelloWorld {\n" +
530             "    public static void main(String... args) {\n" +
531             "        System.out.println(\"Hello World! \" + Arrays.toString(args));\n" +
532             "    }\n" +
533             "}");
534 
535         List<String> log = new JavaTask(tb)
536                 .vmOptions("--enable-preview")
537                 .className(base.resolve("HelloWorld.java").toString())
538                 .run(Task.Expect.FAIL)
539                 .getOutputLines(Task.OutputKind.STDERR);
540         log = log.stream().filter(s->!s.matches("^Picked up .*JAVA.*OPTIONS:.*")).collect(Collectors.toList());
541         checkEqual("stderr", log, List.of("error: --enable-preview must be used with --source"));
542     }
543 
544     @Test
545     public void testNoMain(Path base) throws IOException {
546         tb.writeJavaFiles(base, "class NoMain { }");
547         testError(base.resolve("NoMain.java"), "",
548                 "error: can't find main(String[]) method in class: NoMain");
549     }
550 
551     //@Test temporary disabled as enabled preview allows no-param main
552     public void testMainBadParams(Path base) throws IOException {
553         tb.writeJavaFiles(base,
554                 "class BadParams { public static void main() { } }");
555         testError(base.resolve("BadParams.java"), "",
556                 "error: can't find main(String[]) method in class: BadParams");
557     }
558 
559     //@Test temporary disabled as enabled preview allows non-public main
560     public void testMainNotPublic(Path base) throws IOException {
561         tb.writeJavaFiles(base,
562                 "class NotPublic { static void main(String... args) { } }");
563         testError(base.resolve("NotPublic.java"), "",
564                 "error: can't find main(String[]) method in class: NotPublic");
565     }
566 
567     //@Test temporary disabled as enabled preview allows non-static main
568     public void testMainNotStatic(Path base) throws IOException {
569         tb.writeJavaFiles(base,
570                 "class NotStatic { public void main(String... args) { } }");
571         testError(base.resolve("NotStatic.java"), "",
572                 "error: can't find main(String[]) method in class: NotStatic");
573     }
574 
575     @Test
576     public void testMainNotVoid(Path base) throws IOException {
577         tb.writeJavaFiles(base,
578                 "class NotVoid { public static int main(String... args) { return 0; } }");
579         testError(base.resolve("NotVoid.java"), "",
580                 "error: can't find main(String[]) method in class: NotVoid");
581     }
582 
583     @Test
584     public void testClassInModule(Path base) throws IOException {
585         tb.writeJavaFiles(base, "package java.net; class InModule { }");
586         Path file = base.resolve("java").resolve("net").resolve("InModule.java");
587         testError(file,
588                 file + ":1: error: package exists in another module: java.base\n" +
589                 "package java.net; class InModule { }\n" +
590                 "^\n" +
591                 "1 error\n",
592                 "error: compilation failed");
593     }
594 
595     @Test
596     public void testNoRecompileWithSuggestions(Path base) throws IOException {
597         tb.writeJavaFiles(base,
598             "class NoRecompile {\n" +
599             "    void use(String s) {}\n" +
600             "    void test() {\n" +
601             "        use(1);\n" +
602             "    }\n" +
603             "    <T> void test(T t, Object o) {\n" +
604             "        T t1 = (T) o;\n" +
605             "    }\n" +
606             "    static class Generic<T> {\n" +
607             "        T t;\n" +
608             "        void raw(Generic raw) {\n" +
609             "            raw.t = \"\";\n" +
610             "        }\n" +
611             "    }\n" +
612             "    void deprecation() {\n" +
613             "        Thread.currentThread().stop();\n" +
614             "    }\n" +
615             "    void preview(Object o) {\n" +
616             "      if (o instanceof String s) {\n" +
617             "          System.out.println(s);\n" +
618             "      }\n" +
619             "    }\n" +
620             "}");
621         Result r = run(base.resolve("NoRecompile.java"), Collections.emptyList(), Collections.emptyList());
622         if (r.stdErr.contains("recompile with")) {
623             error("Unexpected recompile suggestions in error output: " + r.stdErr);
624         }
625     }
626 
627     @Test
628     public void testNoOptionsWarnings(Path base) throws IOException {
629         tb.writeJavaFiles(base, "public class Main { public static void main(String... args) {}}");
630         String log = new JavaTask(tb)
631                 .vmOptions("--source", "21")
632                 .className(base.resolve("Main.java").toString())
633                 .run(Task.Expect.SUCCESS)
634                 .getOutput(Task.OutputKind.STDERR);
635 
636         if (log.contains("warning: [options]")) {
637             error("Unexpected options warning in error output: " + log);
638         }
639     }
640 
641     void testError(Path file, String expectStdErr, String expectFault) throws IOException {
642         Result r = run(file, Collections.emptyList(), List.of("1", "2", "3"));
643         checkEmpty("stdout", r.stdOut);
644         checkEqual("stderr", r.stdErr, expectStdErr);
645         checkFault("exception", r.exception, expectFault);
646     }
647 
648     /*
649      * Tests in which main throws an exception.
650      */
651     @Test
652     public void testTargetException1(Path base) throws IOException {
653         tb.writeJavaFiles(base,
654             "import java.util.Arrays;\n" +
655             "class Thrower {\n" +
656             "    public static void main(String... args) {\n" +
657             "        throwWhenZero(Integer.parseInt(args[0]));\n" +
658             "    }\n" +
659             "    static void throwWhenZero(int arg) {\n" +
660             "        if (arg == 0) throw new Error(\"zero!\");\n" +
661             "        throwWhenZero(arg - 1);\n" +
662             "    }\n" +
663             "}");
664         Path file = base.resolve("Thrower.java");
665         Result r = run(file, Collections.emptyList(), List.of("3"));
666         checkEmpty("stdout", r.stdOut);
667         checkEmpty("stderr", r.stdErr);
668         checkTrace("exception", r.exception,
669                 "java.lang.Error: zero!",
670                 "at Thrower.throwWhenZero(Thrower.java:7)",
671                 "at Thrower.throwWhenZero(Thrower.java:8)",
672                 "at Thrower.throwWhenZero(Thrower.java:8)",
673                 "at Thrower.throwWhenZero(Thrower.java:8)",
674                 "at Thrower.main(Thrower.java:4)");
675     }
676 
677     @Test
678     public void testNoDuplicateIncubatorWarning(Path base) throws Exception {
679         Path module = base.resolve("lib");
680         Path moduleSrc = module.resolve("src");
681         Path moduleClasses = module.resolve("classes");
682         Files.createDirectories(moduleClasses);
683         tb.cleanDirectory(moduleClasses);
684         tb.writeJavaFiles(moduleSrc, "module test {}");
685         new JavacTask(tb)
686                 .outdir(moduleClasses)
687                 .files(tb.findJavaFiles(moduleSrc))
688                 .run()
689                 .writeAll();
690         markModuleAsIncubator(moduleClasses.resolve("module-info.class"));
691         tb.writeJavaFiles(base, "public class Main { public static void main(String... args) {}}");
692         String log = new JavaTask(tb)
693                 .vmOptions("--module-path", moduleClasses.toString(),
694                            "--add-modules", "test")
695                 .className(base.resolve("Main.java").toString())
696                 .run(Task.Expect.SUCCESS)
697                 .writeAll()
698                 .getOutput(Task.OutputKind.STDERR);
699 
700         int numberOfWarnings = log.split("WARNING").length - 1;
701 
702         if (log.contains("warning:") || numberOfWarnings != 1) {
703             error("Unexpected warning in error output: " + log);
704         }
705 
706         List<String> compileLog = new JavacTask(tb)
707                 .options("--module-path", moduleClasses.toString(),
708                          "--add-modules", "test",
709                          "-XDrawDiagnostics",
710                          "-XDsourceLauncher",
711                          "-XDshould-stop.at=FLOW")
712                 .files(base.resolve("Main.java").toString())
713                 .run(Task.Expect.SUCCESS)
714                 .writeAll()
715                 .getOutputLines(Task.OutputKind.DIRECT);
716 
717         List<String> expectedOutput = List.of(
718                 "- compiler.warn.incubating.modules: test",
719                 "1 warning"
720         );
721 
722         if (!expectedOutput.equals(compileLog)) {
723             error("Unexpected options : " + compileLog);
724         }
725     }
726         //where:
727         private static void markModuleAsIncubator(Path moduleInfoFile) throws Exception {
728             ClassModel cf = ClassFile.of().parse(moduleInfoFile);
729             ModuleResolutionAttribute newAttr = ModuleResolutionAttribute.of(WARN_INCUBATING);
730             byte[] newBytes = ClassFile.of().transform(cf, ClassTransform.dropping(ce -> ce instanceof Attributes)
731                     .andThen(ClassTransform.endHandler(classBuilder -> classBuilder.with(newAttr))));
732             try (OutputStream out = Files.newOutputStream(moduleInfoFile)) {
733                 out.write(newBytes);
734             }
735         }
736 
737     Result run(Path file, List<String> runtimeArgs, List<String> appArgs) {
738         List<String> args = new ArrayList<>();
739         args.add(file.toString());
740         args.addAll(appArgs);
741 
742         PrintStream prev = System.out;
743         ByteArrayOutputStream baos = new ByteArrayOutputStream();
744         try (PrintStream out = new PrintStream(baos, true)) {
745             System.setOut(out);
746             StringWriter sw = new StringWriter();
747             try (PrintWriter err = new PrintWriter(sw, true)) {
748                 SourceLauncher m = new SourceLauncher(err);
749                 m.run(toArray(runtimeArgs), toArray(args));
750                 return new Result(baos.toString(), sw.toString(), null);
751             } catch (Throwable t) {
752                 return new Result(baos.toString(), sw.toString(), t);
753             }
754         } finally {
755             System.setOut(prev);
756         }
757     }
758 
759     void checkEqual(String name, String found, String expect) {
760         expect = expect.replace("\n", tb.lineSeparator);
761         out.println(name + ": " + found);
762         if (!expect.equals(found)) {
763             error("Unexpected output; expected: " + expect);
764         }
765     }
766 
767     void checkContains(String name, String found, String expect) {
768         expect = expect.replace("\n", tb.lineSeparator);
769         out.println(name + ": " + found);
770         if (!found.contains(expect)) {
771             error("Expected output not found: " + expect);
772         }
773     }
774 
775     void checkEqual(String name, List<String> found, List<String> expect) {
776         out.println(name + ": " + found);
777         tb.checkEqual(expect, found);
778     }
779 
780     void checkMatch(String name, String found, Pattern expect) {
781         out.println(name + ": " + found);
782         if (!expect.matcher(found).matches()) {
783             error("Unexpected output; expected match for: " + expect);
784         }
785     }
786 
787     void checkEmpty(String name, String found) {
788         out.println(name + ": " + found);
789         if (!found.isEmpty()) {
790             error("Unexpected output; expected empty string");
791         }
792     }
793 
794     void checkNull(String name, Throwable found) {
795         out.println(name + ": " + found);
796         if (found != null) {
797             error("Unexpected exception; expected null");
798         }
799     }
800 
801     void checkFault(String name, Throwable found, String expect) {
802         expect = expect.replace("\n", tb.lineSeparator);
803         out.println(name + ": " + found);
804         if (found == null) {
805             error("No exception thrown; expected Fault");
806         } else {
807             if (!(found instanceof Fault)) {
808                 error("Unexpected exception; expected Fault");
809             }
810             if (!(found.getMessage().equals(expect))) {
811                 error("Unexpected detail message; expected: " + expect);
812             }
813         }
814     }
815 
816     void checkTrace(String name, Throwable found, String... expect) {
817         if (!(found instanceof InvocationTargetException)) {
818             error("Unexpected exception; expected InvocationTargetException");
819             out.println("Found:");
820             found.printStackTrace(out);
821         }
822         StringWriter sw = new StringWriter();
823         try (PrintWriter pw = new PrintWriter(sw)) {
824             ((InvocationTargetException) found).getTargetException().printStackTrace(pw);
825         }
826         String trace = sw.toString();
827         out.println(name + ":\n" + trace);
828         String[] traceLines = trace.trim().split("[\r\n]+\\s+");
829         try {
830             tb.checkEqual(List.of(traceLines), List.of(expect));
831         } catch (Error e) {
832             error(e.getMessage());
833         }
834     }
835 
836     String[] toArray(List<String> list) {
837         return list.toArray(new String[list.size()]);
838     }
839 
840     record Result(String stdOut, String stdErr, Throwable exception) {}
841 }