1 package org.apache.bcel.verifier.structurals;
2
3 /* ====================================================================
4 * The Apache Software License, Version 1.1
5 *
6 * Copyright (c) 2001 The Apache Software Foundation. All rights
7 * reserved.
8 *
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
11 * are met:
12 *
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 *
16 * 2. Redistributions in binary form must reproduce the above copyright
17 * notice, this list of conditions and the following disclaimer in
18 * the documentation and/or other materials provided with the
19 * distribution.
20 *
21 * 3. The end-user documentation included with the redistribution,
22 * if any, must include the following acknowledgment:
23 * "This product includes software developed by the
24 * Apache Software Foundation (http://www.apache.org/)."
25 * Alternately, this acknowledgment may appear in the software itself,
26 * if and wherever such third-party acknowledgments normally appear.
27 *
28 * 4. The names "Apache" and "Apache Software Foundation" and
29 * "Apache BCEL" must not be used to endorse or promote products
30 * derived from this software without prior written permission. For
31 * written permission, please contact apache@apache.org.
32 *
33 * 5. Products derived from this software may not be called "Apache",
34 * "Apache BCEL", nor may "Apache" appear in their name, without
35 * prior written permission of the Apache Software Foundation.
36 *
37 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
38 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
39 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
40 * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
41 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
42 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
43 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
44 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
45 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
46 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
47 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
48 * SUCH DAMAGE.
49 * ====================================================================
50 *
51 * This software consists of voluntary contributions made by many
52 * individuals on behalf of the Apache Software Foundation. For more
53 * information on the Apache Software Foundation, please see
54 * <http://www.apache.org/>.
55 */
56
57 import java.io.*;
58 import java.util.ArrayList;
59 import java.util.Random;
60 import java.util.Vector;
61 import org.apache.bcel.Constants;
62 import org.apache.bcel.Repository;
63 import org.apache.bcel.classfile.*;
64 import org.apache.bcel.generic.*;
65 import org.apache.bcel.verifier.*;
66 import org.apache.bcel.verifier.statics.*;
67 import org.apache.bcel.verifier.exc.*;
68
69 /***
70 * This PassVerifier verifies a method of class file according to pass 3,
71 * so-called structural verification as described in The Java Virtual Machine
72 * Specification, 2nd edition.
73 * More detailed information is to be found at the do_verify() method's
74 * documentation.
75 *
76 * @version $Id: Pass3bVerifier.java,v 1.3 2002/07/04 21:44:42 enver Exp $
77 * @author <A HREF="http://www.inf.fu-berlin.de/~ehaase"/>Enver Haase</A>
78 * @see #do_verify()
79 */
80
81 public final class Pass3bVerifier extends PassVerifier{
82 /* TODO: Throughout pass 3b, upper halves of LONG and DOUBLE
83 are represented by Type.UNKNOWN. This should be changed
84 in favour of LONG_Upper and DOUBLE_Upper as in pass 2. */
85
86 /***
87 * An InstructionContextQueue is a utility class that holds
88 * (InstructionContext, ArrayList) pairs in a Queue data structure.
89 * This is used to hold information about InstructionContext objects
90 * externally --- i.e. that information is not saved inside the
91 * InstructionContext object itself. This is useful to save the
92 * execution path of the symbolic execution of the
93 * Pass3bVerifier - this is not information
94 * that belongs into the InstructionContext object itself.
95 * Only at "execute()"ing
96 * time, an InstructionContext object will get the current information
97 * we have about its symbolic execution predecessors.
98 */
99 private static final class InstructionContextQueue{
100 private Vector ics = new Vector(); // Type: InstructionContext
101 private Vector ecs = new Vector(); // Type: ArrayList (of InstructionContext)
102 public void add(InstructionContext ic, ArrayList executionChain){
103 ics.add(ic);
104 ecs.add(executionChain);
105 }
106 public boolean isEmpty(){
107 return ics.isEmpty();
108 }
109 public void remove(){
110 this.remove(0);
111 }
112 public void remove(int i){
113 ics.remove(i);
114 ecs.remove(i);
115 }
116 public InstructionContext getIC(int i){
117 return (InstructionContext) ics.get(i);
118 }
119 public ArrayList getEC(int i){
120 return (ArrayList) ecs.get(i);
121 }
122 public int size(){
123 return ics.size();
124 }
125 } // end Inner Class InstructionContextQueue
126
127 /*** In DEBUG mode, the verification algorithm is not randomized. */
128 private static final boolean DEBUG = true;
129
130 /*** The Verifier that created this. */
131 private Verifier myOwner;
132
133 /*** The method number to verify. */
134 private int method_no;
135
136 /***
137 * This class should only be instantiated by a Verifier.
138 *
139 * @see org.apache.bcel.verifier.Verifier
140 */
141 public Pass3bVerifier(Verifier owner, int method_no){
142 myOwner = owner;
143 this.method_no = method_no;
144 }
145
146 /***
147 * Whenever the outgoing frame
148 * situation of an InstructionContext changes, all its successors are
149 * put [back] into the queue [as if they were unvisited].
150 * The proof of termination is about the existence of a
151 * fix point of frame merging.
152 */
153 private void circulationPump(ControlFlowGraph cfg, InstructionContext start, Frame vanillaFrame, InstConstraintVisitor icv, ExecutionVisitor ev){
154 final Random random = new Random();
155 InstructionContextQueue icq = new InstructionContextQueue();
156
157 start.execute(vanillaFrame, new ArrayList(), icv, ev); // new ArrayList() <=> no Instruction was executed before
158 // => Top-Level routine (no jsr call before)
159 icq.add(start, new ArrayList());
160
161 // LOOP!
162 while (!icq.isEmpty()){
163 InstructionContext u;
164 ArrayList ec;
165 if (!DEBUG){
166 int r = random.nextInt(icq.size());
167 u = icq.getIC(r);
168 ec = icq.getEC(r);
169 icq.remove(r);
170 }
171 else{
172 u = icq.getIC(0);
173 ec = icq.getEC(0);
174 icq.remove(0);
175 }
176
177 ArrayList oldchain = (ArrayList) (ec.clone());
178 ArrayList newchain = (ArrayList) (ec.clone());
179 newchain.add(u);
180
181 if ((u.getInstruction().getInstruction()) instanceof RET){
182 //System.err.println(u);
183 // We can only follow _one_ successor, the one after the
184 // JSR that was recently executed.
185 RET ret = (RET) (u.getInstruction().getInstruction());
186 ReturnaddressType t = (ReturnaddressType) u.getOutFrame(oldchain).getLocals().get(ret.getIndex());
187 InstructionContext theSuccessor = cfg.contextOf(t.getTarget());
188
189 // Sanity check
190 InstructionContext lastJSR = null;
191 int skip_jsr = 0;
192 for (int ss=oldchain.size()-1; ss >= 0; ss--){
193 if (skip_jsr < 0){
194 throw new AssertionViolatedException("More RET than JSR in execution chain?!");
195 }
196 //System.err.println("+"+oldchain.get(ss));
197 if (((InstructionContext) oldchain.get(ss)).getInstruction().getInstruction() instanceof JsrInstruction){
198 if (skip_jsr == 0){
199 lastJSR = (InstructionContext) oldchain.get(ss);
200 break;
201 }
202 else{
203 skip_jsr--;
204 }
205 }
206 if (((InstructionContext) oldchain.get(ss)).getInstruction().getInstruction() instanceof RET){
207 skip_jsr++;
208 }
209 }
210 if (lastJSR == null){
211 throw new AssertionViolatedException("RET without a JSR before in ExecutionChain?! EC: '"+oldchain+"'.");
212 }
213 JsrInstruction jsr = (JsrInstruction) (lastJSR.getInstruction().getInstruction());
214 if ( theSuccessor != (cfg.contextOf(jsr.physicalSuccessor())) ){
215 throw new AssertionViolatedException("RET '"+u.getInstruction()+"' info inconsistent: jump back to '"+theSuccessor+"' or '"+cfg.contextOf(jsr.physicalSuccessor())+"'?");
216 }
217
218 if (theSuccessor.execute(u.getOutFrame(oldchain), newchain, icv, ev)){
219 icq.add(theSuccessor, (ArrayList) newchain.clone());
220 }
221 }
222 else{// "not a ret"
223
224 // Normal successors. Add them to the queue of successors.
225 InstructionContext[] succs = u.getSuccessors();
226 for (int s=0; s<succs.length; s++){
227 InstructionContext v = succs[s];
228 if (v.execute(u.getOutFrame(oldchain), newchain, icv, ev)){
229 icq.add(v, (ArrayList) newchain.clone());
230 }
231 }
232 }// end "not a ret"
233
234 // Exception Handlers. Add them to the queue of successors.
235 // [subroutines are never protected; mandated by JustIce]
236 ExceptionHandler[] exc_hds = u.getExceptionHandlers();
237 for (int s=0; s<exc_hds.length; s++){
238 InstructionContext v = cfg.contextOf(exc_hds[s].getHandlerStart());
239 // TODO: the "oldchain" and "newchain" is used to determine the subroutine
240 // we're in (by searching for the last JSR) by the InstructionContext
241 // implementation. Therefore, we should not use this chain mechanism
242 // when dealing with exception handlers.
243 // Example: a JSR with an exception handler as its successor does not
244 // mean we're in a subroutine if we go to the exception handler.
245 // We should address this problem later; by now we simply "cut" the chain
246 // by using an empty chain for the exception handlers.
247 //if (v.execute(new Frame(u.getOutFrame(oldchain).getLocals(), new OperandStack (u.getOutFrame().getStack().maxStack(), (exc_hds[s].getExceptionType()==null? Type.THROWABLE : exc_hds[s].getExceptionType())) ), newchain), icv, ev){
248 //icq.add(v, (ArrayList) newchain.clone());
249 if (v.execute(new Frame(u.getOutFrame(oldchain).getLocals(), new OperandStack (u.getOutFrame(oldchain).getStack().maxStack(), (exc_hds[s].getExceptionType()==null? Type.THROWABLE : exc_hds[s].getExceptionType())) ), new ArrayList(), icv, ev)){
250 icq.add(v, new ArrayList());
251 }
252 }
253
254 }// while (!icq.isEmpty()) END
255
256 InstructionHandle ih = start.getInstruction();
257 do{
258 if ((ih.getInstruction() instanceof ReturnInstruction) && (!(cfg.isDead(ih)))) {
259 InstructionContext ic = cfg.contextOf(ih);
260 Frame f = ic.getOutFrame(new ArrayList()); // TODO: This is buggy, we check only the top-level return instructions this way. Maybe some maniac returns from a method when in a subroutine?
261 LocalVariables lvs = f.getLocals();
262 for (int i=0; i<lvs.maxLocals(); i++){
263 if (lvs.get(i) instanceof UninitializedObjectType){
264 this.addMessage("Warning: ReturnInstruction '"+ic+"' may leave method with an uninitialized object in the local variables array '"+lvs+"'.");
265 }
266 }
267 OperandStack os = f.getStack();
268 for (int i=0; i<os.size(); i++){
269 if (os.peek(i) instanceof UninitializedObjectType){
270 this.addMessage("Warning: ReturnInstruction '"+ic+"' may leave method with an uninitialized object on the operand stack '"+os+"'.");
271 }
272 }
273 }
274 }while ((ih = ih.getNext()) != null);
275
276 }
277
278 /***
279 * Pass 3b implements the data flow analysis as described in the Java Virtual
280 * Machine Specification, Second Edition.
281 * Later versions will use LocalVariablesInfo objects to verify if the
282 * verifier-inferred types and the class file's debug information (LocalVariables
283 * attributes) match [TODO].
284 *
285 * @see org.apache.bcel.verifier.statics.LocalVariablesInfo
286 * @see org.apache.bcel.verifier.statics.Pass2Verifier#getLocalVariablesInfo(int)
287 */
288 public VerificationResult do_verify(){
289 if (! myOwner.doPass3a(method_no).equals(VerificationResult.VR_OK)){
290 return VerificationResult.VR_NOTYET;
291 }
292
293 // Pass 3a ran before, so it's safe to assume the JavaClass object is
294 // in the BCEL repository.
295 JavaClass jc = Repository.lookupClass(myOwner.getClassName());
296
297 ConstantPoolGen constantPoolGen = new ConstantPoolGen(jc.getConstantPool());
298 // Init Visitors
299 InstConstraintVisitor icv = new InstConstraintVisitor();
300 icv.setConstantPoolGen(constantPoolGen);
301
302 ExecutionVisitor ev = new ExecutionVisitor();
303 ev.setConstantPoolGen(constantPoolGen);
304
305 Method[] methods = jc.getMethods(); // Method no "method_no" exists, we ran Pass3a before on it!
306
307 try{
308
309 MethodGen mg = new MethodGen(methods[method_no], myOwner.getClassName(), constantPoolGen);
310
311 icv.setMethodGen(mg);
312
313 ////////////// DFA BEGINS HERE ////////////////
314 if (! (mg.isAbstract() || mg.isNative()) ){ // IF mg HAS CODE (See pass 2)
315
316 ControlFlowGraph cfg = new ControlFlowGraph(mg);
317
318 // Build the initial frame situation for this method.
319 Frame f = new Frame(mg.getMaxLocals(),mg.getMaxStack());
320 if ( !mg.isStatic() ){
321 if (mg.getName().equals(Constants.CONSTRUCTOR_NAME)){
322 f._this = new UninitializedObjectType(new ObjectType(jc.getClassName()));
323 f.getLocals().set(0, f._this);
324 }
325 else{
326 f._this = null;
327 f.getLocals().set(0, new ObjectType(jc.getClassName()));
328 }
329 }
330 Type[] argtypes = mg.getArgumentTypes();
331 int twoslotoffset = 0;
332 for (int j=0; j<argtypes.length; j++){
333 if (argtypes[j] == Type.SHORT || argtypes[j] == Type.BYTE || argtypes[j] == Type.CHAR || argtypes[j] == Type.BOOLEAN){
334 argtypes[j] = Type.INT;
335 }
336 f.getLocals().set(twoslotoffset + j + (mg.isStatic()?0:1), argtypes[j]);
337 if (argtypes[j].getSize() == 2){
338 twoslotoffset++;
339 f.getLocals().set(twoslotoffset + j + (mg.isStatic()?0:1), Type.UNKNOWN);
340 }
341 }
342 circulationPump(cfg, cfg.contextOf(mg.getInstructionList().getStart()), f, icv, ev);
343 }
344 }
345 catch (VerifierConstraintViolatedException ce){
346 ce.extendMessage("Constraint violated in method '"+methods[method_no]+"':\n","");
347 return new VerificationResult(VerificationResult.VERIFIED_REJECTED, ce.getMessage());
348 }
349 catch (RuntimeException re){
350 // These are internal errors
351
352 StringWriter sw = new StringWriter();
353 PrintWriter pw = new PrintWriter(sw);
354 re.printStackTrace(pw);
355
356 throw new AssertionViolatedException("Some RuntimeException occured while verify()ing class '"+jc.getClassName()+"', method '"+methods[method_no]+"'. Original RuntimeException's stack trace:\n---\n"+sw+"---\n");
357 }
358 return VerificationResult.VR_OK;
359 }
360
361 /*** Returns the method number as supplied when instantiating. */
362 public int getMethodNo(){
363 return method_no;
364 }
365 }
This page was automatically generated by Maven