1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.bcel.verifier.structurals;
18
19 import java.io.PrintWriter;
20 import java.io.StringWriter;
21 import java.util.ArrayList;
22 import java.util.List;
23 import java.util.Random;
24 import java.util.Vector;
25
26 import org.apache.bcel.Const;
27 import org.apache.bcel.Repository;
28 import org.apache.bcel.classfile.JavaClass;
29 import org.apache.bcel.classfile.Method;
30 import org.apache.bcel.generic.ConstantPoolGen;
31 import org.apache.bcel.generic.InstructionHandle;
32 import org.apache.bcel.generic.JsrInstruction;
33 import org.apache.bcel.generic.MethodGen;
34 import org.apache.bcel.generic.ObjectType;
35 import org.apache.bcel.generic.RET;
36 import org.apache.bcel.generic.ReferenceType;
37 import org.apache.bcel.generic.ReturnInstruction;
38 import org.apache.bcel.generic.ReturnaddressType;
39 import org.apache.bcel.generic.Type;
40 import org.apache.bcel.verifier.PassVerifier;
41 import org.apache.bcel.verifier.VerificationResult;
42 import org.apache.bcel.verifier.Verifier;
43 import org.apache.bcel.verifier.exc.AssertionViolatedException;
44 import org.apache.bcel.verifier.exc.StructuralCodeConstraintException;
45 import org.apache.bcel.verifier.exc.VerifierConstraintViolatedException;
46
47
48
49
50
51
52
53
54
55 public final class Pass3bVerifier extends PassVerifier {
56
57
58
59
60
61
62
63
64
65
66
67
68
69 private static final class InstructionContextQueue {
70
71
72 private final List<InstructionContext> ics = new Vector<>();
73
74 private final List<ArrayList<InstructionContext>> ecs = new Vector<>();
75
76
77
78
79
80
81
82 public void add(final InstructionContext ic, final ArrayList<InstructionContext> executionChain) {
83 ics.add(ic);
84 ecs.add(executionChain);
85 }
86
87
88
89
90
91
92
93 public ArrayList<InstructionContext> getEC(final int i) {
94 return ecs.get(i);
95 }
96
97
98
99
100
101
102
103 public InstructionContext getIC(final int i) {
104 return ics.get(i);
105 }
106
107
108
109
110
111
112 public boolean isEmpty() {
113 return ics.isEmpty();
114 }
115
116
117
118
119
120
121 public void remove(final int i) {
122 ics.remove(i);
123 ecs.remove(i);
124 }
125
126
127
128
129
130
131 public int size() {
132 return ics.size();
133 }
134 }
135
136
137 private static final boolean DEBUG = true;
138
139
140 private final Verifier myOwner;
141
142
143 private final int methodNo;
144
145
146
147
148
149
150 public Pass3bVerifier(final Verifier myOwner, final int methodNo) {
151 this.myOwner = myOwner;
152 this.methodNo = methodNo;
153 }
154
155
156
157
158
159 private void circulationPump(final MethodGen m, final ControlFlowGraph cfg, final InstructionContext start, final Frame vanillaFrame,
160 final InstConstraintVisitor icv, final ExecutionVisitor ev) {
161 final Random random = new Random();
162 final InstructionContextQueue icq = new InstructionContextQueue();
163
164 start.execute(vanillaFrame, new ArrayList<>(), icv, ev);
165
166
167 icq.add(start, new ArrayList<>());
168
169
170 while (!icq.isEmpty()) {
171 InstructionContext u;
172 ArrayList<InstructionContext> ec;
173 if (!DEBUG) {
174 final int r = random.nextInt(icq.size());
175 u = icq.getIC(r);
176 ec = icq.getEC(r);
177 icq.remove(r);
178 } else {
179 u = icq.getIC(0);
180 ec = icq.getEC(0);
181 icq.remove(0);
182 }
183
184 @SuppressWarnings("unchecked")
185 final ArrayList<InstructionContext> oldchain = (ArrayList<InstructionContext>) ec.clone();
186 @SuppressWarnings("unchecked")
187 final ArrayList<InstructionContext> newchain = (ArrayList<InstructionContext>) ec.clone();
188 newchain.add(u);
189
190 if (u.getInstruction().getInstruction() instanceof RET) {
191
192
193
194 final RET ret = (RET) u.getInstruction().getInstruction();
195 final ReturnaddressType t = (ReturnaddressType) u.getOutFrame(oldchain).getLocals().get(ret.getIndex());
196 final InstructionContext theSuccessor = cfg.contextOf(t.getTarget());
197
198
199 InstructionContext lastJSR = null;
200 int skipJsr = 0;
201 for (int ss = oldchain.size() - 1; ss >= 0; ss--) {
202 if (skipJsr < 0) {
203 throw new AssertionViolatedException("More RET than JSR in execution chain?!");
204 }
205
206 if (oldchain.get(ss).getInstruction().getInstruction() instanceof JsrInstruction) {
207 if (skipJsr == 0) {
208 lastJSR = oldchain.get(ss);
209 break;
210 }
211 skipJsr--;
212 }
213 if (oldchain.get(ss).getInstruction().getInstruction() instanceof RET) {
214 skipJsr++;
215 }
216 }
217 if (lastJSR == null) {
218 throw new AssertionViolatedException("RET without a JSR before in ExecutionChain?! EC: '" + oldchain + "'.");
219 }
220 final JsrInstruction jsr = (JsrInstruction) lastJSR.getInstruction().getInstruction();
221 if (theSuccessor != cfg.contextOf(jsr.physicalSuccessor())) {
222 throw new AssertionViolatedException("RET '" + u.getInstruction() + "' info inconsistent: jump back to '" + theSuccessor + "' or '"
223 + cfg.contextOf(jsr.physicalSuccessor()) + "'?");
224 }
225
226 if (theSuccessor.execute(u.getOutFrame(oldchain), newchain, icv, ev)) {
227 @SuppressWarnings("unchecked")
228 final ArrayList<InstructionContext> newchainClone = (ArrayList<InstructionContext>) newchain.clone();
229 icq.add(theSuccessor, newchainClone);
230 }
231 } else {
232
233
234 final InstructionContext[] succs = u.getSuccessors();
235 for (final InstructionContext v : succs) {
236 if (v.execute(u.getOutFrame(oldchain), newchain, icv, ev)) {
237 @SuppressWarnings("unchecked")
238 final ArrayList<InstructionContext> newchainClone = (ArrayList<InstructionContext>) newchain.clone();
239 icq.add(v, newchainClone);
240 }
241 }
242 }
243
244
245
246 final ExceptionHandler[] excHds = u.getExceptionHandlers();
247 for (final ExceptionHandler excHd : excHds) {
248 final InstructionContext v = cfg.contextOf(excHd.getHandlerStart());
249
250
251
252
253
254
255
256
257
258
259
260
261 if (v.execute(new Frame(u.getOutFrame(oldchain).getLocals(), new OperandStack(u.getOutFrame(oldchain).getStack().maxStack(),
262 excHd.getExceptionType() == null ? Type.THROWABLE : excHd.getExceptionType())), new ArrayList<>(), icv, ev)) {
263 icq.add(v, new ArrayList<>());
264 }
265 }
266
267 }
268
269 InstructionHandle ih = start.getInstruction();
270 do {
271 if (ih.getInstruction() instanceof ReturnInstruction && !cfg.isDead(ih)) {
272 final InstructionContext ic = cfg.contextOf(ih);
273
274
275 final Frame f = ic.getOutFrame(new ArrayList<>());
276 final LocalVariables lvs = f.getLocals();
277 for (int i = 0; i < lvs.maxLocals(); i++) {
278 if (lvs.get(i) instanceof UninitializedObjectType) {
279 addMessage("Warning: ReturnInstruction '" + ic + "' may leave method with an uninitialized object in the local variables array '"
280 + lvs + "'.");
281 }
282 }
283 final OperandStack os = f.getStack();
284 for (int i = 0; i < os.size(); i++) {
285 if (os.peek(i) instanceof UninitializedObjectType) {
286 addMessage(
287 "Warning: ReturnInstruction '" + ic + "' may leave method with an uninitialized object on the operand stack '" + os + "'.");
288 }
289 }
290
291 Type returnedType = null;
292 final OperandStack inStack = ic.getInFrame().getStack();
293 if (inStack.size() >= 1) {
294 returnedType = inStack.peek();
295 } else {
296 returnedType = Type.VOID;
297 }
298
299 if (returnedType != null) {
300 if (returnedType instanceof ReferenceType) {
301 try {
302 if (!((ReferenceType) returnedType).isCastableTo(m.getReturnType())) {
303 invalidReturnTypeError(returnedType, m);
304 }
305 } catch (final ClassNotFoundException e) {
306
307 throw new IllegalArgumentException(e);
308 }
309 } else if (!returnedType.equals(m.getReturnType().normalizeForStackOrLocal())) {
310 invalidReturnTypeError(returnedType, m);
311 }
312 }
313 }
314 } while ((ih = ih.getNext()) != null);
315
316 }
317
318
319
320
321
322
323
324
325
326 @Override
327 public VerificationResult do_verify() {
328 if (!myOwner.doPass3a(methodNo).equals(VerificationResult.VR_OK)) {
329 return VerificationResult.VR_NOTYET;
330 }
331
332
333
334 JavaClass jc;
335 try {
336 jc = Repository.lookupClass(myOwner.getClassName());
337 } catch (final ClassNotFoundException e) {
338
339 throw new AssertionViolatedException("Missing class: " + e, e);
340 }
341
342 final ConstantPoolGen constantPoolGen = new ConstantPoolGen(jc.getConstantPool());
343
344 final InstConstraintVisitor icv = new InstConstraintVisitor();
345 icv.setConstantPoolGen(constantPoolGen);
346
347 final ExecutionVisitor ev = new ExecutionVisitor();
348 ev.setConstantPoolGen(constantPoolGen);
349
350 final Method[] methods = jc.getMethods();
351
352 try {
353
354 final MethodGen mg = new MethodGen(methods[methodNo], myOwner.getClassName(), constantPoolGen);
355
356 icv.setMethodGen(mg);
357
358
359 if (!(mg.isAbstract() || mg.isNative())) {
360
361 final ControlFlowGraph cfg = new ControlFlowGraph(mg);
362
363
364 final Frame f = new Frame(mg.getMaxLocals(), mg.getMaxStack());
365 if (!mg.isStatic()) {
366 if (mg.getName().equals(Const.CONSTRUCTOR_NAME)) {
367 Frame.setThis(new UninitializedObjectType(ObjectType.getInstance(jc.getClassName())));
368 f.getLocals().set(0, Frame.getThis());
369 } else {
370 Frame.setThis(null);
371 f.getLocals().set(0, ObjectType.getInstance(jc.getClassName()));
372 }
373 }
374 final Type[] argtypes = mg.getArgumentTypes();
375 int twoslotoffset = 0;
376 for (int j = 0; j < argtypes.length; j++) {
377 if (argtypes[j] == Type.SHORT || argtypes[j] == Type.BYTE || argtypes[j] == Type.CHAR || argtypes[j] == Type.BOOLEAN) {
378 argtypes[j] = Type.INT;
379 }
380 f.getLocals().set(twoslotoffset + j + (mg.isStatic() ? 0 : 1), argtypes[j]);
381 if (argtypes[j].getSize() == 2) {
382 twoslotoffset++;
383 f.getLocals().set(twoslotoffset + j + (mg.isStatic() ? 0 : 1), Type.UNKNOWN);
384 }
385 }
386 circulationPump(mg, cfg, cfg.contextOf(mg.getInstructionList().getStart()), f, icv, ev);
387 }
388 } catch (final VerifierConstraintViolatedException ce) {
389 ce.extendMessage("Constraint violated in method '" + methods[methodNo] + "':\n", "");
390 return new VerificationResult(VerificationResult.VERIFIED_REJECTED, ce.getMessage());
391 } catch (final RuntimeException re) {
392
393
394 final StringWriter sw = new StringWriter();
395 final PrintWriter pw = new PrintWriter(sw);
396 re.printStackTrace(pw);
397
398 throw new AssertionViolatedException("Some RuntimeException occurred while verify()ing class '" + jc.getClassName() + "', method '"
399 + methods[methodNo] + "'. Original RuntimeException's stack trace:\n---\n" + sw + "---\n", re);
400 }
401 return VerificationResult.VR_OK;
402 }
403
404
405 public int getMethodNo() {
406 return methodNo;
407 }
408
409
410
411
412
413
414
415
416
417 public void invalidReturnTypeError(final Type returnedType, final MethodGen m) {
418 throw new StructuralCodeConstraintException("Returned type " + returnedType + " does not match Method's return type " + m.getReturnType());
419 }
420 }