1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package org.apache.bcel.classfile;
21
22 import static org.junit.jupiter.api.Assertions.assertThrows;
23 import static org.junit.jupiter.api.Assertions.assertTrue;
24
25 import java.io.ByteArrayInputStream;
26 import java.io.ByteArrayOutputStream;
27 import java.io.DataInput;
28 import java.io.DataInputStream;
29 import java.io.DataOutputStream;
30 import java.io.IOException;
31
32 import org.junit.jupiter.params.ParameterizedTest;
33 import org.junit.jupiter.params.provider.ValueSource;
34
35
36
37
38
39 class AttributeNestingTest {
40
41
42
43
44 private static byte[] nestedCodeAttribute(final int depth, final boolean compactCodeHeader) throws IOException {
45 byte[] inner = {};
46 int attributeCount = 0;
47 for (int i = 0; i < depth; i++) {
48 final ByteArrayOutputStream baos = new ByteArrayOutputStream();
49 try (DataOutputStream dos = new DataOutputStream(baos)) {
50 dos.writeShort(1);
51 dos.writeInt((compactCodeHeader ? 8 : 12) + inner.length);
52 if (compactCodeHeader) {
53 dos.writeByte(0);
54 dos.writeByte(0);
55 dos.writeShort(0);
56 } else {
57 dos.writeShort(0);
58 dos.writeShort(0);
59 dos.writeInt(0);
60 }
61 dos.writeShort(0);
62 dos.writeShort(attributeCount);
63 dos.write(inner);
64 }
65 inner = baos.toByteArray();
66 attributeCount = 1;
67 }
68 return inner;
69 }
70
71 @ParameterizedTest
72 @ValueSource(booleans = {false, true})
73 void testDeeplyNestedCodeAttributeRejected(final boolean compactCodeHeader) throws IOException {
74 final ConstantPool cp = new ConstantPool(new ConstantUtf8("unused index 0"), new ConstantUtf8("Code"));
75 final byte[] bytes = nestedCodeAttribute(1_000, compactCodeHeader);
76 try (DataInputStream in = new DataInputStream(new ByteArrayInputStream(bytes))) {
77 assertThrows(ClassFormatException.class, () -> Attribute.readAttribute(in, cp, compactCodeHeader));
78 }
79 }
80
81 @ParameterizedTest
82 @ValueSource(booleans = {false, true})
83 void testModeratelyNestedCodeAttributeAccepted(final boolean compactCodeHeader) throws IOException {
84 final ConstantPool cp = new ConstantPool(new ConstantUtf8("unused index 0"), new ConstantUtf8("Code"));
85 final byte[] bytes = nestedCodeAttribute(3, compactCodeHeader);
86 try (DataInputStream in = new DataInputStream(new ByteArrayInputStream(bytes))) {
87 assertTrue(Attribute.readAttribute(in, cp, compactCodeHeader) instanceof Code);
88 }
89 }
90 }