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