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
020import java.util.ArrayList;
021import java.util.Arrays;
022import java.util.HashMap;
023import java.util.List;
024import java.util.Map;
025
026import org.apache.bcel.generic.ATHROW;
027import org.apache.bcel.generic.BranchInstruction;
028import org.apache.bcel.generic.GotoInstruction;
029import org.apache.bcel.generic.Instruction;
030import org.apache.bcel.generic.InstructionHandle;
031import org.apache.bcel.generic.JsrInstruction;
032import org.apache.bcel.generic.MethodGen;
033import org.apache.bcel.generic.RET;
034import org.apache.bcel.generic.ReturnInstruction;
035import org.apache.bcel.generic.Select;
036import org.apache.bcel.verifier.exc.AssertionViolatedException;
037import org.apache.bcel.verifier.exc.StructuralCodeConstraintException;
038
039/**
040 * This class represents a control flow graph of a method.
041 *
042 */
043public class ControlFlowGraph {
044
045    /**
046     * Objects of this class represent a node in a ControlFlowGraph. These nodes are instructions, not basic blocks.
047     */
048    private class InstructionContextImpl implements InstructionContext {
049
050        /**
051         * The TAG field is here for external temporary flagging, such as graph colouring.
052         *
053         * @see #getTag()
054         * @see #setTag(int)
055         */
056        private int TAG;
057
058        /**
059         * The InstructionHandle this InstructionContext is wrapped around.
060         */
061        private final InstructionHandle instruction;
062
063        /**
064         * The 'incoming' execution Frames.
065         */
066        private final Map<InstructionContext, Frame> inFrames; // key: the last-executed JSR
067
068        /**
069         * The 'outgoing' execution Frames.
070         */
071        private final Map<InstructionContext, Frame> outFrames; // key: the last-executed JSR
072
073        /**
074         * The 'execution predecessors' - a list of type InstructionContext of those instances that have been execute()d before
075         * in that order.
076         */
077        private List<InstructionContext> executionPredecessors; // Type: InstructionContext
078
079        /**
080         * Creates an InstructionHandleImpl object from an InstructionHandle. Creation of one per InstructionHandle suffices.
081         * Don't create more.
082         */
083        public InstructionContextImpl(final InstructionHandle inst) {
084            if (inst == null) {
085                throw new AssertionViolatedException("Cannot instantiate InstructionContextImpl from NULL.");
086            }
087
088            instruction = inst;
089            inFrames = new HashMap<>();
090            outFrames = new HashMap<>();
091        }
092
093        /**
094         * A utility method that calculates the successors of a given InstructionHandle That means, a RET does have successors
095         * as defined here. A JsrInstruction has its target as its successor (opposed to its physical successor) as defined
096         * here.
097         */
098// TODO: implement caching!
099        private InstructionHandle[] _getSuccessors() {
100            final InstructionHandle[] single = new InstructionHandle[1];
101
102            final Instruction inst = getInstruction().getInstruction();
103
104            if (inst instanceof RET) {
105                final Subroutine s = subroutines.subroutineOf(getInstruction());
106                if (s == null) { // return empty;
107                    // RET in dead code. "empty" would be the correct answer, but we know something about the surrounding project...
108                    throw new AssertionViolatedException("Asking for successors of a RET in dead code?!");
109                }
110
111//TODO: remove. Only JustIce must not use it, but foreign users of the ControlFlowGraph
112//      will want it. Thanks Johannes Wust.
113//throw new AssertionViolatedException("DID YOU REALLY WANT TO ASK FOR RET'S SUCCS?");
114
115                final InstructionHandle[] jsrs = s.getEnteringJsrInstructions();
116                final InstructionHandle[] ret = new InstructionHandle[jsrs.length];
117                Arrays.setAll(ret, i -> jsrs[i].getNext());
118                return ret;
119            }
120
121            // Terminates method normally.
122            // Terminates method abnormally, because JustIce mandates
123            // subroutines not to be protected by exception handlers.
124            if (inst instanceof ReturnInstruction || inst instanceof ATHROW) {
125                return InstructionHandle.EMPTY_ARRAY;
126            }
127
128            // See method comment.
129            if (inst instanceof JsrInstruction) {
130                single[0] = ((JsrInstruction) inst).getTarget();
131                return single;
132            }
133
134            if (inst instanceof GotoInstruction) {
135                single[0] = ((GotoInstruction) inst).getTarget();
136                return single;
137            }
138
139            if (inst instanceof BranchInstruction) {
140                if (inst instanceof Select) {
141                    // BCEL's getTargets() returns only the non-default targets,
142                    // thanks to Eli Tilevich for reporting.
143                    final InstructionHandle[] matchTargets = ((Select) inst).getTargets();
144                    final InstructionHandle[] ret = new InstructionHandle[matchTargets.length + 1];
145                    ret[0] = ((Select) inst).getTarget();
146                    System.arraycopy(matchTargets, 0, ret, 1, matchTargets.length);
147                    return ret;
148                }
149                final InstructionHandle[] pair = new InstructionHandle[2];
150                pair[0] = getInstruction().getNext();
151                pair[1] = ((BranchInstruction) inst).getTarget();
152                return pair;
153            }
154
155            // default case: Fall through.
156            single[0] = getInstruction().getNext();
157            return single;
158        }
159
160        /**
161         * "Merges in" (vmspec2, page 146) the "incoming" frame situation; executes the instructions symbolically and therefore
162         * calculates the "outgoing" frame situation. Returns: True iff the "incoming" frame situation changed after merging
163         * with "inFrame". The execPreds ArrayList must contain the InstructionContext objects executed so far in the correct
164         * order. This is just one execution path [out of many]. This is needed to correctly "merge" in the special case of a
165         * RET's successor. <B>The InstConstraintVisitor and ExecutionVisitor instances must be set up correctly.</B>
166         *
167         * @return true - if and only if the "outgoing" frame situation changed from the one before execute()ing.
168         */
169        @Override
170        public boolean execute(final Frame inFrame, final ArrayList<InstructionContext> execPreds, final InstConstraintVisitor icv, final ExecutionVisitor ev) {
171
172            @SuppressWarnings("unchecked") // OK because execPreds is compatible type
173            final List<InstructionContext> clone = (List<InstructionContext>) execPreds.clone();
174            executionPredecessors = clone;
175
176            // sanity check
177            if (lastExecutionJSR() == null && subroutines.subroutineOf(getInstruction()) != subroutines.getTopLevel()
178                || lastExecutionJSR() != null && subroutines.subroutineOf(getInstruction()) == subroutines.getTopLevel()) {
179                throw new AssertionViolatedException("Huh?! Am I '" + this + "' part of a subroutine or not?");
180            }
181
182            Frame inF = inFrames.get(lastExecutionJSR());
183            if (inF == null) {// no incoming frame was set, so set it.
184                inFrames.put(lastExecutionJSR(), inFrame);
185                inF = inFrame;
186            } else if (inF.equals(inFrame) || !mergeInFrames(inFrame)) { // if there was an "old" inFrame
187                return false;
188            }
189
190            // Now we're sure the inFrame has changed!
191
192            // new inFrame is already merged in, see above.
193            final Frame workingFrame = inF.getClone();
194
195            try {
196                // This verifies the InstructionConstraint for the current
197                // instruction, but does not modify the workingFrame object.
198//InstConstraintVisitor icv = InstConstraintVisitor.getInstance(VerifierFactory.getVerifier(method_gen.getClassName()));
199                icv.setFrame(workingFrame);
200                getInstruction().accept(icv);
201            } catch (final StructuralCodeConstraintException ce) {
202                ce.extendMessage("", "\nInstructionHandle: " + getInstruction() + "\n");
203                ce.extendMessage("", "\nExecution Frame:\n" + workingFrame);
204                extendMessageWithFlow(ce);
205                throw ce;
206            }
207
208            // This executes the Instruction.
209            // Therefore the workingFrame object is modified.
210//ExecutionVisitor ev = ExecutionVisitor.getInstance(VerifierFactory.getVerifier(method_gen.getClassName()));
211            ev.setFrame(workingFrame);
212            getInstruction().accept(ev);
213            // getInstruction().accept(ExecutionVisitor.withFrame(workingFrame));
214            outFrames.put(lastExecutionJSR(), workingFrame);
215
216            return true; // new inFrame was different from old inFrame so merging them
217                         // yielded a different this.inFrame.
218        }
219
220        /**
221         * Extends the StructuralCodeConstraintException ("e") object with an at-the-end-extended message. This extended message
222         * will then reflect the execution flow needed to get to the constraint violation that triggered the throwing of the "e"
223         * object.
224         */
225        private void extendMessageWithFlow(final StructuralCodeConstraintException e) {
226            final String s = "Execution flow:\n";
227            e.extendMessage("", s + getExecutionChain());
228        }
229
230        /**
231         * Returns the exception handlers of this instruction.
232         */
233        @Override
234        public ExceptionHandler[] getExceptionHandlers() {
235            return exceptionhandlers.getExceptionHandlers(getInstruction());
236        }
237
238        /**
239         * Returns the control flow execution chain. This is built while execute(Frame, ArrayList)-ing the code represented by
240         * the surrounding ControlFlowGraph.
241         */
242        private String getExecutionChain() {
243            final StringBuilder s = new StringBuilder(this.toString());
244            for (int i = executionPredecessors.size() - 1; i >= 0; i--) {
245                s.insert(0, executionPredecessors.get(i) + "\n");
246            }
247            return s.toString();
248        }
249
250        @Override
251        public Frame getInFrame() {
252            Frame org;
253
254            final InstructionContext jsr = lastExecutionJSR();
255
256            org = inFrames.get(jsr);
257
258            if (org == null) {
259                throw new AssertionViolatedException("inFrame not set! This:\n" + this + "\nInFrames: '" + inFrames + "'.");
260            }
261            return org.getClone();
262        }
263
264        /*
265         * Fulfils the contract of InstructionContext.getInstruction().
266         */
267        @Override
268        public InstructionHandle getInstruction() {
269            return instruction;
270        }
271
272        /**
273         * Returns a clone of the "outgoing" frame situation with respect to the given ExecutionChain.
274         */
275        @Override
276        public Frame getOutFrame(final ArrayList<InstructionContext> execChain) {
277            executionPredecessors = execChain;
278
279            Frame org;
280
281            final InstructionContext jsr = lastExecutionJSR();
282
283            org = outFrames.get(jsr);
284
285            if (org == null) {
286                throw new AssertionViolatedException(
287                    "outFrame not set! This:\n" + this + "\nExecutionChain: " + getExecutionChain() + "\nOutFrames: '" + outFrames + "'.");
288            }
289            return org.getClone();
290        }
291
292        /* Satisfies InstructionContext.getSuccessors(). */
293        @Override
294        public InstructionContext[] getSuccessors() {
295            return contextsOf(_getSuccessors());
296        }
297
298        /* Satisfies InstructionContext.getTag(). */
299        @Override
300        public int getTag() {
301            return TAG;
302        }
303
304        /**
305         * Returns the InstructionContextImpl with an JSR/JSR_W that was last in the ExecutionChain, without a corresponding
306         * RET, i.e. we were called by this one. Returns null if we were called from the top level.
307         */
308        private InstructionContextImpl lastExecutionJSR() {
309
310            final int size = executionPredecessors.size();
311            int retcount = 0;
312
313            for (int i = size - 1; i >= 0; i--) {
314                final InstructionContextImpl current = (InstructionContextImpl) executionPredecessors.get(i);
315                final Instruction currentlast = current.getInstruction().getInstruction();
316                if (currentlast instanceof RET) {
317                    retcount++;
318                }
319                if (currentlast instanceof JsrInstruction) {
320                    retcount--;
321                    if (retcount == -1) {
322                        return current;
323                    }
324                }
325            }
326            return null;
327        }
328
329        /**
330         * Does the actual merging (vmspec2, page 146). Returns true IFF this.inFrame was changed in course of merging with
331         * inFrame.
332         */
333        private boolean mergeInFrames(final Frame inFrame) {
334            // TODO: Can be performance-improved.
335            final Frame inF = inFrames.get(lastExecutionJSR());
336            final OperandStack oldstack = inF.getStack().getClone();
337            final LocalVariables oldlocals = inF.getLocals().getClone();
338            try {
339                inF.getStack().merge(inFrame.getStack());
340                inF.getLocals().merge(inFrame.getLocals());
341            } catch (final StructuralCodeConstraintException sce) {
342                extendMessageWithFlow(sce);
343                throw sce;
344            }
345            return !(oldstack.equals(inF.getStack()) && oldlocals.equals(inF.getLocals()));
346        }
347
348        /* Satisfies InstructionContext.setTag(int). */
349        @Override
350        public void setTag(final int tag) { // part of InstructionContext interface
351            TAG = tag;
352        }
353
354        /**
355         * Returns a simple String representation of this InstructionContext.
356         */
357        @Override
358        public String toString() {
359            // TODO: Put information in the brackets, e.g.
360            // Is this an ExceptionHandler? Is this a RET? Is this the start of
361            // a subroutine?
362            return getInstruction().toString(false) + "\t[InstructionContext]";
363        }
364
365    } // End Inner InstructionContextImpl Class.
366
367    /// ** The MethodGen object we're working on. */
368    // private final MethodGen method_gen;
369
370    /** The Subroutines object for the method whose control flow is represented by this ControlFlowGraph. */
371    private final Subroutines subroutines;
372
373    /** The ExceptionHandlers object for the method whose control flow is represented by this ControlFlowGraph. */
374    private final ExceptionHandlers exceptionhandlers;
375
376    /** All InstructionContext instances of this ControlFlowGraph. */
377    private final Map<InstructionHandle, InstructionContext> instructionContexts = new HashMap<>();
378
379    /**
380     * A Control Flow Graph; with additional JustIce checks
381     *
382     * @param method_gen the method generator instance
383     */
384    public ControlFlowGraph(final MethodGen method_gen) {
385        this(method_gen, true);
386    }
387
388    /**
389     * A Control Flow Graph.
390     *
391     * @param method_gen the method generator instance
392     * @param enableJustIceCheck if true, additional JustIce checks are performed
393     * @since 6.0
394     */
395    public ControlFlowGraph(final MethodGen method_gen, final boolean enableJustIceCheck) {
396        subroutines = new Subroutines(method_gen, enableJustIceCheck);
397        exceptionhandlers = new ExceptionHandlers(method_gen);
398
399        final InstructionHandle[] instructionhandles = method_gen.getInstructionList().getInstructionHandles();
400        for (final InstructionHandle instructionhandle : instructionhandles) {
401            instructionContexts.put(instructionhandle, new InstructionContextImpl(instructionhandle));
402        }
403
404        // this.method_gen = method_gen;
405    }
406
407    /**
408     * Returns the InstructionContext of a given instruction.
409     */
410    public InstructionContext contextOf(final InstructionHandle inst) {
411        final InstructionContext ic = instructionContexts.get(inst);
412        if (ic == null) {
413            throw new AssertionViolatedException("InstructionContext requested for an InstructionHandle that's not known!");
414        }
415        return ic;
416    }
417
418    /**
419     * Returns the InstructionContext[] of a given InstructionHandle[], in a naturally ordered manner.
420     */
421    public InstructionContext[] contextsOf(final InstructionHandle[] insts) {
422        final InstructionContext[] ret = new InstructionContext[insts.length];
423        Arrays.setAll(ret, i -> contextOf(insts[i]));
424        return ret;
425    }
426
427    /**
428     * Returns an InstructionContext[] with all the InstructionContext instances for the method whose control flow is
429     * represented by this ControlFlowGraph <B>(NOT ORDERED!)</B>.
430     */
431    public InstructionContext[] getInstructionContexts() {
432        final InstructionContext[] ret = new InstructionContext[instructionContexts.size()];
433        return instructionContexts.values().toArray(ret);
434    }
435
436    /**
437     * Returns true, if and only if the said instruction is not reachable; that means, if it is not part of this
438     * ControlFlowGraph.
439     */
440    public boolean isDead(final InstructionHandle i) {
441        return subroutines.subroutineOf(i) == null;
442    }
443}