001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 *  Unless required by applicable law or agreed to in writing, software
012 *  distributed under the License is distributed on an "AS IS" BASIS,
013 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 *  See the License for the specific language governing permissions and
015 *  limitations under the License.
016 *
017 */
018package org.apache.bcel.verifier.structurals;
019
020
021import java.io.PrintWriter;
022import java.io.StringWriter;
023import java.util.ArrayList;
024import java.util.List;
025import java.util.Random;
026import java.util.Vector;
027
028import org.apache.bcel.Const;
029import org.apache.bcel.Repository;
030import org.apache.bcel.classfile.JavaClass;
031import org.apache.bcel.classfile.Method;
032import org.apache.bcel.generic.ConstantPoolGen;
033import org.apache.bcel.generic.InstructionHandle;
034import org.apache.bcel.generic.JsrInstruction;
035import org.apache.bcel.generic.MethodGen;
036import org.apache.bcel.generic.ObjectType;
037import org.apache.bcel.generic.RET;
038import org.apache.bcel.generic.ReferenceType;
039import org.apache.bcel.generic.ReturnInstruction;
040import org.apache.bcel.generic.ReturnaddressType;
041import org.apache.bcel.generic.Type;
042import org.apache.bcel.verifier.PassVerifier;
043import org.apache.bcel.verifier.VerificationResult;
044import org.apache.bcel.verifier.Verifier;
045import org.apache.bcel.verifier.exc.AssertionViolatedException;
046import org.apache.bcel.verifier.exc.StructuralCodeConstraintException;
047import org.apache.bcel.verifier.exc.VerifierConstraintViolatedException;
048
049/**
050 * This PassVerifier verifies a method of class file according to pass 3,
051 * so-called structural verification as described in The Java Virtual Machine
052 * Specification, 2nd edition.
053 * More detailed information is to be found at the do_verify() method's
054 * documentation.
055 *
056 * @see #do_verify()
057 */
058
059public final class Pass3bVerifier extends PassVerifier{
060    /* TODO:    Throughout pass 3b, upper halves of LONG and DOUBLE
061                        are represented by Type.UNKNOWN. This should be changed
062                        in favour of LONG_Upper and DOUBLE_Upper as in pass 2. */
063
064    /**
065     * An InstructionContextQueue is a utility class that holds
066     * (InstructionContext, ArrayList) pairs in a Queue data structure.
067     * This is used to hold information about InstructionContext objects
068     * externally --- i.e. that information is not saved inside the
069     * InstructionContext object itself. This is useful to save the
070     * execution path of the symbolic execution of the
071     * Pass3bVerifier - this is not information
072     * that belongs into the InstructionContext object itself.
073     * Only at "execute()"ing
074     * time, an InstructionContext object will get the current information
075     * we have about its symbolic execution predecessors.
076     */
077    private static final class InstructionContextQueue{
078        private final List<InstructionContext> ics = new Vector<>();
079        private final List<ArrayList<InstructionContext>> ecs = new Vector<>();
080        public void add(final InstructionContext ic, final ArrayList<InstructionContext> executionChain) {
081            ics.add(ic);
082            ecs.add(executionChain);
083        }
084        public boolean isEmpty() {
085            return ics.isEmpty();
086        }
087        public void remove(final int i) {
088            ics.remove(i);
089            ecs.remove(i);
090        }
091        public InstructionContext getIC(final int i) {
092            return ics.get(i);
093        }
094        public ArrayList<InstructionContext> getEC(final int i) {
095            return ecs.get(i);
096        }
097        public int size() {
098            return ics.size();
099        }
100    } // end Inner Class InstructionContextQueue
101
102    /** In DEBUG mode, the verification algorithm is not randomized. */
103    private static final boolean DEBUG = true;
104
105    /** The Verifier that created this. */
106    private final Verifier myOwner;
107
108    /** The method number to verify. */
109    private final int method_no;
110
111    /**
112     * This class should only be instantiated by a Verifier.
113     *
114     * @see org.apache.bcel.verifier.Verifier
115     */
116    public Pass3bVerifier(final Verifier owner, final int method_no) {
117        myOwner = owner;
118        this.method_no = method_no;
119    }
120
121    /**
122     * Whenever the outgoing frame
123     * situation of an InstructionContext changes, all its successors are
124     * put [back] into the queue [as if they were unvisited].
125   * The proof of termination is about the existence of a
126   * fix point of frame merging.
127     */
128    private void circulationPump(final MethodGen m,final ControlFlowGraph cfg, final InstructionContext start,
129            final Frame vanillaFrame, final InstConstraintVisitor icv, final ExecutionVisitor ev) {
130        final Random random = new Random();
131        final InstructionContextQueue icq = new InstructionContextQueue();
132
133        start.execute(vanillaFrame, new ArrayList<InstructionContext>(), icv, ev);
134        // new ArrayList() <=>    no Instruction was executed before
135        //                                    => Top-Level routine (no jsr call before)
136        icq.add(start, new ArrayList<InstructionContext>());
137
138        // LOOP!
139        while (!icq.isEmpty()) {
140            InstructionContext u;
141            ArrayList<InstructionContext> ec;
142            if (!DEBUG) {
143                final int r = random.nextInt(icq.size());
144                u = icq.getIC(r);
145                ec = icq.getEC(r);
146                icq.remove(r);
147            }
148            else{
149                u  = icq.getIC(0);
150                ec = icq.getEC(0);
151                icq.remove(0);
152            }
153
154            @SuppressWarnings("unchecked") // ec is of type ArrayList<InstructionContext>
155            final
156            ArrayList<InstructionContext> oldchain = (ArrayList<InstructionContext>) (ec.clone());
157            @SuppressWarnings("unchecked") // ec is of type ArrayList<InstructionContext>
158            final
159            ArrayList<InstructionContext> newchain = (ArrayList<InstructionContext>) (ec.clone());
160            newchain.add(u);
161
162            if ((u.getInstruction().getInstruction()) instanceof RET) {
163//System.err.println(u);
164                // We can only follow _one_ successor, the one after the
165                // JSR that was recently executed.
166                final RET ret = (RET) (u.getInstruction().getInstruction());
167                final ReturnaddressType t = (ReturnaddressType) u.getOutFrame(oldchain).getLocals().get(ret.getIndex());
168                final InstructionContext theSuccessor = cfg.contextOf(t.getTarget());
169
170                // Sanity check
171                InstructionContext lastJSR = null;
172                int skip_jsr = 0;
173                for (int ss=oldchain.size()-1; ss >= 0; ss--) {
174                    if (skip_jsr < 0) {
175                        throw new AssertionViolatedException("More RET than JSR in execution chain?!");
176                    }
177//System.err.println("+"+oldchain.get(ss));
178                    if ((oldchain.get(ss)).getInstruction().getInstruction() instanceof JsrInstruction) {
179                        if (skip_jsr == 0) {
180                            lastJSR = oldchain.get(ss);
181                            break;
182                        }
183                        skip_jsr--;
184                    }
185                    if ((oldchain.get(ss)).getInstruction().getInstruction() instanceof RET) {
186                        skip_jsr++;
187                    }
188                }
189                if (lastJSR == null) {
190                    throw new AssertionViolatedException("RET without a JSR before in ExecutionChain?! EC: '"+oldchain+"'.");
191                }
192                final JsrInstruction jsr = (JsrInstruction) (lastJSR.getInstruction().getInstruction());
193                if ( theSuccessor != (cfg.contextOf(jsr.physicalSuccessor())) ) {
194                    throw new AssertionViolatedException("RET '"+u.getInstruction()+"' info inconsistent: jump back to '"+
195                        theSuccessor+"' or '"+cfg.contextOf(jsr.physicalSuccessor())+"'?");
196                }
197
198                if (theSuccessor.execute(u.getOutFrame(oldchain), newchain, icv, ev)) {
199                    @SuppressWarnings("unchecked") // newchain is already of type ArrayList<InstructionContext>
200                    final
201                    ArrayList<InstructionContext> newchainClone = (ArrayList<InstructionContext>) newchain.clone();
202                    icq.add(theSuccessor, newchainClone);
203                }
204            }
205            else{// "not a ret"
206
207                // Normal successors. Add them to the queue of successors.
208                final InstructionContext[] succs = u.getSuccessors();
209                for (final InstructionContext v : succs) {
210                    if (v.execute(u.getOutFrame(oldchain), newchain, icv, ev)) {
211                        @SuppressWarnings("unchecked") // newchain is already of type ArrayList<InstructionContext>
212                        final
213                        ArrayList<InstructionContext> newchainClone = (ArrayList<InstructionContext>) newchain.clone();
214                        icq.add(v, newchainClone);
215                    }
216                }
217            }// end "not a ret"
218
219            // Exception Handlers. Add them to the queue of successors.
220            // [subroutines are never protected; mandated by JustIce]
221            final ExceptionHandler[] exc_hds = u.getExceptionHandlers();
222            for (final ExceptionHandler exc_hd : exc_hds) {
223                final InstructionContext v = cfg.contextOf(exc_hd.getHandlerStart());
224                // TODO: the "oldchain" and "newchain" is used to determine the subroutine
225                // we're in (by searching for the last JSR) by the InstructionContext
226                // implementation. Therefore, we should not use this chain mechanism
227                // when dealing with exception handlers.
228                // Example: a JSR with an exception handler as its successor does not
229                // mean we're in a subroutine if we go to the exception handler.
230                // We should address this problem later; by now we simply "cut" the chain
231                // by using an empty chain for the exception handlers.
232                //if (v.execute(new Frame(u.getOutFrame(oldchain).getLocals(),
233                // new OperandStack (u.getOutFrame().getStack().maxStack(),
234                // (exc_hds[s].getExceptionType()==null? Type.THROWABLE : exc_hds[s].getExceptionType())) ), newchain), icv, ev) {
235                    //icq.add(v, (ArrayList) newchain.clone());
236                if (v.execute(new Frame(u.getOutFrame(oldchain).getLocals(),
237                        new OperandStack (u.getOutFrame(oldchain).getStack().maxStack(),
238                        exc_hd.getExceptionType()==null? Type.THROWABLE : exc_hd.getExceptionType())),
239                        new ArrayList<InstructionContext>(), icv, ev)) {
240                    icq.add(v, new ArrayList<InstructionContext>());
241                }
242            }
243
244        }// while (!icq.isEmpty()) END
245
246        InstructionHandle ih = start.getInstruction();
247        do{
248            if ((ih.getInstruction() instanceof ReturnInstruction) && (!(cfg.isDead(ih)))) {
249                final InstructionContext ic = cfg.contextOf(ih);
250                // TODO: This is buggy, we check only the top-level return instructions this way.
251                // Maybe some maniac returns from a method when in a subroutine?
252                final Frame f = ic.getOutFrame(new ArrayList<InstructionContext>());
253                final LocalVariables lvs = f.getLocals();
254                for (int i=0; i<lvs.maxLocals(); i++) {
255                    if (lvs.get(i) instanceof UninitializedObjectType) {
256                        this.addMessage("Warning: ReturnInstruction '"+ic+
257                            "' may leave method with an uninitialized object in the local variables array '"+lvs+"'.");
258                    }
259                }
260                final OperandStack os = f.getStack();
261                for (int i=0; i<os.size(); i++) {
262                    if (os.peek(i) instanceof UninitializedObjectType) {
263                        this.addMessage("Warning: ReturnInstruction '"+ic+
264                            "' may leave method with an uninitialized object on the operand stack '"+os+"'.");
265                    }
266                }
267                //see JVM $4.8.2
268                Type returnedType = null;
269                final OperandStack inStack = ic.getInFrame().getStack();
270                if (inStack.size() >= 1) {
271                    returnedType = inStack.peek();
272                } else {
273                    returnedType = Type.VOID;
274                }
275
276                if (returnedType != null) {
277                    if (returnedType instanceof ReferenceType) {
278                        try {
279                            if (!((ReferenceType) returnedType).isCastableTo(m.getReturnType())) {
280                                invalidReturnTypeError(returnedType, m);
281                            }
282                        } catch (final ClassNotFoundException e) {
283                            // Don't know what do do now, so raise RuntimeException
284                            throw new RuntimeException(e);
285                        }
286                    } else if (!returnedType.equals(m.getReturnType().normalizeForStackOrLocal())) {
287                        invalidReturnTypeError(returnedType, m);
288                    }
289                }
290            }
291        } while ((ih = ih.getNext()) != null);
292
293     }
294
295    /**
296     * Throws an exception indicating the returned type is not compatible with the return type of the given method
297     * @throws StructuralCodeConstraintException always
298     * @since 6.0
299     */
300    public void invalidReturnTypeError(final Type returnedType, final MethodGen m) {
301        throw new StructuralCodeConstraintException(
302            "Returned type "+returnedType+" does not match Method's return type "+m.getReturnType());
303    }
304
305    /**
306     * Pass 3b implements the data flow analysis as described in the Java Virtual
307     * Machine Specification, Second Edition.
308      * Later versions will use LocalVariablesInfo objects to verify if the
309      * verifier-inferred types and the class file's debug information (LocalVariables
310      * attributes) match [TODO].
311      *
312      * @see org.apache.bcel.verifier.statics.LocalVariablesInfo
313      * @see org.apache.bcel.verifier.statics.Pass2Verifier#getLocalVariablesInfo(int)
314      */
315    @Override
316    public VerificationResult do_verify() {
317        if (! myOwner.doPass3a(method_no).equals(VerificationResult.VR_OK)) {
318            return VerificationResult.VR_NOTYET;
319        }
320
321        // Pass 3a ran before, so it's safe to assume the JavaClass object is
322        // in the BCEL repository.
323        JavaClass jc;
324        try {
325            jc = Repository.lookupClass(myOwner.getClassName());
326        } catch (final ClassNotFoundException e) {
327            // FIXME: maybe not the best way to handle this
328            throw new AssertionViolatedException("Missing class: " + e, e);
329        }
330
331        final ConstantPoolGen constantPoolGen = new ConstantPoolGen(jc.getConstantPool());
332        // Init Visitors
333        final InstConstraintVisitor icv = new InstConstraintVisitor();
334        icv.setConstantPoolGen(constantPoolGen);
335
336        final ExecutionVisitor ev = new ExecutionVisitor();
337        ev.setConstantPoolGen(constantPoolGen);
338
339        final Method[] methods = jc.getMethods(); // Method no "method_no" exists, we ran Pass3a before on it!
340
341        try{
342
343            final MethodGen mg = new MethodGen(methods[method_no], myOwner.getClassName(), constantPoolGen);
344
345            icv.setMethodGen(mg);
346
347            ////////////// DFA BEGINS HERE ////////////////
348            if (! (mg.isAbstract() || mg.isNative()) ) { // IF mg HAS CODE (See pass 2)
349
350                final ControlFlowGraph cfg = new ControlFlowGraph(mg);
351
352                // Build the initial frame situation for this method.
353                final Frame f = new Frame(mg.getMaxLocals(),mg.getMaxStack());
354                if ( !mg.isStatic() ) {
355                    if (mg.getName().equals(Const.CONSTRUCTOR_NAME)) {
356                        Frame.setThis(new UninitializedObjectType(ObjectType.getInstance(jc.getClassName())));
357                        f.getLocals().set(0, Frame.getThis());
358                    }
359                    else{
360                        Frame.setThis(null);
361                        f.getLocals().set(0, ObjectType.getInstance(jc.getClassName()));
362                    }
363                }
364                final Type[] argtypes = mg.getArgumentTypes();
365                int twoslotoffset = 0;
366                for (int j=0; j<argtypes.length; j++) {
367                    if (argtypes[j] == Type.SHORT || argtypes[j] == Type.BYTE ||
368                        argtypes[j] == Type.CHAR || argtypes[j] == Type.BOOLEAN) {
369                        argtypes[j] = Type.INT;
370                    }
371                    f.getLocals().set(twoslotoffset + j + (mg.isStatic()?0:1), argtypes[j]);
372                    if (argtypes[j].getSize() == 2) {
373                        twoslotoffset++;
374                        f.getLocals().set(twoslotoffset + j + (mg.isStatic()?0:1), Type.UNKNOWN);
375                    }
376                }
377                circulationPump(mg,cfg, cfg.contextOf(mg.getInstructionList().getStart()), f, icv, ev);
378            }
379        }
380        catch (final VerifierConstraintViolatedException ce) {
381            ce.extendMessage("Constraint violated in method '"+methods[method_no]+"':\n","");
382            return new VerificationResult(VerificationResult.VERIFIED_REJECTED, ce.getMessage());
383        }
384        catch (final RuntimeException re) {
385            // These are internal errors
386
387            final StringWriter sw = new StringWriter();
388            final PrintWriter pw = new PrintWriter(sw);
389            re.printStackTrace(pw);
390
391            throw new AssertionViolatedException("Some RuntimeException occured while verify()ing class '"+jc.getClassName()+
392                "', method '"+methods[method_no]+"'. Original RuntimeException's stack trace:\n---\n"+sw+"---\n", re);
393        }
394        return VerificationResult.VR_OK;
395    }
396
397    /** Returns the method number as supplied when instantiating. */
398    public int getMethodNo() {
399        return method_no;
400    }
401}