1 /*
  2  * Copyright (c) 2013, 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 8023524 8304846
 27  * @requires vm.flagless
 28  * @library /test/lib/
 29  * @library /java/nio/file
 30  * @modules jdk.compiler
 31  *          jdk.zipfs
 32  * @run testng LogGeneratedClassesTest
 33  * @summary tests logging generated classes for lambda
 34  */
 35 import java.io.IOException;
 36 import java.nio.charset.Charset;
 37 import java.util.ArrayList;
 38 import java.util.List;
 39 import java.util.function.Predicate;
 40 import java.nio.file.Files;
 41 import java.nio.file.Path;
 42 import java.nio.file.Paths;
 43 import java.nio.file.attribute.PosixFileAttributeView;
 44 
 45 import jdk.test.lib.compiler.CompilerUtils;
 46 import jdk.test.lib.process.OutputAnalyzer;
 47 import org.testng.annotations.AfterClass;
 48 import org.testng.annotations.BeforeClass;
 49 import org.testng.annotations.Test;
 50 
 51 import static java.nio.file.attribute.PosixFilePermissions.*;
 52 import static jdk.test.lib.process.ProcessTools.*;
 53 import static org.testng.Assert.assertEquals;
 54 import static org.testng.Assert.assertFalse;
 55 import static org.testng.Assert.assertTrue;
 56 
 57 public class LogGeneratedClassesTest {
 58     static final Path DUMP_LAMBDA_PROXY_CLASS_FILES = Path.of("DUMP_LAMBDA_PROXY_CLASS_FILES");
 59     static final Path CLASSES = Path.of("classes").toAbsolutePath();
 60     String longFQCN;
 61 
 62     @BeforeClass
 63     public void setup() throws IOException {
 64         final List<String> scratch = new ArrayList<>();
 65         scratch.clear();
 66         scratch.add("package com.example;");
 67         scratch.add("public class TestLambda {");
 68         scratch.add("    interface I {");
 69         scratch.add("        int foo();");
 70         scratch.add("    }");
 71         scratch.add("    public static void main(String[] args) {");
 72         scratch.add("        System.setSecurityManager(new SecurityManager());");
 73         scratch.add("        I lam = () -> 10;");
 74         scratch.add("        Runnable r = () -> {");
 75         scratch.add("            System.out.println(\"Runnable\");");
 76         scratch.add("        };");
 77         scratch.add("        r.run();");
 78         scratch.add("        System.out.println(\"Finish\");");
 79         scratch.add("    }");
 80         scratch.add("}");
 81 
 82         Path testLambda = Path.of("TestLambda.java");
 83         Files.write(testLambda, scratch, Charset.defaultCharset());
 84 
 85         scratch.remove(0);
 86         scratch.remove(0);
 87         scratch.add(0, "public class LongPackageName {");
 88         StringBuilder sb = new StringBuilder("com.example.");
 89         // longer than 255 which exceed max length of most filesystems
 90         for (int i = 0; i < 30; i++) {
 91             sb.append("nonsense.");
 92         }
 93         sb.append("enough");
 94         longFQCN = sb.toString() + ".LongPackageName";
 95         sb.append(";");
 96         sb.insert(0, "package ");
 97         scratch.add(0, sb.toString());
 98         Path lpnTest = Path.of("LongPackageName.java");
 99         Files.write(lpnTest, scratch, Charset.defaultCharset());
100 
101         CompilerUtils.compile(Path.of("."), CLASSES);
102     }
103 
104     @AfterClass
105     public void cleanup() throws IOException {
106         Files.delete(Paths.get("TestLambda.java"));
107         Files.delete(Paths.get("LongPackageName.java"));
108         TestUtil.removeAll(DUMP_LAMBDA_PROXY_CLASS_FILES);
109         TestUtil.removeAll(Paths.get("notDir"));
110         TestUtil.removeAll(Paths.get("dump"));
111         TestUtil.removeAll(Paths.get("dumpLong"));
112     }
113 
114     @Test
115     public void testNotLogging() throws Exception {
116         ProcessBuilder pb = createLimitedTestJavaProcessBuilder(
117                                "-cp", CLASSES.toString(),
118                                "-Djava.security.manager=allow",
119                                "com.example.TestLambda");
120         executeProcess(pb).shouldHaveExitValue(0);
121     }
122 
123     @Test
124     public void testLogging() throws Exception {
125         Path testDir = Path.of("dump");
126         Path dumpDir = testDir.resolve(DUMP_LAMBDA_PROXY_CLASS_FILES);
127         Files.createDirectory(testDir);
128         ProcessBuilder pb = createLimitedTestJavaProcessBuilder(
129                                "-cp", CLASSES.toString(),
130                                "-Djava.security.manager=allow",
131                                "-Djdk.invoke.LambdaMetafactory.dumpProxyClassFiles",
132                                "com.example.TestLambda").directory(testDir.toFile());
133         executeProcess(pb).shouldHaveExitValue(0);
134 
135         // 2 our own class files. We don't care about the others
136         assertEquals(Files.find(
137                         dumpDir,
138                         99,
139                         (p, a) -> p.startsWith(dumpDir.resolve("com/example"))
140                                 && a.isRegularFile()).count(),
141                         2, "Two lambda captured");
142     }
143 
144     @Test
145     public void testDumpDirNotExist() throws Exception {
146         Path testDir = Path.of("NotExist");
147         Path dumpDir = testDir.resolve(DUMP_LAMBDA_PROXY_CLASS_FILES);
148         Files.createDirectory(testDir);
149         TestUtil.removeAll(dumpDir);
150         assertFalse(Files.exists(dumpDir));
151 
152         ProcessBuilder pb = createLimitedTestJavaProcessBuilder(
153                                 "-cp", CLASSES.toString(),
154                                 "-Djava.security.manager=allow",
155                                 "-Djdk.invoke.LambdaMetafactory.dumpProxyClassFiles",
156                                 "com.example.TestLambda").directory(testDir.toFile());
157         executeProcess(pb).shouldHaveExitValue(0);
158 
159         // The dump directory will be created if not exist
160         assertEquals(Files.find(
161                         dumpDir,
162                         99,
163                         (p, a) -> p.startsWith(dumpDir.resolve("com/example"))
164                                 && a.isRegularFile()).count(),
165                         2, "Two lambda captured");
166     }
167 
168     @Test
169     public void testDumpDirIsFile() throws Exception {
170         Path testDir = Path.of("notDir");
171         Path dumpFile = testDir.resolve(DUMP_LAMBDA_PROXY_CLASS_FILES);
172         Files.createDirectory(testDir);
173         Files.createFile(dumpFile);
174         assertTrue(Files.isRegularFile(dumpFile));
175         ProcessBuilder pb = createLimitedTestJavaProcessBuilder(
176                                 "-cp", CLASSES.toString(),
177                                 "-Djava.security.manager=allow",
178                                 "-Djdk.invoke.LambdaMetafactory.dumpProxyClassFiles",
179                                 "com.example.TestLambda").directory(testDir.toFile());
180         executeProcess(pb)
181                 .shouldContain("DUMP_LAMBDA_PROXY_CLASS_FILES is not a directory")
182                 .shouldNotHaveExitValue(0);
183     }
184 
185     private static boolean isWriteableDirectory(Path p) {
186         if (!Files.isDirectory(p)) {
187             return false;
188         }
189         Path test = p.resolve(Paths.get("test"));
190         try {
191             Files.createFile(test);
192             assertTrue(Files.exists(test));
193             return true;
194         } catch (IOException e) {
195             assertFalse(Files.exists(test));
196             return false;
197         } finally {
198             if (Files.exists(test)) {
199                 try {
200                     Files.delete(test);
201                 } catch (IOException e) {
202                     throw new Error(e);
203                 }
204             }
205         }
206     }
207 
208     @Test
209     public void testDumpDirNotWritable() throws Exception {
210         if (!Files.getFileStore(Paths.get("."))
211                   .supportsFileAttributeView(PosixFileAttributeView.class)) {
212             // No easy way to setup readonly directory without POSIX
213             // We would like to skip the test with a cause with
214             //     throw new SkipException("Posix not supported");
215             // but jtreg will report failure so we just pass the test
216             // which we can look at if jtreg changed its behavior
217             System.out.println("WARNING: POSIX is not supported. Skipping testDumpDirNotWritable test.");
218             return;
219         }
220 
221         Path testDir = Path.of("readOnly");
222         Path dumpDir = testDir.resolve(DUMP_LAMBDA_PROXY_CLASS_FILES);
223         Files.createDirectory(testDir);
224         Files.createDirectory(dumpDir,
225                               asFileAttribute(fromString("r-xr-xr-x")));
226         try {
227             if (isWriteableDirectory(dumpDir)) {
228                 // Skipping the test: it's allowed to write into read-only directory
229                 // (e.g. current user is super user).
230                 System.out.println("WARNING: The dump directory is writeable. Skipping testDumpDirNotWritable test.");
231                 return;
232             }
233 
234             ProcessBuilder pb = createLimitedTestJavaProcessBuilder(
235                                    "-cp", CLASSES.toString(),
236                                    "-Djava.security.manager=allow",
237                                    "-Djdk.invoke.LambdaMetafactory.dumpProxyClassFiles",
238                                    "com.example.TestLambda").directory(testDir.toFile());
239             executeProcess(pb)
240                     .shouldContain("DUMP_LAMBDA_PROXY_CLASS_FILES is not writable")
241                     .shouldNotHaveExitValue(0);
242         } finally {
243             TestUtil.removeAll(testDir);
244         }
245     }
246 
247     @Test
248     public void testLoggingException() throws Exception {
249         Path testDir = Path.of("dumpLong");
250         Path dumpDir = testDir.resolve(DUMP_LAMBDA_PROXY_CLASS_FILES);
251         Files.createDirectories(dumpDir.resolve("com/example/nonsense"));
252         Files.createFile(dumpDir.resolve("com/example/nonsense/nonsense"));
253         ProcessBuilder pb = createLimitedTestJavaProcessBuilder(
254                                "-cp", CLASSES.toString(),
255                                "-Djava.security.manager=allow",
256                                "-Djdk.invoke.LambdaMetafactory.dumpProxyClassFiles",
257                                longFQCN).directory(testDir.toFile());
258         OutputAnalyzer outputAnalyzer = executeProcess(pb);
259         outputAnalyzer.shouldHaveExitValue(0);
260         assertEquals(outputAnalyzer.asLines().stream()
261                                   .filter(s -> s.startsWith("WARNING: Exception"))
262                                   .count(),
263                      2, "show error each capture");
264         // dumpLong/DUMP_LAMBDA_PROXY_CLASS_FILES/com/example/nonsense/nonsense
265         Path dumpPath = dumpDir.resolve("com/example/nonsense");
266         Predicate<Path> filter = p -> p.getParent() == null || dumpPath.startsWith(p) || p.startsWith(dumpPath);
267         boolean debug = true;
268         if (debug) {
269            Files.walk(dumpDir)
270                 .forEachOrdered(p -> {
271                     if (filter.test(p)) {
272                         System.out.println("accepted: " + p.toString());
273                     } else {
274                         System.out.println("filtered out: " + p.toString());
275                     }
276                  });
277         }
278         assertEquals(Files.walk(dumpDir)
279                 .filter(filter)
280                 .count(), 5, "Two lambda captured failed to log");
281     }
282 }