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.classfile;
21  
22  import static org.junit.jupiter.api.Assertions.assertNotNull;
23  import static org.junit.jupiter.api.Assertions.assertNull;
24  import static org.junit.jupiter.api.Assertions.assertThrows;
25  
26  import java.io.ByteArrayInputStream;
27  import java.io.ByteArrayOutputStream;
28  import java.io.IOException;
29  import java.nio.file.Files;
30  import java.nio.file.Path;
31  import java.nio.file.Paths;
32  
33  import org.apache.bcel.Const;
34  import org.apache.bcel.Repository;
35  import org.apache.bcel.generic.ClassGen;
36  import org.apache.bcel.generic.InstructionFactory;
37  import org.apache.bcel.generic.InstructionList;
38  import org.apache.bcel.generic.MethodGen;
39  import org.apache.bcel.generic.Type;
40  import org.apache.bcel.util.ClassPath;
41  import org.apache.bcel.util.SyntheticRepository;
42  import org.apache.commons.lang3.SystemProperties;
43  import org.junit.jupiter.api.BeforeAll;
44  import org.junit.jupiter.api.Test;
45  import org.junit.jupiter.api.io.TempDir;
46  import org.junit.jupiter.params.ParameterizedTest;
47  import org.junit.jupiter.params.provider.MethodSource;
48  
49  /**
50   * Tests {@link JavaClass}.
51   */
52  class JavaClassTest {
53  
54      private static final String INTERFACE_NAME_A = "InterfaceA";
55  
56      private static final String INTERFACE_NAME_B = "InterfaceB";
57  
58      private static final String CLASS_NAME = "TargetClass";
59  // Doesn't compile due to cyclic inheritance
60  //  private interface InterfaceA extends InterfaceB {
61  //  }
62  //
63  //  private interface InterfaceB extends InterfaceA {
64  //  }
65  
66      @TempDir
67      static Path tempDir;
68  
69      static Path tempClassFile;
70  
71      static Path tempIntefaceAFile;
72  
73      static Path tempIntefaceBFile;
74  
75      @BeforeAll
76      static void beforeAll() throws Exception {
77          // Create InterfaceA that extends InterfaceB (will create cycle)
78          tempIntefaceAFile = writeInterfaceA();
79          // Create InterfaceB that extends InterfaceA (completes the cycle)
80          tempIntefaceBFile = writeInterfaceB();
81          // Create a class that implements InterfaceA
82          tempClassFile = writeTargetClass();
83          // Cycle: InterfaceA -> InterfaceB -> InterfaceA -> ...
84      }
85  
86      static byte[] createClass(final String name, final String extendsClass) throws IOException {
87          return toByteArray(new ClassGen(name, extendsClass, name + ".java", Const.ACC_PUBLIC, new String[] {}));
88      }
89  
90      static byte[] createClass(final String name, final String extendsClass, final String implementsInterface) throws IOException {
91          return toByteArray(new ClassGen(name, extendsClass, name + ".java", Const.ACC_PUBLIC, new String[] { implementsInterface }));
92      }
93  
94      static byte[] createInterface(final String name, final String extendsInterface) throws IOException {
95          return toByteArray(new ClassGen(name, "java.lang.Object", name + ".java", Const.ACC_PUBLIC | Const.ACC_INTERFACE | Const.ACC_ABSTRACT,
96                  new String[] { extendsInterface }));
97      }
98  
99      static byte[] toByteArray(final ClassGen cg) throws IOException {
100         final ByteArrayOutputStream baos = new ByteArrayOutputStream();
101         cg.getJavaClass().dump(baos);
102         return baos.toByteArray();
103     }
104 
105     private static Path writeInterfaceA() throws Exception {
106         // Create InterfaceA that extends InterfaceB
107         final ClassGen classGen = new ClassGen(INTERFACE_NAME_A, "java.lang.Object", INTERFACE_NAME_A + ".java",
108                 Const.ACC_PUBLIC | Const.ACC_INTERFACE | Const.ACC_ABSTRACT, new String[] { INTERFACE_NAME_B });
109         final Path path = tempDir.resolve(INTERFACE_NAME_A + ".class");
110         classGen.getJavaClass().dump(path.toString());
111         return path;
112     }
113 
114     private static Path writeInterfaceB() throws Exception {
115         // Create InterfaceB that extends InterfaceA
116         final ClassGen classGen = new ClassGen(INTERFACE_NAME_B, "java.lang.Object", INTERFACE_NAME_B + ".java",
117                 Const.ACC_PUBLIC | Const.ACC_INTERFACE | Const.ACC_ABSTRACT, new String[] { INTERFACE_NAME_A });
118         final Path path = tempDir.resolve(INTERFACE_NAME_B + ".class");
119         classGen.getJavaClass().dump(path.toString());
120         return path;
121     }
122 
123     private static Path writeTargetClass() throws Exception {
124         // Create a class that implements InterfaceA
125         final ClassGen cg = new ClassGen(CLASS_NAME, "java.lang.Object", CLASS_NAME + ".java", Const.ACC_PUBLIC, new String[] { INTERFACE_NAME_A });
126         // Add default constructor
127         final InstructionList il = new InstructionList();
128         final MethodGen constructor = new MethodGen(Const.ACC_PUBLIC, Type.VOID, Type.NO_ARGS, new String[] {}, "<init>", CLASS_NAME, il, cg.getConstantPool());
129         final InstructionFactory factory = new InstructionFactory(cg);
130         il.append(InstructionFactory.createLoad(Type.OBJECT, 0));
131         il.append(factory.createInvoke("java.lang.Object", "<init>", Type.VOID, Type.NO_ARGS, Const.INVOKESPECIAL));
132         il.append(InstructionFactory.createReturn(Type.VOID));
133         constructor.setMaxStack();
134         constructor.setMaxLocals();
135         cg.addMethod(constructor.getMethod());
136         il.dispose();
137         // Create the class file
138         final Path path = tempDir.resolve(CLASS_NAME + ".class");
139         cg.getJavaClass().dump(path.toString());
140         return path;
141     }
142 
143     private Field findFieldDoesNotExist(final Class<?> clazz) throws ClassNotFoundException {
144         return Repository.lookupClass(clazz.getName()).findField("nonExistentField", Type.INT);
145     }
146 
147     @Test
148     void testFindFieldCustomClass() throws Exception {
149         final byte[] classABytes = createClass("CyclicClassA", "CyclicClassB");
150         final byte[] classBBytes = createInterface("CyclicClassB", "CyclicClassA");
151         final byte[] testClassBytes = createClass("CyclicTestClass", "CyclicClassA");
152         final JavaClass interfaceA = new ClassParser(new ByteArrayInputStream(classABytes), "CyclicClassA.class").parse();
153         final JavaClass interfaceB = new ClassParser(new ByteArrayInputStream(classBBytes), "CyclicClassB.class").parse();
154         final JavaClass testClass = new ClassParser(new ByteArrayInputStream(testClassBytes), "CyclicTestClass.class").parse();
155         final SyntheticRepository repo = SyntheticRepository.getInstance();
156         try {
157             repo.storeClass(interfaceA);
158             repo.storeClass(interfaceB);
159             repo.storeClass(testClass);
160             Repository.setRepository(repo);
161             assertThrows(ClassFormatException.class, () -> testClass.findField("nonExistentField", Type.INT));
162         } finally {
163             repo.removeClass(interfaceA);
164             repo.removeClass(interfaceB);
165             repo.removeClass(testClass);
166         }
167     }
168 
169     @Test
170     void testFindFieldCustomInterface1() throws IOException, ClassNotFoundException {
171         // Set up repository to load classes from the malicious_classes directory
172         final String classPath = tempDir.toString() + SystemProperties.getPathSeparator() + SystemProperties.getJavaClassPath();
173         Repository.setRepository(SyntheticRepository.getInstance(new ClassPath(classPath)));
174         assertThrows(ClassFormatException.class, () -> Repository.lookupClass(CLASS_NAME).findField("nonExistentField", Type.INT));
175         // sanity check
176         final Path targetDir = Paths.get("target/test-classes");
177         final Path targetClassFile = targetDir.resolve(CLASS_NAME + ".class");
178         final Path targetInterfaceA = targetDir.resolve(INTERFACE_NAME_A + ".class");
179         final Path targetInterfaceB = targetDir.resolve(INTERFACE_NAME_B + ".class");
180         try {
181             Files.copy(tempClassFile, targetClassFile);
182             Files.copy(tempIntefaceAFile, targetInterfaceA);
183             Files.copy(tempIntefaceBFile, targetInterfaceB);
184             assertThrows(ClassCircularityError.class, () -> Class.forName(CLASS_NAME));
185         } finally {
186             Files.delete(targetClassFile);
187             Files.delete(targetInterfaceA);
188             Files.delete(targetInterfaceB);
189         }
190     }
191 
192     @Test
193     void testFindFieldCustomInterface2() throws Exception {
194         final byte[] interfaceABytes = createInterface("CyclicInterfaceA", "CyclicInterfaceB");
195         final byte[] interfaceBBytes = createInterface("CyclicInterfaceB", "CyclicInterfaceA");
196         final byte[] testClassBytes = createClass("CyclicTestClass", "java.lang.Object", "CyclicInterfaceA");
197         final JavaClass interfaceA = new ClassParser(new ByteArrayInputStream(interfaceABytes), "CyclicInterfaceA.class").parse();
198         final JavaClass interfaceB = new ClassParser(new ByteArrayInputStream(interfaceBBytes), "CyclicInterfaceB.class").parse();
199         final JavaClass testClass = new ClassParser(new ByteArrayInputStream(testClassBytes), "CyclicTestClass.class").parse();
200         final SyntheticRepository repo = SyntheticRepository.getInstance();
201         try {
202             repo.storeClass(interfaceA);
203             repo.storeClass(interfaceB);
204             repo.storeClass(testClass);
205             Repository.setRepository(repo);
206             assertThrows(ClassFormatException.class, () -> testClass.findField("nonExistentField", Type.INT));
207         } finally {
208             repo.removeClass(interfaceA);
209             repo.removeClass(interfaceB);
210             repo.removeClass(testClass);
211         }
212     }
213 
214     @ParameterizedTest
215     @MethodSource("org.apache.bcel.Java8PublicClasses#getAll")
216     void testFindFieldJavaLang(final Class<?> clazz) throws ClassNotFoundException {
217         assertNull(findFieldDoesNotExist(clazz));
218     }
219 
220     @ParameterizedTest
221     @MethodSource("org.apache.bcel.Java8PublicClasses#getAll")
222     void testGetAllInterfaces(final Class<?> clazz) throws ClassNotFoundException {
223         assertNotNull(Repository.lookupClass(clazz.getName()).getAllInterfaces());
224     }
225 
226     @ParameterizedTest
227     @MethodSource("org.apache.bcel.Java8PublicClasses#getAll")
228     void testGetSuperClassesAll(final Class<?> clazz) throws ClassNotFoundException {
229         assertNotNull(Repository.lookupClass(clazz.getName()).getSuperClasses());
230     }
231 }