View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *   https://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing,
13   * software distributed under the License is distributed on an
14   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   * KIND, either express or implied.  See the License for the
16   * specific language governing permissions and limitations
17   * under the License.
18   */
19  
20  package org.apache.bcel.generic;
21  
22  import static org.junit.jupiter.api.Assertions.assertArrayEquals;
23  import static org.junit.jupiter.api.Assertions.assertNotNull;
24  import static org.junit.jupiter.api.Assertions.fail;
25  import static org.junit.jupiter.api.Assumptions.assumeTrue;
26  
27  import java.io.File;
28  import java.io.IOException;
29  import java.io.InputStream;
30  import java.nio.file.FileSystems;
31  import java.nio.file.FileVisitResult;
32  import java.nio.file.Files;
33  import java.nio.file.Path;
34  import java.nio.file.PathMatcher;
35  import java.nio.file.Paths;
36  import java.nio.file.SimpleFileVisitor;
37  import java.nio.file.attribute.BasicFileAttributes;
38  import java.util.Enumeration;
39  import java.util.jar.JarEntry;
40  import java.util.jar.JarFile;
41  import java.util.stream.Stream;
42  
43  import org.apache.bcel.classfile.ClassParser;
44  import org.apache.bcel.classfile.Code;
45  import org.apache.bcel.classfile.JavaClass;
46  import org.apache.bcel.classfile.Method;
47  import org.apache.bcel.util.ModularRuntimeImage;
48  import org.apache.commons.lang3.JavaVersion;
49  import org.apache.commons.lang3.SystemUtils;
50  import org.junit.jupiter.api.condition.DisabledOnJre;
51  import org.junit.jupiter.api.condition.JRE;
52  import org.junit.jupiter.params.ParameterizedTest;
53  import org.junit.jupiter.params.provider.MethodSource;
54  
55  /**
56   * Test that the generic dump() methods work on the JDK classes Reads each class into an instruction list and then dumps the instructions. The output bytes
57   * should be the same as the input.
58   * <p>
59   * Sets the property {@value JavaHome#EXTRA_JAVA_HOMES} to a {@link File#pathSeparator}-separated list of JRE/JDK paths for additional testing.
60   * </p>
61   * <p>
62   * For example:
63   * </p>
64   *
65   * <pre>
66   * mvn test -Dtest=JdkGenericDumpTest -DExtraJavaHomes="C:\Program Files\Java\openjdk\jdk-13;C:\Program Files\Java\openjdk\jdk-14"
67   * mvn test -Dtest=JdkGenericDumpTest -DExtraJavaRoot="C:\Program Files\Eclipse Adoptium"
68   * </pre>
69   * <p>
70   * Where "C:\Program Files\Eclipse Adoptium" contains JDK directories, for example:
71   * </p>
72   * <ul>
73   * <li>jdk-11.0.16.101-hotspot</li>
74   * <li>jdk-17.0.4.101-hotspot</li>
75   * <li>jdk-19.0.0.36-hotspot</li>
76   * <li>jdk-8.0.345.1-hotspot</li>
77   * </ul>
78   */
79  class JdkGenericDumpTest {
80  
81      private static final boolean PRINT_CLASS_NAME = Boolean.getBoolean("bcel.print.ClassNames");
82      private static final boolean PRINT_JAR_NAME = Boolean.getBoolean("bcel.print.JarNames");
83  
84      private static class ClassParserFilesVisitor extends SimpleFileVisitor<Path> {
85  
86          private final PathMatcher matcher;
87  
88          @SuppressWarnings("resource") // FileSystems.getDefault() returns a singleton
89          ClassParserFilesVisitor(final String pattern) {
90              matcher = FileSystems.getDefault().getPathMatcher("glob:" + pattern);
91          }
92  
93          private void find(final Path path) throws IOException {
94              final Path name = path.getFileName();
95              if (name != null && matcher.matches(name)) {
96                  try (InputStream inputStream = Files.newInputStream(path)) {
97                      final ClassParser classParser = new ClassParser(inputStream, name.toAbsolutePath().toString());
98                      assertNotNull(classParser.parse());
99                  }
100             }
101         }
102 
103         @Override
104         public FileVisitResult preVisitDirectory(final Path dir, final BasicFileAttributes attrs) throws IOException {
105             find(dir);
106             return FileVisitResult.CONTINUE;
107         }
108 
109         @Override
110         public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException {
111             find(file);
112             return FileVisitResult.CONTINUE;
113         }
114 
115         @Override
116         public FileVisitResult visitFileFailed(final Path file, final IOException e) {
117             System.err.println(e);
118             return FileVisitResult.CONTINUE;
119         }
120     }
121 
122     private static final char[] hexArray = "0123456789ABCDEF".toCharArray();
123 
124     private static String bytesToHex(final byte[] bytes) {
125         final char[] hexChars = new char[bytes.length * 3];
126         int i = 0;
127         for (final byte b : bytes) {
128             final int v = b & 0xFF;
129             hexChars[i++] = hexArray[v >>> 4];
130             hexChars[i++] = hexArray[v & 0x0F];
131             hexChars[i++] = ' ';
132         }
133         return new String(hexChars);
134     }
135 
136     static Stream<Path> testJdkModules() {
137         // JUnit requires at least one parameter.
138         // Make sure we have at least one JMOD file, since Java 25 and up may not have them present by default, depending on your installation.
139         return Stream.concat(JavaHome.streamModulePath(), Stream.of(Paths.get("src/test/resources/jpms/empty/empty.jmod")));
140     }
141 
142     private void compare(final String name, final Method method) {
143         // System.out.println("Method: " + m);
144         final Code code = method.getCode();
145         if (code == null) {
146             return; // for example abstract method
147         }
148         final byte[] src = code.getCode();
149         final InstructionList instructionList = new InstructionList(src);
150         final byte[] out = instructionList.getByteCode();
151         if (src.length == out.length) {
152             assertArrayEquals(src, out, () -> name + ": " + method.toString());
153         } else {
154             System.out.println(name + ": " + method.toString() + " " + src.length + " " + out.length);
155             System.out.println(bytesToHex(src));
156             System.out.println(bytesToHex(out));
157             for (final InstructionHandle instructionHandle : instructionList) {
158                 System.out.println(instructionHandle.toString(false));
159             }
160             fail("Array comparison failure");
161         }
162     }
163 
164     private void testJar(final Path file) throws Exception {
165         if (PRINT_JAR_NAME) {
166             System.out.println(" - " + file);
167         }
168         try (JarFile jar = new JarFile(file.toFile())) {
169             final Enumeration<JarEntry> en = jar.entries();
170             while (en.hasMoreElements()) {
171                 final JarEntry jarEntry = en.nextElement();
172                 final String name = jarEntry.getName();
173                 if (name.endsWith(JavaClass.EXTENSION)) {
174                     if (PRINT_CLASS_NAME) {
175                         System.out.println("  - " + name);
176                     }
177                     try (InputStream inputStream = jar.getInputStream(jarEntry)) {
178                         final ClassParser classParser = new ClassParser(inputStream, name);
179                         final JavaClass javaClass = classParser.parse();
180                         for (final Method method : javaClass.getMethods()) {
181                             compare(name, method);
182                         }
183                     }
184                 }
185             }
186         }
187     }
188 
189     @ParameterizedTest
190     @MethodSource("org.apache.bcel.generic.JavaHome#streamJarPath")
191     void testJdkJars(final Path jarPath) throws Exception {
192         testJar(jarPath);
193     }
194 
195     @ParameterizedTest
196     @DisabledOnJre(value = JRE.JAVA_8)
197     @MethodSource
198     void testJdkModules(final Path jmodPath) throws Exception {
199         testJar(jmodPath);
200     }
201 
202     @ParameterizedTest
203     @MethodSource("org.apache.bcel.generic.JavaHome#streamJavaHome")
204     void testJreModules(final JavaHome javaHome) throws Exception {
205         assumeTrue(SystemUtils.isJavaVersionAtLeast(JavaVersion.JAVA_9));
206         try (ModularRuntimeImage mri = javaHome.getModularRuntimeImage()) {
207             for (final Path path : mri.modules()) {
208                 Files.walkFileTree(path, new ClassParserFilesVisitor("*.class"));
209             }
210         }
211     }
212 
213 }