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