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.assertArrayEquals;
23  import static org.junit.jupiter.api.Assertions.assertEquals;
24  import static org.junit.jupiter.api.Assertions.assertFalse;
25  import static org.junit.jupiter.api.Assertions.assertNotNull;
26  import static org.junit.jupiter.api.Assertions.assertThrows;
27  import static org.junit.jupiter.api.Assertions.assertTrue;
28  
29  import java.io.ByteArrayInputStream;
30  import java.io.ByteArrayOutputStream;
31  import java.io.DataInputStream;
32  import java.io.DataOutputStream;
33  import java.io.EOFException;
34  import java.io.IOException;
35  import java.nio.file.Files;
36  import java.nio.file.Paths;
37  import java.util.Arrays;
38  
39  import org.apache.bcel.Const;
40  import org.apache.bcel.Java1OakExampleCreator;
41  import org.apache.bcel.generic.ClassGen;
42  import org.apache.bcel.generic.ConstantPoolGen;
43  import org.apache.bcel.generic.FieldGen;
44  import org.apache.bcel.generic.MethodGen;
45  import org.apache.bcel.generic.Type;
46  import org.junit.jupiter.api.Test;
47  import org.junit.jupiter.api.condition.EnabledOnJre;
48  import org.junit.jupiter.api.condition.JRE;
49  import org.junit.jupiter.params.ParameterizedTest;
50  import org.junit.jupiter.params.provider.CsvSource;
51  import org.junit.jupiter.params.provider.ValueSource;
52  
53  /**
54   * Tests compact four-byte and standard eight-byte Code headers and their preservation during bytecode manipulation.
55   * The sizes cover max_stack, max_locals, and code_length only; the rest of the Code attribute layout is unchanged.
56   */
57  class CompactCodeHeaderTest {
58  
59      private static final class TestLoader extends ClassLoader {
60          Class<?> define(final byte[] bytes) {
61              return defineClass(null, bytes, 0, bytes.length);
62          }
63      }
64  
65      private static JavaClass compactHeaderClass() throws IOException {
66          return parse(fixture(), true);
67      }
68  
69      private static byte[] dump(final Code code) throws IOException {
70          final ByteArrayOutputStream bytes = new ByteArrayOutputStream();
71          try (DataOutputStream out = new DataOutputStream(bytes)) {
72              code.dump(out);
73          }
74          assertEquals(code.getLength() + 6, bytes.size());
75          return bytes.toByteArray();
76      }
77  
78      private static byte[] fixture() throws IOException {
79          return Files.readAllBytes(Paths.get("src/test/resources/Java1OakExample.class"));
80      }
81  
82      private static Code mainCode(final JavaClass clazz) {
83          return Arrays.stream(clazz.getMethods()).filter(method -> "main".equals(method.getName())).findFirst().get().getCode();
84      }
85  
86      private static JavaClass parse(final byte[] bytes, final boolean compactCodeHeader) throws IOException {
87          final ClassParser parser = new ClassParser(new ByteArrayInputStream(bytes), "Java1OakExample.class");
88          assertFalse(parser.isCompactCodeHeaderEnabled());
89          parser.setCompactCodeHeaderEnabled(compactCodeHeader);
90          assertEquals(compactCodeHeader, parser.isCompactCodeHeaderEnabled());
91          return parser.parse();
92      }
93  
94      private static Code readCode(final byte[] bytes, final ConstantPool cp, final boolean compactCodeHeader) throws IOException {
95          try (DataInputStream in = new DataInputStream(new ByteArrayInputStream(bytes))) {
96              final Code code = (Code) Attribute.readAttribute(in, cp, compactCodeHeader);
97              assertEquals(0, in.available());
98              return code;
99          }
100     }
101 
102     private static JavaClass rebuild(final JavaClass clazz) {
103         final ClassGen cg = new ClassGen(clazz);
104         for (final Method method : cg.getMethods()) {
105             final MethodGen mg = new MethodGen(method, cg.getClassName(), cg.getConstantPool());
106             assertTrue(mg.isCompactCodeHeader());
107             cg.replaceMethod(method, mg.getMethod());
108         }
109         return cg.getJavaClass();
110     }
111 
112     @Test
113     void testAddedMethodUsesEnclosingCompactCodeHeader() throws IOException {
114         final ClassGen cg = new ClassGen(compactHeaderClass());
115         final Method main = Arrays.stream(cg.getMethods()).filter(method -> "main".equals(method.getName())).findFirst().get();
116         final MethodGen mg = new MethodGen(main, cg.getClassName(), cg.getConstantPool());
117         mg.setName("anotherMethod");
118         mg.setCompactCodeHeader(false);
119         final Method added = mg.getMethod();
120         cg.addMethod(added);
121         final JavaClass parsed = parse(cg.getJavaClass().getBytes(), true);
122         assertEquals(3, parsed.getMethods().length);
123         for (final Method method : parsed.getMethods()) {
124             assertTrue(method.getCode().isCompactCodeHeader());
125         }
126         assertFalse(added.getCode().isCompactCodeHeader(), "Dump must not modify shared method attributes");
127         added.getCode().setMaxLocals(256);
128         assertThrows(ClassFormatException.class, () -> cg.getJavaClass().getBytes());
129     }
130 
131     @Test
132     void testAttributeLayoutSelection() throws IOException {
133         final Code code = mainCode(compactHeaderClass());
134         assertArrayEquals(dump(code), dump(readCode(dump(code), code.getConstantPool(), true)));
135         code.setCompactCodeHeader(false);
136         try (DataInputStream in = new DataInputStream(new ByteArrayInputStream(dump(code)))) {
137             final Code parsed = (Code) Attribute.readAttribute(in, code.getConstantPool());
138             assertFalse(parsed.isCompactCodeHeader());
139             assertEquals(0, in.available());
140             assertArrayEquals(code.getCode(), parsed.getCode());
141         }
142     }
143 
144     @ParameterizedTest
145     @ValueSource(ints = {0, 65535})
146     void testCodeLengthLimits(final int length) throws IOException {
147         final Code code = mainCode(compactHeaderClass());
148         code.setCode(new byte[length]);
149         assertEquals(length, readCode(dump(code), code.getConstantPool(), true).getCode().length);
150         code.setCode(new byte[65536]);
151         assertThrows(ClassFormatException.class, () -> dump(code));
152     }
153 
154     @ParameterizedTest
155     @ValueSource(ints = {-1, 256})
156     void testCompactCodeHeaderBounds(final int invalid) throws IOException {
157         final Code code = mainCode(compactHeaderClass());
158         code.setMaxStack(255);
159         code.setMaxLocals(255);
160         final Code parsed = readCode(dump(code), code.getConstantPool(), true);
161         assertEquals(255, parsed.getMaxStack());
162         assertEquals(255, parsed.getMaxLocals());
163         code.setMaxStack(invalid);
164         assertThrows(ClassFormatException.class, () -> dump(code));
165         code.setMaxStack(255);
166         code.setMaxLocals(invalid);
167         assertThrows(ClassFormatException.class, () -> dump(code));
168     }
169 
170     @Test
171     void testCompactCodeHeaderValidatesBeforeChangingMode() throws IOException {
172         final Code code = mainCode(compactHeaderClass());
173         code.setCompactCodeHeader(false);
174         code.setMaxStack(256);
175         code.setMaxLocals(256);
176         assertEquals(256, readCode(dump(code), code.getConstantPool(), false).getMaxStack());
177         final int length = code.getLength();
178         assertThrows(ClassFormatException.class, () -> code.setCompactCodeHeader(true));
179         assertFalse(code.isCompactCodeHeader());
180         assertEquals(length, code.getLength());
181     }
182 
183     @ParameterizedTest
184     @ValueSource(ints = {0, 1, 2})
185     void testCompactCodeHeaderVersionsRoundTrip(final int minor) throws IOException {
186         final byte[] bytes = fixture();
187         bytes[5] = (byte) minor;
188         final JavaClass clazz = parse(bytes, true);
189         assertEquals(minor, clazz.getMinor());
190         assertArrayEquals(bytes, clazz.getBytes());
191         assertTrue(mainCode(clazz).isCompactCodeHeader());
192     }
193 
194     @Test
195     void testCopiesPreserveLayout() throws IOException {
196         final JavaClass original = compactHeaderClass();
197         assertArrayEquals(fixture(), original.copy().getBytes());
198         final Code code = mainCode(original);
199         final Code shallow = new Code(code);
200         final Code deep = (Code) code.copy(code.getConstantPool());
201         assertTrue(shallow.isCompactCodeHeader());
202         assertTrue(deep.isCompactCodeHeader());
203         assertArrayEquals(dump(code), dump(shallow));
204         assertArrayEquals(dump(code), dump(deep));
205         shallow.setCompactCodeHeader(false);
206         assertTrue(code.isCompactCodeHeader());
207     }
208 
209     @Test
210     void testFixtureValuesAndReproducibility() throws IOException {
211         assertArrayEquals(Java1OakExampleCreator.create().getBytes(), fixture());
212         final JavaClass clazz = compactHeaderClass();
213         assertEquals("Java1OakExample", clazz.getClassName());
214         assertEquals(45, clazz.getMajor());
215         assertEquals(2, clazz.getMinor());
216         assertEquals(2, clazz.getMethods().length);
217         final Code main = mainCode(clazz);
218         assertEquals(2, main.getMaxStack());
219         assertEquals(1, main.getMaxLocals());
220         assertEquals(9, main.getCode().length);
221         assertNotNull(main.getLocalVariableTable());
222         assertEquals(0, main.getExceptionTable().length);
223     }
224 
225     @Test
226     void testLengthRecalculation() throws IOException {
227         final Code code = mainCode(compactHeaderClass());
228         code.setAttributes(Attribute.EMPTY_ARRAY);
229         code.setExceptionTable(new CodeException[] {new CodeException(0, 1, 0, 0)});
230         code.setCode(new byte[] {(byte) Const.RETURN});
231         assertEquals(17, code.getLength());
232         final Code parsed = readCode(dump(code), code.getConstantPool(), true);
233         assertEquals(1, parsed.getExceptionTable().length);
234         assertEquals(1, parsed.getCode().length);
235         code.setCompactCodeHeader(false);
236         assertEquals(21, code.getLength());
237         assertEquals(1, readCode(dump(code), code.getConstantPool(), false).getExceptionTable().length);
238         code.setCompactCodeHeader(true);
239         assertEquals(17, code.getLength());
240     }
241 
242     @Test
243     void testLocalVariableGrowthFailureDoesNotLeaveAttributes() throws IOException {
244         final JavaClass clazz = compactHeaderClass();
245         final Method main = Arrays.stream(clazz.getMethods()).filter(method -> "main".equals(method.getName())).findFirst().get();
246         final MethodGen mg = new MethodGen(main, clazz.getClassName(), new ConstantPoolGen(clazz.getConstantPool()));
247         mg.addLocalVariable("extra", Type.INT, 255, mg.getInstructionList().getStart(), mg.getInstructionList().getEnd());
248         // Rebuilding the local variable table restores the required count of 256 during getMethod().
249         mg.setMaxLocals(1);
250         assertThrows(ClassFormatException.class, mg::getMethod);
251         assertEquals(0, mg.getCodeAttributes().length, "Failed generation must not leave temporary attributes");
252         mg.setCompactCodeHeader(false);
253         final Code code = mg.getMethod().getCode();
254         assertEquals(256, code.getMaxLocals());
255         assertEquals(1, Arrays.stream(code.getAttributes()).filter(LocalVariableTable.class::isInstance).count());
256     }
257 
258     @Test
259     void testMethodGenPreservesLayout() throws IOException {
260         final JavaClass clazz = compactHeaderClass();
261         final JavaClass rebuilt = parse(rebuild(clazz).getBytes(), true);
262         assertTrue(mainCode(rebuilt).isCompactCodeHeader());
263         assertArrayEquals(mainCode(clazz).getCode(), mainCode(rebuilt).getCode());
264         final MethodGen mg = new MethodGen(clazz.getMethods()[0], clazz.getClassName(), new ConstantPoolGen(clazz.getConstantPool()));
265         assertTrue(mg.copy(clazz.getClassName(), new ConstantPoolGen(clazz.getConstantPool())).getMethod().getCode().isCompactCodeHeader());
266         mg.setMaxStack(256);
267         assertThrows(ClassFormatException.class, mg::getMethod);
268         mg.setCompactCodeHeader(false);
269         assertFalse(mg.getMethod().getCode().isCompactCodeHeader());
270     }
271 
272     @Test
273     void testNonCodeAttributesWithCompactCodeHeaders() throws IOException {
274         final ClassGen cg = new ClassGen(compactHeaderClass());
275         final FieldGen fg = new FieldGen(Const.ACC_PUBLIC | Const.ACC_STATIC | Const.ACC_FINAL, Type.INT, "VALUE", cg.getConstantPool());
276         fg.setInitValue(42);
277         cg.addField(fg.getField());
278         final JavaClass parsed = parse(cg.getJavaClass().getBytes(), true);
279         assertEquals("42", parsed.getFields()[0].getConstantValue().toString());
280         assertEquals("Java1OakExample.java", parsed.getSourceFileName());
281     }
282 
283     @ParameterizedTest
284     @ValueSource(ints = {0, 1, 2, 3})
285     void testStandardCodeHeaderRemainsDefault(final int minor) throws IOException {
286         final JavaClass clazz = compactHeaderClass();
287         for (final Method method : clazz.getMethods()) {
288             method.getCode().setCompactCodeHeader(false);
289         }
290         clazz.setMinor(minor);
291         final byte[] bytes = clazz.getBytes();
292         final JavaClass parsed = parse(bytes, false);
293         assertFalse(mainCode(parsed).isCompactCodeHeader());
294         assertEquals(1, mainCode(parsed).getMaxLocals());
295         assertArrayEquals(bytes, parsed.getBytes());
296     }
297 
298     @Test
299     void testTruncatedCompactCodeAttribute() throws IOException {
300         final Code code = mainCode(compactHeaderClass());
301         final byte[] bytes = dump(code);
302         assertThrows(EOFException.class, () -> readCode(Arrays.copyOf(bytes, bytes.length - 1), code.getConstantPool(), true));
303     }
304 
305     @Test
306     @EnabledOnJre(JRE.JAVA_8)
307     void testValidCompactCodeHeaderFixtureAndRegeneratedMethodsLoadInJava8() throws Exception {
308         assertNotNull(new TestLoader().define(fixture()).getDeclaredMethod("main", String[].class));
309         assertNotNull(new TestLoader().define(rebuild(compactHeaderClass()).getBytes()).getDeclaredMethod("main", String[].class));
310     }
311 
312     @ParameterizedTest
313     @CsvSource({"45, 3", "46, 0"})
314     void testVersionChangesSelectStandardCodeHeaders(final int major, final int minor) throws Exception {
315         final JavaClass clazz = compactHeaderClass();
316         clazz.setMajor(major);
317         clazz.setMinor(minor);
318         final byte[] bytes = clazz.getBytes();
319         assertFalse(mainCode(parse(bytes, false)).isCompactCodeHeader());
320         assertFalse(mainCode(parse(bytes, true)).isCompactCodeHeader(), "Compact Code header parsing must only apply to versions 45.0 through 45.2");
321         assertTrue(mainCode(clazz).isCompactCodeHeader(), "Dump must not mutate the original attributes");
322         assertNotNull(new TestLoader().define(bytes).getDeclaredMethod("main", String[].class));
323         final ClassGen cg = new ClassGen(compactHeaderClass());
324         cg.setMajor(major);
325         cg.setMinor(minor);
326         assertFalse(mainCode(parse(cg.getJavaClass().getBytes(), false)).isCompactCodeHeader());
327     }
328 }