KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > sun > org > apache > bcel > internal > verifier > structurals > Pass3bVerifier


1 package com.sun.org.apache.bcel.internal.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 JavaDoc;
59 import java.util.Iterator JavaDoc;
60 import java.util.Random JavaDoc;
61 import java.util.Vector JavaDoc;
62 import com.sun.org.apache.bcel.internal.Constants;
63 import com.sun.org.apache.bcel.internal.Repository;
64 import com.sun.org.apache.bcel.internal.classfile.*;
65 import com.sun.org.apache.bcel.internal.generic.*;
66 import com.sun.org.apache.bcel.internal.verifier.*;
67 import com.sun.org.apache.bcel.internal.verifier.statics.*;
68 import com.sun.org.apache.bcel.internal.verifier.exc.*;
69
70 /**
71  * This PassVerifier verifies a method of class file according to pass 3,
72  * so-called structural verification as described in The Java Virtual Machine
73  * Specification, 2nd edition.
74  * More detailed information is to be found at the do_verify() method's
75  * documentation.
76  *
77  * @version $Id: Pass3bVerifier.java,v 1.1.1.1 2001/10/29 20:00:42 jvanzyl Exp $
78  * @author <A HREF="http://www.inf.fu-berlin.de/~ehaase"/>Enver Haase</A>
79  * @see #do_verify()
80  */

81
82 public final class Pass3bVerifier extends PassVerifier{
83     /* TODO: Throughout pass 3b, upper halves of LONG and DOUBLE
84                         are represented by Type.UNKNOWN. This should be changed
85                         in favour of LONG_Upper and DOUBLE_Upper as in pass 2. */

86
87     /**
88      * An InstructionContextQueue is a utility class that holds
89      * (InstructionContext, ArrayList) pairs in a Queue data structure.
90      * This is used to hold information about InstructionContext objects
91      * externally --- i.e. that information is not saved inside the
92      * InstructionContext object itself. This is useful to save the
93      * execution path of the symbolic execution of the
94      * Pass3bVerifier - this is not information
95      * that belongs into the InstructionContext object itself.
96      * Only at "execute()"ing
97      * time, an InstructionContext object will get the current information
98      * we have about its symbolic execution predecessors.
99      */

100     private static final class InstructionContextQueue{
101         private Vector JavaDoc ics = new Vector JavaDoc(); // Type: InstructionContext
102
private Vector JavaDoc ecs = new Vector JavaDoc(); // Type: ArrayList (of InstructionContext)
103
public void add(InstructionContext ic, ArrayList JavaDoc executionChain){
104             ics.add(ic);
105             ecs.add(executionChain);
106         }
107         public boolean isEmpty(){
108             return ics.isEmpty();
109         }
110         public void remove(){
111             this.remove(0);
112         }
113         public void remove(int i){
114             ics.remove(i);
115             ecs.remove(i);
116         }
117         public InstructionContext getIC(int i){
118             return (InstructionContext) ics.get(i);
119         }
120         public ArrayList JavaDoc getEC(int i){
121             return (ArrayList JavaDoc) ecs.get(i);
122         }
123         public int size(){
124             return ics.size();
125         }
126     } // end Inner Class InstructionContextQueue
127

128     /** In DEBUG mode, the verification algorithm is not randomized. */
129     private static final boolean DEBUG = true;
130
131     /** The Verifier that created this. */
132     private Verifier myOwner;
133
134     /** The method number to verify. */
135     private int method_no;
136
137     /**
138      * This class should only be instantiated by a Verifier.
139      *
140      * @see com.sun.org.apache.bcel.internal.verifier.Verifier
141      */

142     public Pass3bVerifier(Verifier owner, int method_no){
143         myOwner = owner;
144         this.method_no = method_no;
145     }
146
147     /**
148      * Whenever the outgoing frame
149      * situation of an InstructionContext changes, all its successors are
150      * put [back] into the queue [as if they were unvisited].
151    * The proof of termination is about the existence of a
152    * fix point of frame merging.
153      */

154     private void circulationPump(ControlFlowGraph cfg, InstructionContext start, Frame vanillaFrame, InstConstraintVisitor icv, ExecutionVisitor ev){
155         final Random JavaDoc random = new Random JavaDoc();
156         InstructionContextQueue icq = new InstructionContextQueue();
157         
158         start.execute(vanillaFrame, new ArrayList JavaDoc(), icv, ev); // new ArrayList() <=> no Instruction was executed before
159
// => Top-Level routine (no jsr call before)
160
icq.add(start, new ArrayList JavaDoc());
161
162         // LOOP!
163
while (!icq.isEmpty()){
164             InstructionContext u;
165             ArrayList JavaDoc ec;
166             if (!DEBUG){
167                 int r = random.nextInt(icq.size());
168                 u = icq.getIC(r);
169                 ec = icq.getEC(r);
170                 icq.remove(r);
171             }
172             else{
173                 u = icq.getIC(0);
174                 ec = icq.getEC(0);
175                 icq.remove(0);
176             }
177             
178             ArrayList JavaDoc oldchain = (ArrayList JavaDoc) (ec.clone());
179             ArrayList JavaDoc newchain = (ArrayList JavaDoc) (ec.clone());
180             newchain.add(u);
181
182             if ((u.getInstruction().getInstruction()) instanceof RET){
183 //System.err.println(u);
184
// We can only follow _one_ successor, the one after the
185
// JSR that was recently executed.
186
RET ret = (RET) (u.getInstruction().getInstruction());
187                 ReturnaddressType t = (ReturnaddressType) u.getOutFrame(oldchain).getLocals().get(ret.getIndex());
188                 InstructionContext theSuccessor = cfg.contextOf(t.getTarget());
189
190                 // Sanity check
191
InstructionContext lastJSR = null;
192                 int skip_jsr = 0;
193                 for (int ss=oldchain.size()-1; ss >= 0; ss--){
194                     if (skip_jsr < 0){
195                         throw new AssertionViolatedException("More RET than JSR in execution chain?!");
196                     }
197 //System.err.println("+"+oldchain.get(ss));
198
if (((InstructionContext) oldchain.get(ss)).getInstruction().getInstruction() instanceof JsrInstruction){
199                         if (skip_jsr == 0){
200                             lastJSR = (InstructionContext) oldchain.get(ss);
201                             break;
202                         }
203                         else{
204                             skip_jsr--;
205                         }
206                     }
207                     if (((InstructionContext) oldchain.get(ss)).getInstruction().getInstruction() instanceof RET){
208                         skip_jsr++;
209                     }
210                 }
211                 if (lastJSR == null){
212                     throw new AssertionViolatedException("RET without a JSR before in ExecutionChain?! EC: '"+oldchain+"'.");
213                 }
214                 JsrInstruction jsr = (JsrInstruction) (lastJSR.getInstruction().getInstruction());
215                 if ( theSuccessor != (cfg.contextOf(jsr.physicalSuccessor())) ){
216                     throw new AssertionViolatedException("RET '"+u.getInstruction()+"' info inconsistent: jump back to '"+theSuccessor+"' or '"+cfg.contextOf(jsr.physicalSuccessor())+"'?");
217                 }
218                 
219                 if (theSuccessor.execute(u.getOutFrame(oldchain), newchain, icv, ev)){
220                     icq.add(theSuccessor, (ArrayList JavaDoc) newchain.clone());
221                 }
222             }
223             else{// "not a ret"
224

225                 // Normal successors. Add them to the queue of successors.
226
InstructionContext[] succs = u.getSuccessors();
227                 for (int s=0; s<succs.length; s++){
228                     InstructionContext v = succs[s];
229                     if (v.execute(u.getOutFrame(oldchain), newchain, icv, ev)){
230                         icq.add(v, (ArrayList JavaDoc) newchain.clone());
231                     }
232                 }
233             }// end "not a ret"
234

235             // Exception Handlers. Add them to the queue of successors.
236
// [subroutines are never protected; mandated by JustIce]
237
ExceptionHandler[] exc_hds = u.getExceptionHandlers();
238             for (int s=0; s<exc_hds.length; s++){
239                 InstructionContext v = cfg.contextOf(exc_hds[s].getHandlerStart());
240                 // TODO: the "oldchain" and "newchain" is used to determine the subroutine
241
// we're in (by searching for the last JSR) by the InstructionContext
242
// implementation. Therefore, we should not use this chain mechanism
243
// when dealing with exception handlers.
244
// Example: a JSR with an exception handler as its successor does not
245
// mean we're in a subroutine if we go to the exception handler.
246
// We should address this problem later; by now we simply "cut" the chain
247
// by using an empty chain for the exception handlers.
248
//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){
249
//icq.add(v, (ArrayList) newchain.clone());
250
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 JavaDoc(), icv, ev)){
251                     icq.add(v, new ArrayList JavaDoc());
252                 }
253             }
254
255         }// while (!icq.isEmpty()) END
256

257         InstructionHandle ih = start.getInstruction();
258         do{
259             if ((ih.getInstruction() instanceof ReturnInstruction) && (!(cfg.isDead(ih)))) {
260                 InstructionContext ic = cfg.contextOf(ih);
261                 Frame f = ic.getOutFrame(new ArrayList JavaDoc()); // TODO: This is buggy, we check only the top-level return instructions this way.
262
LocalVariables lvs = f.getLocals();
263                 for (int i=0; i<lvs.maxLocals(); i++){
264                     if (lvs.get(i) instanceof UninitializedObjectType){
265                         this.addMessage("Warning: ReturnInstruction '"+ic+"' may leave method with an uninitialized object in the local variables array '"+lvs+"'.");
266                     }
267                 }
268                 OperandStack os = f.getStack();
269                 for (int i=0; i<os.size(); i++){
270                     if (os.peek(i) instanceof UninitializedObjectType){
271                         this.addMessage("Warning: ReturnInstruction '"+ic+"' may leave method with an uninitialized object on the operand stack '"+os+"'.");
272                     }
273                 }
274             }
275         }while ((ih = ih.getNext()) != null);
276         
277     }
278
279     /**
280      * Pass 3b implements the data flow analysis as described in the Java Virtual
281      * Machine Specification, Second Edition.
282      * Later versions will use LocalVariablesInfo objects to verify if the
283      * verifier-inferred types and the class file's debug information (LocalVariables
284      * attributes) match [TODO].
285      *
286      * @see com.sun.org.apache.bcel.internal.verifier.statics.LocalVariablesInfo
287      * @see com.sun.org.apache.bcel.internal.verifier.statics.Pass2Verifier#getLocalVariablesInfo(int)
288      */

289     public VerificationResult do_verify(){
290         if (! myOwner.doPass3a(method_no).equals(VerificationResult.VR_OK)){
291             return VerificationResult.VR_NOTYET;
292         }
293
294         // Pass 3a ran before, so it's safe to assume the JavaClass object is
295
// in the BCEL repository.
296
JavaClass jc = Repository.lookupClass(myOwner.getClassName());
297
298         ConstantPoolGen constantPoolGen = new ConstantPoolGen(jc.getConstantPool());
299         // Init Visitors
300
InstConstraintVisitor icv = new InstConstraintVisitor();
301         icv.setConstantPoolGen(constantPoolGen);
302         
303         ExecutionVisitor ev = new ExecutionVisitor();
304         ev.setConstantPoolGen(constantPoolGen);
305         
306         Method[] methods = jc.getMethods(); // Method no "method_no" exists, we ran Pass3a before on it!
307

308         try{
309
310             MethodGen mg = new MethodGen(methods[method_no], myOwner.getClassName(), constantPoolGen);
311
312             icv.setMethodGen(mg);
313                 
314             ////////////// DFA BEGINS HERE ////////////////
315
if (! (mg.isAbstract() || mg.isNative()) ){ // IF mg HAS CODE (See pass 2)
316

317                 ControlFlowGraph cfg = new ControlFlowGraph(mg);
318
319                 // Build the initial frame situation for this method.
320
Frame f = new Frame(mg.getMaxLocals(),mg.getMaxStack());
321                 if ( !mg.isStatic() ){
322                     if (mg.getName().equals(Constants.CONSTRUCTOR_NAME)){
323                         f._this = new UninitializedObjectType(new ObjectType(jc.getClassName()));
324                         f.getLocals().set(0, f._this);
325                     }
326                     else{
327                         f._this = null;
328                         f.getLocals().set(0, new ObjectType(jc.getClassName()));
329                     }
330                 }
331                 Type[] argtypes = mg.getArgumentTypes();
332                 int twoslotoffset = 0;
333                 for (int j=0; j<argtypes.length; j++){
334                     if (argtypes[j] == Type.SHORT || argtypes[j] == Type.BYTE || argtypes[j] == Type.CHAR || argtypes[j] == Type.BOOLEAN){
335                         argtypes[j] = Type.INT;
336                     }
337                     f.getLocals().set(twoslotoffset + j + (mg.isStatic()?0:1), argtypes[j]);
338                     if (argtypes[j].getSize() == 2){
339                         twoslotoffset++;
340                         f.getLocals().set(twoslotoffset + j + (mg.isStatic()?0:1), Type.UNKNOWN);
341                     }
342                 }
343                 circulationPump(cfg, cfg.contextOf(mg.getInstructionList().getStart()), f, icv, ev);
344             }
345         }
346         catch (VerifierConstraintViolatedException ce){
347             ce.extendMessage("Constraint violated in method '"+methods[method_no]+"':\n","");
348             return new VerificationResult(VerificationResult.VERIFIED_REJECTED, ce.getMessage());
349         }
350         catch (RuntimeException JavaDoc re){
351             // These are internal errors
352

353             StringWriter sw = new StringWriter();
354             PrintWriter pw = new PrintWriter(sw);
355             re.printStackTrace(pw);
356
357             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");
358         }
359         return VerificationResult.VR_OK;
360     }
361
362     /** Returns the method number as supplied when instantiating. */
363     public int getMethodNo(){
364         return method_no;
365     }
366 }
367
Popular Tags