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.generic;
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.List;
32  
33  import org.apache.bcel.Const;
34  import org.apache.bcel.Repository;
35  import org.apache.bcel.classfile.JavaClass;
36  import org.apache.bcel.classfile.Method;
37  import org.junit.jupiter.api.Test;
38  
39  class MethodGenTest {
40  
41      @interface A {
42      }
43  
44      @interface B {
45      }
46  
47      public static class Bar {
48          public class Inner {
49              Inner(@A final Object a, @B final Object b) {
50  
51              }
52          }
53      }
54  
55      public static class Foo {
56          public void bar() {
57              @SuppressWarnings("unused")
58              final int a = 1;
59          }
60      }
61  
62      private MethodGen getMethod(final Class<?> cls, final String name) throws ClassNotFoundException {
63          final JavaClass jc = Repository.lookupClass(cls);
64          final ConstantPoolGen cp = new ConstantPoolGen(jc.getConstantPool());
65          for (final Method method : jc.getMethods()) {
66              if (method.getName().equals(name)) {
67                  return new MethodGen(method, jc.getClassName(), cp);
68              }
69          }
70  
71          fail(() -> "Method " + name + " not found in class " + cls);
72          return null;
73      }
74  
75      @Test
76      void testAnnotationsAreUnpacked() throws Exception {
77          final JavaClass jc = Repository.lookupClass(Bar.Inner.class);
78          final ClassGen cg = new ClassGen(jc);
79          final MethodGen mg = new MethodGen(cg.getMethodAt(0), cg.getClassName(), cg.getConstantPool());
80          final List<AnnotationEntryGen> firstParamAnnotations = mg.getAnnotationsOnParameter(0);
81          assertEquals(1, firstParamAnnotations.size(), "Wrong number of annotations in the first parameter");
82          final List<AnnotationEntryGen> secondParamAnnotations = mg.getAnnotationsOnParameter(1);
83          assertEquals(1, secondParamAnnotations.size(), "Wrong number of annotations in the second parameter");
84      }
85  
86      private void testInvalidNullMethodBody(final String className) throws ClassNotFoundException {
87          final JavaClass jc = Repository.lookupClass(className);
88          final ClassGen classGen = new ClassGen(jc);
89          for (final Method method : jc.getMethods()) {
90              new MethodGen(method, jc.getClassName(), classGen.getConstantPool());
91          }
92      }
93  
94      @Test
95      void testInvalidNullMethodBody_EmptyStaticInit() throws Exception {
96          testInvalidNullMethodBody("org.apache.bcel.generic.EmptyStaticInit");
97      }
98  
99      @Test
100     void testInvalidNullMethodBody_MailDateFormat() {
101         assertThrows(IllegalStateException.class, () -> testInvalidNullMethodBody("javax.mail.internet.MailDateFormat"));
102     }
103 
104     @Test
105     void testRemoveLocalVariable() throws Exception {
106         final MethodGen mg = getMethod(Foo.class, "bar");
107 
108         final LocalVariableGen lv = mg.getLocalVariables()[1];
109         assertEquals("a", lv.getName(), "variable name");
110         final InstructionHandle start = lv.getStart();
111         final InstructionHandle end = lv.getEnd();
112         assertNotNull(start, "scope start");
113         assertNotNull(end, "scope end");
114         assertTrue(Arrays.asList(start.getTargeters()).contains(lv), "scope start not targeted by the local variable");
115         assertTrue(Arrays.asList(end.getTargeters()).contains(lv), "scope end not targeted by the local variable");
116 
117         // now let's remove the local variable
118         mg.removeLocalVariable(lv);
119 
120         assertFalse(Arrays.asList(start.getTargeters()).contains(lv), "scope start still targeted by the removed variable");
121         assertFalse(Arrays.asList(end.getTargeters()).contains(lv), "scope end still targeted by the removed variable");
122         assertNull(lv.getStart(), "scope start");
123         assertNull(lv.getEnd(), "scope end");
124     }
125 
126     @Test
127     void testRemoveLocalVariables() throws Exception {
128         final MethodGen mg = getMethod(Foo.class, "bar");
129 
130         final LocalVariableGen lv = mg.getLocalVariables()[1];
131         assertEquals("a", lv.getName(), "variable name");
132         final InstructionHandle start = lv.getStart();
133         final InstructionHandle end = lv.getEnd();
134         assertNotNull(start, "scope start");
135         assertNotNull(end, "scope end");
136         assertTrue(Arrays.asList(start.getTargeters()).contains(lv), "scope start not targeted by the local variable");
137         assertTrue(Arrays.asList(end.getTargeters()).contains(lv), "scope end not targeted by the local variable");
138 
139         // now let's remove the local variables
140         mg.removeLocalVariables();
141 
142         assertFalse(Arrays.asList(start.getTargeters()).contains(lv), "scope start still targeted by the removed variable");
143         assertFalse(Arrays.asList(end.getTargeters()).contains(lv), "scope end still targeted by the removed variable");
144         assertNull(lv.getStart(), "scope start");
145         assertNull(lv.getEnd(), "scope end");
146     }
147 
148     @Test
149     void testSetMaxLocalsAccountsForLocalVariableTable() {
150         // BCEL-280: some compilers (for example kotlinc) emit LocalVariableTable entries for slots that no
151         // instruction in the method body ever touches. setMaxLocals() must not shrink maxLocals below
152         // what those entries require, or the resulting class file fails verification with a
153         // "Invalid index ... in LocalVariableTable" ClassFormatError.
154         final InstructionList il = new InstructionList();
155         il.append(InstructionConst.ALOAD_0);
156         il.append(InstructionConst.RETURN);
157 
158         final MethodGen mg = new MethodGen(Const.ACC_PUBLIC, Type.VOID, Type.NO_ARGS, new String[0], "bar", "Foo", il,
159             new ConstantPoolGen());
160 
161         final InstructionHandle start = il.getStart();
162         final InstructionHandle end = il.getEnd();
163         // Slot 6 is only referenced through the local variable table below, never by an instruction.
164         mg.addLocalVariable("unusedByCompiler", Type.INT, 6, start, end);
165         assertEquals(7, mg.getMaxLocals(), "addLocalVariable() should already have grown maxLocals");
166 
167         // Simulate a later pass (for example instrumentation) recomputing maxLocals from the instruction list.
168         mg.setMaxLocals();
169 
170         assertEquals(7, mg.getMaxLocals(), "setMaxLocals() dropped a local variable table entry unreferenced by instructions");
171     }
172 }