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
24 import java.io.IOException;
25
26 import org.apache.bcel.Const;
27 import org.junit.jupiter.api.Test;
28
29 /**
30 * Tests {@link LocalVariableInstruction} parsing of the {@code wide} prefix.
31 */
32 class LocalVariableInstructionTest {
33
34 /**
35 * A {@code wide} prefix whose index does not fit in a byte must keep the four-byte encoding.
36 */
37 @Test
38 void testWideLoadWithLargeIndexStaysWide() throws IOException {
39 // wide, iload, index 0x012C (300)
40 final Instruction instruction = Instruction.readInstruction(new byte[] {(byte) Const.WIDE, (byte) Const.ILOAD, 0x01, 0x2C});
41 assertEquals(300, ((ILOAD) instruction).getIndex());
42 assertEquals(4, instruction.getLength());
43 assertEquals(instruction.getLength(), instruction.dumpToByteArray().length);
44 }
45
46 /**
47 * {@code dump} emits the {@code wide} prefix only when the index needs it, so a {@code wide} load whose index fits in a byte must report the two-byte
48 * length it actually writes rather than the four bytes it was read from.
49 */
50 @Test
51 void testWideLoadWithSmallIndexLengthMatchesDump() throws IOException {
52 // wide, iload, index 0x0005
53 final Instruction instruction = Instruction.readInstruction(new byte[] {(byte) Const.WIDE, (byte) Const.ILOAD, 0x00, 0x05});
54 assertEquals(5, ((ILOAD) instruction).getIndex());
55 assertEquals(instruction.dumpToByteArray().length, instruction.getLength());
56 }
57
58 /**
59 * The store family shares the same base-class parsing, so it must round-trip its length too.
60 */
61 @Test
62 void testWideStoreWithSmallIndexLengthMatchesDump() throws IOException {
63 // wide, istore, index 0x0007
64 final Instruction instruction = Instruction.readInstruction(new byte[] {(byte) Const.WIDE, (byte) Const.ISTORE, 0x00, 0x07});
65 assertEquals(7, ((ISTORE) instruction).getIndex());
66 assertEquals(instruction.dumpToByteArray().length, instruction.getLength());
67 }
68 }