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.DataInputStream;
28 import java.io.DataOutputStream;
29 import java.io.IOException;
30
31 import org.junit.jupiter.api.Test;
32
33
34
35
36
37 class ElementValueNestingTest {
38
39
40
41
42 private static byte[] annotationOf(final byte[] inner) throws IOException {
43 final ByteArrayOutputStream baos = new ByteArrayOutputStream();
44 try (DataOutputStream dos = new DataOutputStream(baos)) {
45 dos.writeByte(ElementValue.ANNOTATION);
46 dos.writeShort(0);
47 dos.writeShort(1);
48 dos.writeShort(0);
49 dos.write(inner);
50 }
51 return baos.toByteArray();
52 }
53
54
55
56
57 private static byte[] arrayOf(final byte[] inner) throws IOException {
58 final ByteArrayOutputStream baos = new ByteArrayOutputStream();
59 try (DataOutputStream dos = new DataOutputStream(baos)) {
60 dos.writeByte(ElementValue.ARRAY);
61 dos.writeShort(1);
62 dos.write(inner);
63 }
64 return baos.toByteArray();
65 }
66
67 private static byte[] stringValue() {
68 return new byte[] {ElementValue.STRING, 0, 0};
69 }
70
71 @Test
72 void testAlternatingArrayAnnotationNestingRejected() throws IOException {
73 byte[] bytes = stringValue();
74 for (int i = 0; i < 300; i++) {
75 bytes = arrayOf(annotationOf(bytes));
76 }
77 try (DataInputStream in = new DataInputStream(new ByteArrayInputStream(bytes))) {
78 assertThrows(ClassFormatException.class, () -> ElementValue.readElementValue(in, new ConstantPool(new ConstantUtf8("Test"))));
79 }
80 }
81
82 @Test
83 void testDeeplyNestedAnnotationsRejected() throws IOException {
84 byte[] bytes = stringValue();
85 for (int i = 0; i < 300; i++) {
86 bytes = annotationOf(bytes);
87 }
88 try (DataInputStream in = new DataInputStream(new ByteArrayInputStream(bytes))) {
89 assertThrows(ClassFormatException.class, () -> ElementValue.readElementValue(in, new ConstantPool(new ConstantUtf8("Test"))));
90 }
91 }
92
93 @Test
94 void testModeratelyNestedAnnotationsAccepted() throws IOException {
95 byte[] bytes = stringValue();
96 for (int i = 0; i < 3; i++) {
97 bytes = annotationOf(arrayOf(bytes));
98 }
99 try (DataInputStream in = new DataInputStream(new ByteArrayInputStream(bytes))) {
100 assertTrue(ElementValue.readElementValue(in, new ConstantPool(new ConstantUtf8("Test"))) instanceof AnnotationElementValue);
101 }
102 }
103 }