View Javadoc
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.classfile;
21  
22  import static org.junit.jupiter.api.Assertions.assertEquals;
23  import static org.junit.jupiter.api.Assertions.assertFalse;
24  import static org.junit.jupiter.api.Assertions.assertNotNull;
25  import static org.junit.jupiter.api.Assertions.assertNull;
26  import static org.junit.jupiter.api.Assertions.assertThrows;
27  import static org.junit.jupiter.api.Assertions.assertTrue;
28  import static org.junit.jupiter.api.Assertions.fail;
29  
30  import java.util.Arrays;
31  import java.util.concurrent.atomic.AtomicReference;
32  
33  import org.apache.bcel.Const;
34  import org.apache.bcel.Repository;
35  import org.apache.bcel.util.ByteSequence;
36  import org.junit.jupiter.api.Test;
37  
38  /**
39   * Tests {@link Utility}.
40   */
41  class UtilityTest {
42  
43  
44      @Test
45      void testClearBit() {
46          assertEquals(0, Utility.clearBit(0, 0));
47          assertEquals(0, Utility.clearBit(1, 0), "1 bit 0 set to 0 -> 0");
48          assertEquals(1, Utility.clearBit(1, 1), "1 bit 1 is 0 hence no change");
49          assertEquals(8, Utility.clearBit(8, 4), "1000 only has 4 bits, hence no change");
50          assertEquals(1, Utility.clearBit(9, 3), "1001 bit 3 set to 0 -> 0001");
51          assertEquals(-2, Utility.clearBit(-1, 0), "111...11 set bit 0 to 0 -> 111..10");
52          assertEquals(0, Utility.clearBit(Integer.MIN_VALUE, 31), "100...00 set bit 31 to 0 -> 000..00");
53      }
54  
55      @Test
56      void testCodeToString() throws Exception {
57          final class CodeToString {
58              int[][] a = new int[0][0];
59  
60              CodeToString() {
61                  if (a instanceof int[][]) {
62                      System.out.print(Arrays.asList(a).size());
63                  }
64              }
65          }
66          final JavaClass javaClass = Repository.lookupClass(CodeToString.class);
67          assertNotNull(javaClass);
68          for (final Method method : javaClass.getMethods()) {
69              assertEquals("<init>", method.getName());
70              final String code = method.getCode().toString(false);
71              assertTrue(code.contains("0:    aload_0"), code);
72              assertTrue(code.contains("1:    aload_1"), code);
73              assertTrue(
74                      code.contains(
75                              "2:    putfield\t\torg.apache.bcel.classfile.UtilityTest$1CodeToString.this$0 Lorg/apache/bcel/classfile/UtilityTest;"),
76                      code);
77              assertTrue(code.contains("5:    aload_0"), code);
78              assertTrue(code.contains("6:    invokespecial\tjava.lang.Object.<init> ()V"), code);
79              assertTrue(code.contains("9:    aload_0"), code);
80              assertTrue(code.contains("10:   iconst_0"), code);
81              assertTrue(code.contains("11:   iconst_0"), code);
82              assertTrue(code.contains("12:   multianewarray\t<[[I>\t2"), code);
83              assertTrue(code.contains("16:   putfield\t\torg.apache.bcel.classfile.UtilityTest$1CodeToString.a [[I"), code);
84              assertTrue(code.contains("19:   aload_0"), code);
85              assertTrue(code.contains("20:   getfield\t\torg.apache.bcel.classfile.UtilityTest$1CodeToString.a [[I"), code);
86              assertTrue(code.contains("23:   instanceof\t<[[I>"), code);
87              assertTrue(code.contains("26:   ifeq\t\t#47"), code);
88              assertTrue(code.contains("29:   getstatic\t\tjava.lang.System.out Ljava/io/PrintStream;"), code);
89              assertTrue(code.contains("32:   aload_0"), code);
90              assertTrue(code.contains("33:   getfield\t\torg.apache.bcel.classfile.UtilityTest$1CodeToString.a [[I"), code);
91              assertTrue(code.contains("36:   invokestatic\tjava.util.Arrays.asList ([Ljava/lang/Object;)Ljava/util/List;"), code);
92              assertTrue(code.contains("39:   invokeinterface\tjava.util.List.size ()I1\t0"), code);
93              assertTrue(code.contains("44:   invokevirtual\tjava.io.PrintStream.print "), code);
94              assertTrue(code.contains("47:   return"), code);
95          }
96      }
97  
98  
99      @Test
100     void testCodeToStringOversizedLookupSwitch() {
101         // A LOOKUPSWITCH claiming Integer.MAX_VALUE pairs without any table bytes behind it
102         // must be rejected instead of allocating two huge arrays.
103         final byte[] code = { (byte) Const.LOOKUPSWITCH, 0, 0, 0, // opcode plus 3 padding bytes
104             0, 0, 0, 0, // default offset
105             0x7f, (byte) 0xff, (byte) 0xff, (byte) 0xff }; // npairs = Integer.MAX_VALUE
106         assertThrows(ClassFormatException.class, () -> Utility.codeToString(new ByteSequence(code), new ConstantPool()));
107     }
108 
109     @Test
110     void testCodeToStringOversizedTableSwitch() {
111         // A TABLESWITCH claiming 2^32 entries without any table bytes behind it must be
112         // rejected instead of allocating a huge jump table.
113         final byte[] code = { (byte) Const.TABLESWITCH, 0, 0, 0, // opcode plus 3 padding bytes
114             0, 0, 0, 0, // default offset
115             (byte) 0x80, 0, 0, 0, // low = Integer.MIN_VALUE
116             0x7f, (byte) 0xff, (byte) 0xff, (byte) 0xff }; // high = Integer.MAX_VALUE
117         assertThrows(ClassFormatException.class, () -> Utility.codeToString(new ByteSequence(code), new ConstantPool()));
118     }
119 
120     @Test
121     void testCodeToStringWideDoesNotLeakAcrossCalls() {
122         // A truncated code array ending right after a WIDE opcode must not leave the thread-local WIDE flag
123         // set, or the next (unrelated) disassembly on the same thread is mis-decoded.
124         final String first = Utility.codeToString(new byte[] {(byte) Const.WIDE}, new ConstantPool(), 0, -1, false);
125         assertTrue(first.contains("wide"), first);
126         // iload with a single index byte; without the reset this reads a 16-bit index (%258) and swallows a byte.
127         final String next = Utility.codeToString(new byte[] {(byte) Const.ILOAD, 1, 2}, new ConstantPool(), 0, -1, false);
128         assertTrue(next.contains("iload\t\t%1"), next);
129         // Same for the exceptional path: wide iload with its operand missing throws, but must still reset the flag.
130         try {
131             Utility.codeToString(new byte[] {(byte) Const.WIDE, (byte) Const.ILOAD}, new ConstantPool(), 0, -1, false);
132             fail("Expected ClassFormatException for a truncated wide instruction");
133         } catch (final ClassFormatException e) {
134             // expected: the operand of the wide iload is missing
135         }
136         final String afterThrow = Utility.codeToString(new byte[] {(byte) Const.ILOAD, 1, 2}, new ConstantPool(), 0, -1, false);
137         assertTrue(afterThrow.contains("iload\t\t%1"), afterThrow);
138     }
139 
140     @Test
141     void testCodeToStringWideIsThreadLocal() throws Exception {
142         // A WIDE opcode disassembled on one thread must not change how the next
143         // local-variable instruction is decoded on another thread.
144         final Thread setter = new Thread(() -> {
145             try {
146                 Utility.codeToString(new ByteSequence(new byte[] {(byte) Const.WIDE}), new ConstantPool(), false);
147             } catch (final Exception e) {
148                 fail("WIDE disassembly failed", e);
149             }
150         });
151         setter.start();
152         setter.join();
153         final AtomicReference<String> reader = new AtomicReference<>();
154         final Thread thread = new Thread(() -> {
155             try {
156                 // iload with a single index byte; the trailing 0x02 must stay unread.
157                 reader.set(Utility.codeToString(new ByteSequence(new byte[] {(byte) Const.ILOAD, 1, 2}), new ConstantPool(), false));
158             } catch (final Exception e) {
159                 fail("iload disassembly failed", e);
160             }
161         });
162         thread.start();
163         thread.join();
164         assertEquals("iload\t\t%1", reader.get());
165     }
166 
167     @Test
168     void testConvertString() {
169         assertEquals("\\n", Utility.convertString("\n"));
170         assertEquals("\\r", Utility.convertString("\r"));
171         assertEquals("\\\"", Utility.convertString("\""));
172         assertEquals("\\'", Utility.convertString("'"));
173         assertEquals("\\\\", Utility.convertString("\\"));
174         assertEquals("abc", Utility.convertString("abc"));
175     }
176 
177     @Test
178     void testDeeplyNestedTypeSignatureThrows() {
179         // One recursion level per generic nesting level: must fail fast, not StackOverflowError.
180         final int depth = 20_000;
181         final StringBuilder sig = new StringBuilder();
182         for (int i = 0; i < depth; i++) {
183             sig.append("LA<");
184         }
185         sig.append("LB;");
186         for (int i = 0; i < depth; i++) {
187             sig.append(">;");
188         }
189         assertThrows(ClassFormatException.class, () -> Utility.typeSignatureToString(sig.toString(), false));
190     }
191 
192     @Test
193     void testIsSet() {
194         assertTrue(Utility.isSet(1, 0));
195         assertTrue(Utility.isSet(7, 1));
196         assertTrue(Utility.isSet(8, 3));
197         assertTrue(Utility.isSet(9, 0));
198         assertTrue(Utility.isSet(Integer.MIN_VALUE, 31));
199         assertFalse(Utility.isSet(0, 0));
200         assertFalse(Utility.isSet(8, 4));
201         assertFalse(Utility.isSet(9, 1));
202     }
203 
204     @Test
205     void testModeratelyNestedTypeSignatureStillParses() {
206         assertEquals("A<A<B>>", Utility.typeSignatureToString("LA<LA<LB;>;>;", false));
207     }
208 
209     @Test
210     void testPrintArray() {
211         assertNull(Utility.printArray(null, false, false));
212         assertEquals("", Utility.printArray(new Object[0], false, false));
213         assertEquals("{}", Utility.printArray(new Object[0], true, false));
214         assertEquals("null", Utility.printArray(new Object[] { null }, false, false));
215         assertEquals("a, b", Utility.printArray(new String[] { "a", "b" }, false, false));
216         assertEquals("{a, b}", Utility.printArray(new String[] { "a", "b" }, true, false));
217         assertEquals("\"a\", \"b\"", Utility.printArray(new String[] { "a", "b" }, false, true));
218         assertEquals("{\"a\", \"b\"}", Utility.printArray(new String[] { "a", "b" }, true, true));
219     }
220 
221     @Test
222     void testSearchOpcode() {
223         assertEquals(Const.ALOAD, Utility.searchOpcode("aload"));
224         assertEquals(Const.NOP, Utility.searchOpcode("nop"));
225         assertEquals(Const.BREAKPOINT, Utility.searchOpcode("breakpoint"));
226         assertEquals(Const.IMPDEP2, Utility.searchOpcode("impdep2"));
227         assertEquals(Const.I2D, Utility.searchOpcode("I2D"), "case insensitive");
228         assertEquals(Const.UNDEFINED, Utility.searchOpcode("???"), "not found");
229     }
230 
231     @Test
232     void testSetBit() {
233         assertEquals(1, Utility.setBit(0, 0), "0 bit 0 set to 1 -> 1");
234         assertEquals(1, Utility.setBit(1, 0), "1 bit 0 is 1 hence no change");
235         assertEquals(3, Utility.setBit(1, 1), "1 bit 1 set to 1 -> 3");
236         assertEquals(8, Utility.setBit(8, 3), "1000 bit 3 is 1 hence no change");
237         assertEquals(9, Utility.setBit(1, 3), "0001 bit 3 set to 1 -> 1001");
238         assertEquals(-1, Utility.setBit(-2, 0), "111...10 set bit 0 to 1 -> 111..11");
239         assertEquals(Integer.MIN_VALUE, Utility.setBit(0, 31), "000...00 set bit 31 to 0 -> 100..00");
240     }
241 
242     @Test
243     void testSignatureToStringWithGenerics() throws Exception {
244         // tests for BCEL-197
245         assertEquals("java.util.Map<X, java.util.List<Y>>", Utility.signatureToString("Ljava/util/Map<TX;Ljava/util/List<TY;>;>;"), "generic signature");
246         assertEquals("java.util.Set<? extends java.nio.file.OpenOption>", Utility.signatureToString("Ljava/util/Set<+Ljava/nio/file/OpenOption;>;"),
247                 "generic signature");
248         assertEquals("java.nio.file.attribute.FileAttribute<?>[]", Utility.signatureToString("[Ljava/nio/file/attribute/FileAttribute<*>;"),
249                 "generic signature");
250 
251         // tests for BCEL-286
252         assertEquals(
253           "boofcv.alg.tracker.tld.TldTracker<boofcv.struct.image.ImageGray<boofcv.struct.image.GrayU8>, boofcv.struct.image.GrayI<boofcv.struct.image.GrayU8>>",
254             Utility.signatureToString(
255               "Lboofcv/alg/tracker/tld/TldTracker<Lboofcv/struct/image/ImageGray<Lboofcv/struct/image/GrayU8;>;Lboofcv/struct/image/GrayI<Lboofcv/struct/image/GrayU8;>;>;"),
256               "generic signature");
257         assertEquals("java.util.Map<?, ?>", Utility.signatureToString("Ljava/util/Map<**>;"), "generic signature");
258         assertEquals("com.jme3.util.IntMap<T>.IntMapIterator", Utility.signatureToString("Lcom/jme3/util/IntMap<TT;>.IntMapIterator;"), "generic signature");
259 
260         // tests for BCEL-279
261         assertEquals("<T extends java.lang.Object>(com.google.common.io.ByteProcessor<T>, int)T",
262                 Utility.signatureToString("<T:Ljava/lang/Object;>(Lcom/google/common/io/ByteProcessor<TT;>;I)TT;", false), "type parameters signature");
263         assertEquals("<T extends Object>(com.google.common.io.ByteProcessor<T>, int)T",
264                 Utility.signatureToString("<T:Ljava/lang/Object;>(Lcom/google/common/io/ByteProcessor<TT;>;I)TT;", true), "type parameters signature");
265         assertEquals("<M extends java.lang.reflect.AccessibleObject & java.lang.reflect.Member>(M)void",
266                 Utility.signatureToString("<M:Ljava/lang/reflect/AccessibleObject;:Ljava/lang/reflect/Member;>(TM;)V"), "type parameters signature");
267         assertEquals("<K1 extends K, V1 extends V>()com.google.common.cache.Weigher<K1, V1>",
268                 Utility.signatureToString("<K1:TK;V1:TV;>()Lcom/google/common/cache/Weigher<TK1;TV1;>;"), "type parameters signature");
269         assertEquals("<K1 extends K, V1 extends V>(com.google.common.cache.Weigher<? super K1, ? super V1>)com.google.common.cache.CacheBuilder<K1, V1>",
270                 Utility.signatureToString("<K1:TK;V1:TV;>(Lcom/google/common/cache/Weigher<-TK1;-TV1;>;)Lcom/google/common/cache/CacheBuilder<TK1;TV1;>;"),
271                 "type parameters signature");
272         assertEquals("<N extends java.lang.Object, E extends java.lang.Object> extends java.lang.Object implements com.google.common.graph.Network<N, E>",
273                 Utility.signatureToString("<N:Ljava/lang/Object;E:Ljava/lang/Object;>Ljava/lang/Object;Lcom/google/common/graph/Network<TN;TE;>;", false),
274                 "class signature");
275         assertEquals("<K extends Object, V extends Object> extends Object",
276                 Utility.signatureToString("<K:Ljava/lang/Object;V:Ljava/lang/Object;>Ljava/lang/Object;"), "class signature");
277     }
278 }