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.generic;
21
22 import static org.junit.jupiter.api.Assertions.assertEquals;
23 import static org.junit.jupiter.api.Assertions.assertThrows;
24
25 import org.apache.bcel.Const;
26 import org.junit.jupiter.api.Test;
27
28 /**
29 * A constant pool or local variable index is encoded as a u2, so {@code setIndex} must reject a value above
30 * {@link Const#MAX_SHORT}; otherwise {@code dump} truncates it with {@code writeShort} and the emitted instruction
31 * references a different slot than requested. {@code LocalVariableInstruction.setIndex} already enforces this; these
32 * cover the siblings that did not.
33 */
34 class SetIndexBoundsTest {
35
36 @Test
37 void testCpInstructionRejectsIndexAboveU2() {
38 assertEquals(Const.MAX_SHORT, new LDC_W(Const.MAX_SHORT).getIndex());
39 assertThrows(ClassGenException.class, () -> new LDC_W(Const.MAX_SHORT + 1));
40 }
41
42 @Test
43 void testIincRejectsIndexAboveU2() {
44 assertEquals(Const.MAX_SHORT, new IINC(Const.MAX_SHORT, 1).getIndex());
45 assertThrows(ClassGenException.class, () -> new IINC(Const.MAX_SHORT + 1, 1));
46 }
47
48 @Test
49 void testRetRejectsIndexAboveU2() {
50 assertEquals(Const.MAX_SHORT, new RET(Const.MAX_SHORT).getIndex());
51 assertThrows(ClassGenException.class, () -> new RET(Const.MAX_SHORT + 1));
52 }
53 }