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  package org.apache.bcel.util;
20  
21  import java.io.PrintWriter;
22  import java.util.ArrayList;
23  import java.util.HashMap;
24  import java.util.List;
25  import java.util.Map;
26  
27  import org.apache.bcel.Const;
28  import org.apache.bcel.classfile.ConstantInterfaceMethodref;
29  import org.apache.bcel.classfile.Utility;
30  import org.apache.bcel.generic.AllocationInstruction;
31  import org.apache.bcel.generic.ArrayInstruction;
32  import org.apache.bcel.generic.ArrayType;
33  import org.apache.bcel.generic.BranchHandle;
34  import org.apache.bcel.generic.BranchInstruction;
35  import org.apache.bcel.generic.CHECKCAST;
36  import org.apache.bcel.generic.CPInstruction;
37  import org.apache.bcel.generic.CodeExceptionGen;
38  import org.apache.bcel.generic.ConstantPoolGen;
39  import org.apache.bcel.generic.ConstantPushInstruction;
40  import org.apache.bcel.generic.EmptyVisitor;
41  import org.apache.bcel.generic.FieldInstruction;
42  import org.apache.bcel.generic.IINC;
43  import org.apache.bcel.generic.INSTANCEOF;
44  import org.apache.bcel.generic.Instruction;
45  import org.apache.bcel.generic.InstructionConst;
46  import org.apache.bcel.generic.InstructionHandle;
47  import org.apache.bcel.generic.InvokeInstruction;
48  import org.apache.bcel.generic.LDC;
49  import org.apache.bcel.generic.LDC2_W;
50  import org.apache.bcel.generic.LocalVariableInstruction;
51  import org.apache.bcel.generic.MULTIANEWARRAY;
52  import org.apache.bcel.generic.MethodGen;
53  import org.apache.bcel.generic.NEWARRAY;
54  import org.apache.bcel.generic.ObjectType;
55  import org.apache.bcel.generic.RET;
56  import org.apache.bcel.generic.ReturnInstruction;
57  import org.apache.bcel.generic.Select;
58  import org.apache.bcel.generic.Type;
59  import org.apache.commons.lang3.StringUtils;
60  
61  /**
62   * Factory creates il.append() statements, and sets instruction targets. A helper class for BCELifier.
63   *
64   * @see BCELifier
65   */
66  final class BCELFactory extends EmptyVisitor {
67  
68      private static final String CONSTANT_PREFIX = Const.class.getSimpleName() + ".";
69      private final MethodGen methodGen;
70      private final PrintWriter printWriter;
71      private final ConstantPoolGen constantPoolGen;
72      private final boolean preserveConstantPool;
73  
74      private final Map<Instruction, InstructionHandle> branchMap = new HashMap<>();
75  
76      // Memorize BranchInstructions that need an update
77      private final List<BranchInstruction> branches = new ArrayList<>();
78  
79      BCELFactory(final MethodGen methodGen, final PrintWriter printWriter, final boolean preserveConstantPool) {
80          this.methodGen = methodGen;
81          this.constantPoolGen = methodGen.getConstantPool();
82          this.printWriter = printWriter;
83          this.preserveConstantPool = preserveConstantPool;
84      }
85  
86      private void createConstant(final Object value) {
87          String embed = value.toString();
88          if (value instanceof String) {
89              embed = '"' + Utility.convertString(embed) + '"';
90          } else if (value instanceof Character) {
91              embed = "(char) 0x" + Integer.toHexString(((Character) value).charValue());
92          } else if (value instanceof Float) {
93              final Float f = (Float) value;
94              if (Float.isNaN(f)) {
95                  embed = "Float.NaN";
96              } else if (f == Float.POSITIVE_INFINITY) {
97                  embed = "Float.POSITIVE_INFINITY";
98              } else if (f == Float.NEGATIVE_INFINITY) {
99                  embed = "Float.NEGATIVE_INFINITY";
100             } else {
101                 embed += "f";
102             }
103         }  else if (value instanceof Double) {
104             final Double d = (Double) value;
105             if (Double.isNaN(d)) {
106                 embed = "Double.NaN";
107             } else if (d == Double.POSITIVE_INFINITY) {
108                 embed = "Double.POSITIVE_INFINITY";
109             } else if (d == Double.NEGATIVE_INFINITY) {
110                 embed = "Double.NEGATIVE_INFINITY";
111             } else {
112                 embed += "d";
113             }
114         } else if (value instanceof Long) {
115             embed += "L";
116         } else if (value instanceof ObjectType) {
117             final ObjectType ot = (ObjectType) value;
118             embed = "new ObjectType(\"" + Utility.convertString(ot.getClassName()) + "\")";
119         } else if (value instanceof ArrayType) {
120             final ArrayType at = (ArrayType) value;
121             embed = "new ArrayType(" + BCELifier.printType(at.getBasicType()) + ", " + at.getDimensions() + ")";
122         }
123 
124         printWriter.println("il.append(new PUSH(_cp, " + embed + "));");
125     }
126 
127     public void start() {
128         if (!methodGen.isAbstract() && !methodGen.isNative()) {
129             for (InstructionHandle ih = methodGen.getInstructionList().getStart(); ih != null; ih = ih.getNext()) {
130                 final Instruction i = ih.getInstruction();
131                 if (i instanceof BranchInstruction) {
132                     branchMap.put(i, ih); // memorize container
133                 }
134                 if (ih.hasTargeters()) {
135                     if (i instanceof BranchInstruction) {
136                         printWriter.println("    InstructionHandle ih_" + ih.getPosition() + ";");
137                     } else {
138                         printWriter.print("    InstructionHandle ih_" + ih.getPosition() + " = ");
139                     }
140                 } else {
141                     printWriter.print("    ");
142                 }
143                 if (!visitInstruction(i)) {
144                     i.accept(this);
145                 }
146             }
147             updateBranchTargets();
148             updateExceptionHandlers();
149         }
150     }
151 
152     private void updateBranchTargets() {
153         branches.forEach(bi -> {
154             final BranchHandle bh = (BranchHandle) branchMap.get(bi);
155             final int pos = bh.getPosition();
156             final String name = bi.getName() + "_" + pos;
157             int targetPos = bh.getTarget().getPosition();
158             printWriter.println("    " + name + ".setTarget(ih_" + targetPos + ");");
159             if (bi instanceof Select) {
160                 final InstructionHandle[] ihs = ((Select) bi).getTargets();
161                 for (int j = 0; j < ihs.length; j++) {
162                     targetPos = ihs[j].getPosition();
163                     printWriter.println("    " + name + ".setTarget(" + j + ", ih_" + targetPos + ");");
164                 }
165             }
166         });
167     }
168 
169     private void updateExceptionHandlers() {
170         final CodeExceptionGen[] handlers = methodGen.getExceptionHandlers();
171         for (final CodeExceptionGen h : handlers) {
172             final String type = h.getCatchType() == null ? "null" : BCELifier.printType(h.getCatchType());
173             printWriter.println("    method.addExceptionHandler(ih_" + h.getStartPC().getPosition() + ", ih_" + h.getEndPC().getPosition() + ", ih_"
174                     + h.getHandlerPC().getPosition() + ", " + type + ");");
175         }
176     }
177 
178     @Override
179     public void visitAllocationInstruction(final AllocationInstruction i) {
180         Type type;
181         if (i instanceof CPInstruction) {
182             type = ((CPInstruction) i).getType(constantPoolGen);
183         } else {
184             type = ((NEWARRAY) i).getType();
185         }
186         final short opcode = ((Instruction) i).getOpcode();
187         int dim = 1;
188         switch (opcode) {
189         case Const.NEW:
190             printWriter.println("il.append(_factory.createNew(\"" + Utility.convertString(((ObjectType) type).getClassName()) + "\"));");
191             break;
192         case Const.MULTIANEWARRAY:
193             dim = ((MULTIANEWARRAY) i).getDimensions();
194             // falls-through
195         case Const.NEWARRAY:
196             if (type instanceof ArrayType) {
197                 type = ((ArrayType) type).getBasicType();
198             }
199             // falls-through
200         case Const.ANEWARRAY:
201             printWriter.println("il.append(_factory.createNewArray(" + BCELifier.printType(type) + ", (short) " + dim + "));");
202             break;
203         default:
204             throw new IllegalArgumentException("Unhandled opcode: " + opcode);
205         }
206     }
207 
208     @Override
209     public void visitArrayInstruction(final ArrayInstruction i) {
210         final short opcode = i.getOpcode();
211         final Type type = i.getType(constantPoolGen);
212         final String kind = opcode < Const.IASTORE ? "Load" : "Store";
213         printWriter.println("il.append(_factory.createArray" + kind + "(" + BCELifier.printType(type) + "));");
214     }
215 
216     @Override
217     public void visitBranchInstruction(final BranchInstruction bi) {
218         final BranchHandle bh = (BranchHandle) branchMap.get(bi);
219         final int pos = bh.getPosition();
220         final String name = bi.getName() + "_" + pos;
221         if (bi instanceof Select) {
222             final Select s = (Select) bi;
223             branches.add(bi);
224             final StringBuilder args = new StringBuilder("new int[] { ");
225             final int[] matchs = s.getMatchs();
226             for (int i = 0; i < matchs.length; i++) {
227                 args.append(matchs[i]);
228                 if (i < matchs.length - 1) {
229                     args.append(", ");
230                 }
231             }
232             args.append(" }");
233             printWriter.print("Select " + name + " = new " + StringUtils.toRootUpperCase(bi.getName()) + "(" + args + ", new InstructionHandle[] { ");
234             for (int i = 0; i < matchs.length; i++) {
235                 printWriter.print("null");
236                 if (i < matchs.length - 1) {
237                     printWriter.print(", ");
238                 }
239             }
240             printWriter.println(" }, null);");
241         } else {
242             final int tPos = bh.getTarget().getPosition();
243             final String target;
244             if (pos > tPos) {
245                 target = "ih_" + tPos;
246             } else {
247                 branches.add(bi);
248                 target = "null";
249             }
250             printWriter.println("    BranchInstruction " + name + " = _factory.createBranchInstruction(" + CONSTANT_PREFIX
251                     + StringUtils.toRootUpperCase(bi.getName()) + ", " + target + ");");
252         }
253         if (bh.hasTargeters()) {
254             printWriter.println("    ih_" + pos + " = il.append(" + name + ");");
255         } else {
256             printWriter.println("    il.append(" + name + ");");
257         }
258     }
259 
260     @Override
261     public void visitCHECKCAST(final CHECKCAST i) {
262         final Type type = i.getType(constantPoolGen);
263         printWriter.println("il.append(_factory.createCheckCast(" + BCELifier.printType(type) + "));");
264     }
265 
266     @Override
267     public void visitConstantPushInstruction(final ConstantPushInstruction i) {
268         createConstant(i.getValue());
269     }
270 
271     @Override
272     public void visitFieldInstruction(final FieldInstruction i) {
273         final short opcode = i.getOpcode();
274         final String className = i.getClassName(constantPoolGen);
275         final String fieldName = i.getFieldName(constantPoolGen);
276         final Type type = i.getFieldType(constantPoolGen);
277         printWriter.println("il.append(_factory.createFieldAccess(\"" + Utility.convertString(className) + "\", \"" + Utility.convertString(fieldName) + "\", "
278                 + BCELifier.printType(type) + ", "
279                 + CONSTANT_PREFIX + StringUtils.toRootUpperCase(Const.getOpcodeName(opcode)) + "));");
280     }
281 
282     @Override
283     public void visitINSTANCEOF(final INSTANCEOF i) {
284         final Type type = i.getType(constantPoolGen);
285         printWriter.println("il.append(_factory.createInstanceOf(" + BCELifier.printType(type) + "));");
286     }
287 
288     private boolean visitInstruction(final Instruction i) {
289         final short opcode = i.getOpcode();
290         if (InstructionConst.getInstruction(opcode) != null && !(i instanceof ConstantPushInstruction) && !(i instanceof ReturnInstruction)) { // Handled below
291             printWriter.println("il.append(InstructionConst." + StringUtils.toRootUpperCase(i.getName()) + ");");
292             return true;
293         }
294         return false;
295     }
296 
297     @Override
298     public void visitInvokeInstruction(final InvokeInstruction i) {
299         final short opcode = i.getOpcode();
300         if (opcode == Const.INVOKEDYNAMIC) {
301             printWriter.println("il.append(new INVOKEDYNAMIC(" + i.getIndex() + "));");
302             return;
303         }
304         final String className = i.getClassName(constantPoolGen);
305         final String methodName = i.getMethodName(constantPoolGen);
306         final Type type = i.getReturnType(constantPoolGen);
307         final Type[] argTypes = i.getArgumentTypes(constantPoolGen);
308         printWriter.println("il.append(_factory.createInvoke(\"" + Utility.convertString(className) + "\", \"" + Utility.convertString(methodName) + "\", "
309             + BCELifier.printType(type) + ", " + BCELifier.printArgumentTypes(argTypes) + ", " + CONSTANT_PREFIX
310             + StringUtils.toRootUpperCase(Const.getOpcodeName(opcode))
311             + (opcode != Const.INVOKEINTERFACE && constantPoolGen.getConstant(i.getIndex()) instanceof ConstantInterfaceMethodref ? ", true" : "") + "));");
312     }
313 
314     @Override
315     public void visitLDC(final LDC i) {
316         if (preserveConstantPool) {
317             printWriter.println("il.append(new " + StringUtils.toRootUpperCase(i.getName()) + "(" + i.getIndex() + "));");
318         } else {
319             createConstant(i.getValue(constantPoolGen));
320         }
321     }
322 
323     @Override
324     public void visitLDC2_W(final LDC2_W i) {
325         if (preserveConstantPool) {
326             printWriter.println("il.append(new " + StringUtils.toRootUpperCase(i.getName()) + "(" + i.getIndex() + "));");
327         } else {
328             createConstant(i.getValue(constantPoolGen));
329         }
330     }
331 
332     @Override
333     public void visitLocalVariableInstruction(final LocalVariableInstruction i) {
334         final short opcode = i.getOpcode();
335         final Type type = i.getType(constantPoolGen);
336         if (opcode == Const.IINC) {
337             printWriter.println("il.append(new IINC(" + i.getIndex() + ", " + ((IINC) i).getIncrement() + "));");
338         } else {
339             final String kind = opcode < Const.ISTORE ? "Load" : "Store";
340             printWriter.println("il.append(_factory.create" + kind + "(" + BCELifier.printType(type) + ", " + i.getIndex() + "));");
341         }
342     }
343 
344     @Override
345     public void visitRET(final RET i) {
346         printWriter.println("il.append(new RET(" + i.getIndex() + "));");
347     }
348 
349     @Override
350     public void visitReturnInstruction(final ReturnInstruction i) {
351         final Type type = i.getType(constantPoolGen);
352         printWriter.println("il.append(_factory.createReturn(" + BCELifier.printType(type) + "));");
353     }
354 }