1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package org.apache.bcel.generic;
21
22 import static org.junit.jupiter.api.Assertions.assertEquals;
23 import static org.junit.jupiter.api.Assertions.assertThrows;
24
25 import java.io.ByteArrayOutputStream;
26 import java.io.DataOutputStream;
27 import java.io.IOException;
28
29 import org.apache.bcel.Const;
30 import org.apache.bcel.classfile.ClassFormatException;
31 import org.junit.jupiter.api.Test;
32
33
34
35
36
37 class SwitchAllocationTest {
38
39 private static byte[] switchBytes(final short opcode, final int... operands) throws IOException {
40 final ByteArrayOutputStream baos = new ByteArrayOutputStream();
41 try (DataOutputStream dos = new DataOutputStream(baos)) {
42 dos.writeByte(opcode);
43 for (int i = 0; i < 3; i++) {
44 dos.writeByte(0);
45 }
46 for (final int operand : operands) {
47 dos.writeInt(operand);
48 }
49 }
50 return baos.toByteArray();
51 }
52
53 @Test
54 void testLookupswitchHugeNpairsRejected() throws IOException {
55
56 final byte[] code = switchBytes(Const.LOOKUPSWITCH, 0, Integer.MAX_VALUE);
57 assertThrows(ClassFormatException.class, () -> new InstructionList(code));
58 }
59
60 @Test
61 void testLookupswitchNegativeNpairsRejected() throws IOException {
62 final byte[] code = switchBytes(Const.LOOKUPSWITCH, 0, -1);
63 assertThrows(ClassFormatException.class, () -> new InstructionList(code));
64 }
65
66 @Test
67 void testLookupswitchValidAccepted() throws IOException {
68
69 final byte[] code = switchBytes(Const.LOOKUPSWITCH, 0, 1, 5, 0);
70 assertEquals(1, new InstructionList(code).getLength());
71 }
72
73 @Test
74 void testTableswitchHugeRangeRejected() throws IOException {
75
76 final byte[] code = switchBytes(Const.TABLESWITCH, 0, 0, Integer.MAX_VALUE - 1);
77 assertThrows(ClassFormatException.class, () -> new InstructionList(code));
78 }
79
80 @Test
81 void testTableswitchOverflowingRangeRejected() throws IOException {
82
83 final byte[] code = switchBytes(Const.TABLESWITCH, 0, Integer.MIN_VALUE, Integer.MAX_VALUE);
84 assertThrows(ClassFormatException.class, () -> new InstructionList(code));
85 }
86
87 @Test
88 void testTableswitchValidAccepted() throws IOException {
89
90 final byte[] code = switchBytes(Const.TABLESWITCH, 0, 0, 1, 0, 0);
91 assertEquals(1, new InstructionList(code).getLength());
92 }
93 }