View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements.  See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache License, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License.  You may obtain a copy of the License at
8    *
9    *      http://www.apache.org/licenses/LICENSE-2.0
10   *
11   *  Unless required by applicable law or agreed to in writing, software
12   *  distributed under the License is distributed on an "AS IS" BASIS,
13   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   *  See the License for the specific language governing permissions and
15   *  limitations under the License.
16   */
17  package org.apache.bcel.util;
18  
19  import static org.junit.jupiter.api.Assertions.assertEquals;
20  import static org.junit.jupiter.api.Assertions.assertNotNull;
21  import static org.junit.jupiter.api.Assertions.assertTrue;
22  
23  import java.io.BufferedInputStream;
24  import java.io.ByteArrayOutputStream;
25  import java.io.File;
26  import java.io.OutputStream;
27  import java.io.PrintStream;
28  import java.nio.charset.StandardCharsets;
29  import java.nio.file.Files;
30  import java.util.regex.Matcher;
31  import java.util.regex.Pattern;
32  
33  import org.apache.bcel.AbstractTestCase;
34  import org.apache.bcel.HelloWorldCreator;
35  import org.apache.bcel.classfile.JavaClass;
36  import org.apache.bcel.classfile.Utility;
37  import org.apache.bcel.generic.BinaryOpCreator;
38  import org.apache.commons.lang3.SystemProperties;
39  import org.junit.jupiter.api.Test;
40  import org.junit.jupiter.params.ParameterizedTest;
41  import org.junit.jupiter.params.provider.ValueSource;
42  
43  public class BCELifierTestCase extends AbstractTestCase {
44  
45      private static final String EOL = System.lineSeparator();
46      public static final String CLASSPATH = "." + File.pathSeparator + SystemProperties.getJavaClassPath();
47  
48      // Canonicalise the javap output so it compares better
49      private String canonHashRef(String input) {
50          input = input.replaceAll("#\\d+", "#n"); // numbers may vary in length
51          input = input.replaceAll(" +", " "); // collapse spaces
52          return input.replaceAll("//.+", "");
53      }
54  
55      private String exec(final File workDir, final String... args) throws Exception {
56          // System.err.println(java.util.Arrays.toString(args));
57          final ProcessBuilder pb = new ProcessBuilder(args);
58          pb.directory(workDir);
59          pb.redirectErrorStream(true);
60          final Process proc = pb.start();
61          try (BufferedInputStream is = new BufferedInputStream(proc.getInputStream())) {
62              final byte[] buff = new byte[2048];
63              int len;
64  
65              final StringBuilder sb = new StringBuilder();
66              while ((len = is.read(buff)) != -1) {
67                  sb.append(new String(buff, 0, len));
68              }
69              final String output = sb.toString();
70              assertEquals(0, proc.waitFor(), output);
71              return output;
72          }
73      }
74  
75      @ParameterizedTest
76      @ValueSource(strings = {
77      // @formatter:off
78          "iadd 3 2 = 5",
79          "isub 3 2 = 1",
80          "imul 3 2 = 6",
81          "idiv 3 2 = 1",
82          "irem 3 2 = 1",
83          "iand 3 2 = 2",
84          "ior 3 2 = 3",
85          "ixor 3 2 = 1",
86          "ishl 4 1 = 8",
87          "ishr 4 1 = 2",
88          "iushr 4 1 = 2",
89          "ladd 3 2 = 5",
90          "lsub 3 2 = 1",
91          "lmul 3 2 = 6",
92          "ldiv 3 2 = 1",
93          "lrem 3 2 = 1",
94          "land 3 2 = 2",
95          "lor 3 2 = 3",
96          "lxor 3 2 = 1",
97          "lshl 4 1 = 8",
98          "lshr 4 1 = 2",
99          "lushr 4 1 = 2",
100         "fadd 3 2 = 5.0",
101         "fsub 3 2 = 1.0",
102         "fmul 3 2 = 6.0",
103         "fdiv 3 2 = 1.5",
104         "frem 3 2 = 1.0",
105         "dadd 3 2 = 5.0",
106         "dsub 3 2 = 1.0",
107         "dmul 3 2 = 6.0",
108         "ddiv 3 2 = 1.5",
109         "drem 3 2 = 1.0"
110     // @formatter:on
111     })
112     public void testBinaryOp(final String exp) throws Exception {
113         BinaryOpCreator.main(new String[] {});
114         final File workDir = new File("target");
115         final Pattern pattern = Pattern.compile("([a-z]{3,5}) ([-+]?\\d*\\.?\\d+) ([-+]?\\d*\\.?\\d+) = ([-+]?\\d*\\.?\\d+)");
116         final Matcher matcher = pattern.matcher(exp);
117         assertTrue(matcher.matches());
118         final String op = matcher.group(1);
119         final String a = matcher.group(2);
120         final String b = matcher.group(3);
121         final String expected = matcher.group(4);
122         final String javaAgent = getJavaAgent();
123         if (javaAgent == null) {
124             assertEquals(expected + EOL, exec(workDir, "java", "-cp", CLASSPATH, "org.apache.bcel.generic.BinaryOp", op, a, b));
125         } else {
126             final String runtimeExecJavaAgent = javaAgent.replace("jacoco.exec", "jacoco_org.apache.bcel.generic.BinaryOp.exec");
127             assertEquals(expected + EOL, exec(workDir, "java", runtimeExecJavaAgent, "-cp", CLASSPATH, "org.apache.bcel.generic.BinaryOp", op, a, b));
128         }
129     }
130 
131     private void testClassOnPath(final String javaClassFileName) throws Exception {
132         final File workDir = new File("target");
133         final File infile = new File(javaClassFileName);
134         final JavaClass javaClass = BCELifier.getJavaClass(infile.getName().replace(JavaClass.EXTENSION, ""));
135         assertNotNull(javaClass);
136 
137         // Get javap of the input class
138         final String initial = exec(null, "javap", "-cp", CLASSPATH, "-p", "-c", javaClass.getClassName());
139         final String outFileName = javaClass.getSourceFilePath().replace(".java", "Creator.java");
140         final File outfile = new File(workDir, outFileName);
141         Files.createDirectories(outfile.getParentFile().toPath());
142         final String javaAgent = getJavaAgent();
143         String creatorSourceContents = null;
144         if (javaAgent == null) {
145             creatorSourceContents = exec(workDir, "java", "-cp", CLASSPATH, "org.apache.bcel.util.BCELifier", javaClass.getClassName());
146         } else {
147             final String runtimeExecJavaAgent = javaAgent.replace("jacoco.exec", "jacoco_" + infile.getName() + ".exec");
148             creatorSourceContents = exec(workDir, "java", runtimeExecJavaAgent, "-cp", CLASSPATH, "org.apache.bcel.util.BCELifier", javaClass.getClassName());
149         }
150         Files.write(outfile.toPath(), creatorSourceContents.getBytes(StandardCharsets.UTF_8));
151         assertEquals("", exec(workDir, "javac", "-cp", CLASSPATH, outFileName.toString()));
152         if (javaAgent == null) {
153             assertEquals("", exec(workDir, "java", "-cp", CLASSPATH, javaClass.getClassName() + "Creator"));
154         } else {
155             final String runtimeExecJavaAgent = javaAgent.replace("jacoco.exec", "jacoco_" + Utility.pathToPackage(outFileName) + ".exec");
156             assertEquals("", exec(workDir, "java", runtimeExecJavaAgent, "-cp", CLASSPATH, javaClass.getClassName() + "Creator"));
157         }
158         final String output = exec(workDir, "javap", "-p", "-c", infile.getName());
159         assertEquals(canonHashRef(initial), canonHashRef(output));
160     }
161 
162     @Test
163     public void testHelloWorld() throws Exception {
164         HelloWorldCreator.main(new String[] {});
165         final File workDir = new File("target");
166         final String javaAgent = getJavaAgent();
167         if (javaAgent == null) {
168             assertEquals("Hello World!" + EOL, exec(workDir, "java", "-cp", CLASSPATH, "org.apache.bcel.HelloWorld"));
169         } else {
170             final String runtimeExecJavaAgent = javaAgent.replace("jacoco.exec", "jacoco_org.apache.bcel.HelloWorld.exec");
171             assertEquals("Hello World!" + EOL, exec(workDir, "java", runtimeExecJavaAgent, "-cp", CLASSPATH, "org.apache.bcel.HelloWorld"));
172         }
173     }
174 
175     /*
176      * Dumps a class using "javap" and compare with the same class recreated using BCELifier, "javac", "java" and dumped with "javap".
177      *
178      * TODO: detect if JDK present and skip test if not
179      */
180     @ParameterizedTest
181     @ValueSource(strings = {
182     // @formatter:off
183         "org.apache.commons.lang.math.Fraction.class",
184         "org.apache.commons.lang.exception.NestableDelegate.class",
185         "org.apache.commons.lang.builder.CompareToBuilder.class",
186         "org.apache.commons.lang.builder.ToStringBuilder.class",
187         "org.apache.commons.lang.SerializationUtils.class",
188         "org.apache.commons.lang.ArrayUtils.class",
189         "target/test-classes/Java8Example.class",
190         "target/test-classes/Java8Example2.class",
191         "target/test-classes/Java4Example.class"
192     // @formatter:on
193     })
194     public void testJavapCompare(final String pathToClass) throws Exception {
195         testClassOnPath(pathToClass);
196     }
197 
198     @Test
199     public void testMainNoArg() throws Exception {
200         final PrintStream sysout = System.out;
201         try {
202             final ByteArrayOutputStream out = new ByteArrayOutputStream();
203             System.setOut(new PrintStream(out));
204             BCELifier.main(new String[0]);
205             final String outputNoArgs = new String(out.toByteArray());
206             assertEquals("Usage: BCELifier className" + EOL + "\tThe class must exist on the classpath" + EOL, outputNoArgs);
207         } finally {
208             System.setOut(sysout);
209         }
210     }
211 
212     @ParameterizedTest
213     @ValueSource(strings = { "StackMapExample", "StackMapExample2" })
214     public void testStackMap(final String className) throws Exception {
215         testJavapCompare(className);
216         final File workDir = new File("target");
217         assertEquals("Hello World" + EOL, exec(workDir, "java", "-cp", CLASSPATH, className, "Hello"));
218     }
219 
220     @Test
221     public void testStart() throws Exception {
222         final OutputStream os = new ByteArrayOutputStream();
223         final JavaClass javaClass = BCELifier.getJavaClass("Java8Example");
224         assertNotNull(javaClass);
225         final BCELifier bcelifier = new BCELifier(javaClass, os);
226         bcelifier.start();
227     }
228 }