1. package com.sun.org.apache.bcel.internal.verifier.structurals;
  2. /* ====================================================================
  3. * The Apache Software License, Version 1.1
  4. *
  5. * Copyright (c) 2001 The Apache Software Foundation. All rights
  6. * reserved.
  7. *
  8. * Redistribution and use in source and binary forms, with or without
  9. * modification, are permitted provided that the following conditions
  10. * are met:
  11. *
  12. * 1. Redistributions of source code must retain the above copyright
  13. * notice, this list of conditions and the following disclaimer.
  14. *
  15. * 2. Redistributions in binary form must reproduce the above copyright
  16. * notice, this list of conditions and the following disclaimer in
  17. * the documentation and/or other materials provided with the
  18. * distribution.
  19. *
  20. * 3. The end-user documentation included with the redistribution,
  21. * if any, must include the following acknowledgment:
  22. * "This product includes software developed by the
  23. * Apache Software Foundation (http://www.apache.org/)."
  24. * Alternately, this acknowledgment may appear in the software itself,
  25. * if and wherever such third-party acknowledgments normally appear.
  26. *
  27. * 4. The names "Apache" and "Apache Software Foundation" and
  28. * "Apache BCEL" must not be used to endorse or promote products
  29. * derived from this software without prior written permission. For
  30. * written permission, please contact apache@apache.org.
  31. *
  32. * 5. Products derived from this software may not be called "Apache",
  33. * "Apache BCEL", nor may "Apache" appear in their name, without
  34. * prior written permission of the Apache Software Foundation.
  35. *
  36. * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
  37. * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  38. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  39. * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
  40. * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  41. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  42. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
  43. * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  44. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  45. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
  46. * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  47. * SUCH DAMAGE.
  48. * ====================================================================
  49. *
  50. * This software consists of voluntary contributions made by many
  51. * individuals on behalf of the Apache Software Foundation. For more
  52. * information on the Apache Software Foundation, please see
  53. * <http://www.apache.org/>.
  54. */
  55. import com.sun.org.apache.bcel.internal.generic.*;
  56. import com.sun.org.apache.bcel.internal.verifier.VerifierFactory;
  57. import com.sun.org.apache.bcel.internal.verifier.exc.*;
  58. import java.util.*;
  59. /**
  60. * This class represents a control flow graph of a method.
  61. *
  62. * @version $Id: ControlFlowGraph.java,v 1.1.1.1 2001/10/29 20:00:37 jvanzyl Exp $
  63. * @author <A HREF="http://www.inf.fu-berlin.de/~ehaase"/>Enver Haase</A>
  64. */
  65. public class ControlFlowGraph{
  66. /**
  67. * Objects of this class represent a node in a ControlFlowGraph.
  68. * These nodes are instructions, not basic blocks.
  69. */
  70. private class InstructionContextImpl implements InstructionContext{
  71. /**
  72. * The TAG field is here for external temporary flagging, such
  73. * as graph colouring.
  74. *
  75. * @see #getTag()
  76. * @see #setTag(int)
  77. */
  78. private int TAG;
  79. /**
  80. * The InstructionHandle this InstructionContext is wrapped around.
  81. */
  82. private InstructionHandle instruction;
  83. /**
  84. * The 'incoming' execution Frames.
  85. */
  86. private HashMap inFrames; // key: the last-executed JSR
  87. /**
  88. * The 'outgoing' execution Frames.
  89. */
  90. private HashMap outFrames; // key: the last-executed JSR
  91. /**
  92. * The 'execution predecessors' - a list of type InstructionContext
  93. * of those instances that have been execute()d before in that order.
  94. */
  95. private ArrayList executionPredecessors = null; // Type: InstructionContext
  96. /**
  97. * Creates an InstructionHandleImpl object from an InstructionHandle.
  98. * Creation of one per InstructionHandle suffices. Don't create more.
  99. */
  100. public InstructionContextImpl(InstructionHandle inst){
  101. if (inst == null) throw new AssertionViolatedException("Cannot instantiate InstructionContextImpl from NULL.");
  102. instruction = inst;
  103. inFrames = new java.util.HashMap();
  104. outFrames = new java.util.HashMap();
  105. }
  106. /* Satisfies InstructionContext.getTag(). */
  107. public int getTag(){
  108. return TAG;
  109. }
  110. /* Satisfies InstructionContext.setTag(int). */
  111. public void setTag(int tag){
  112. TAG = tag;
  113. }
  114. /**
  115. * Returns the exception handlers of this instruction.
  116. */
  117. public ExceptionHandler[] getExceptionHandlers(){
  118. return exceptionhandlers.getExceptionHandlers(getInstruction());
  119. }
  120. /**
  121. * Returns a clone of the "outgoing" frame situation with respect to the given ExecutionChain.
  122. */
  123. public Frame getOutFrame(ArrayList execChain){
  124. executionPredecessors = execChain;
  125. Frame org;
  126. InstructionContext jsr = lastExecutionJSR();
  127. org = (Frame) outFrames.get(jsr);
  128. if (org == null){
  129. throw new AssertionViolatedException("outFrame not set! This:\n"+this+"\nExecutionChain: "+getExecutionChain()+"\nOutFrames: '"+outFrames+"'.");
  130. }
  131. return org.getClone();
  132. }
  133. /**
  134. * "Merges in" (vmspec2, page 146) the "incoming" frame situation;
  135. * executes the instructions symbolically
  136. * and therefore calculates the "outgoing" frame situation.
  137. * Returns: True iff the "incoming" frame situation changed after
  138. * merging with "inFrame".
  139. * The execPreds ArrayList must contain the InstructionContext
  140. * objects executed so far in the correct order. This is just
  141. * one execution path [out of many]. This is needed to correctly
  142. * "merge" in the special case of a RET's successor.
  143. * <B>The InstConstraintVisitor and ExecutionVisitor instances
  144. * must be set up correctly.</B>
  145. * @return true - if and only if the "outgoing" frame situation
  146. * changed from the one before execute()ing.
  147. */
  148. public boolean execute(Frame inFrame, ArrayList execPreds, InstConstraintVisitor icv, ExecutionVisitor ev){
  149. executionPredecessors = (ArrayList) execPreds.clone();
  150. //sanity check
  151. if ( (lastExecutionJSR() == null) && (subroutines.subroutineOf(getInstruction()) != subroutines.getTopLevel() ) ){
  152. throw new AssertionViolatedException("Huh?! Am I '"+this+"' part of a subroutine or not?");
  153. }
  154. if ( (lastExecutionJSR() != null) && (subroutines.subroutineOf(getInstruction()) == subroutines.getTopLevel() ) ){
  155. throw new AssertionViolatedException("Huh?! Am I '"+this+"' part of a subroutine or not?");
  156. }
  157. Frame inF = (Frame) inFrames.get(lastExecutionJSR());
  158. if (inF == null){// no incoming frame was set, so set it.
  159. inFrames.put(lastExecutionJSR(), inFrame);
  160. inF = inFrame;
  161. }
  162. else{// if there was an "old" inFrame
  163. if (inF.equals(inFrame)){ //shortcut: no need to merge equal frames.
  164. return false;
  165. }
  166. if (! mergeInFrames(inFrame)){
  167. return false;
  168. }
  169. }
  170. // Now we're sure the inFrame has changed!
  171. // new inFrame is already merged in, see above.
  172. Frame workingFrame = inF.getClone();
  173. try{
  174. // This verifies the InstructionConstraint for the current
  175. // instruction, but does not modify the workingFrame object.
  176. //InstConstraintVisitor icv = InstConstraintVisitor.getInstance(VerifierFactory.getVerifier(method_gen.getClassName()));
  177. icv.setFrame(workingFrame);
  178. getInstruction().accept(icv);
  179. }
  180. catch(StructuralCodeConstraintException ce){
  181. ce.extendMessage("","\nInstructionHandle: "+getInstruction()+"\n");
  182. ce.extendMessage("","\nExecution Frame:\n"+workingFrame);
  183. extendMessageWithFlow(ce);
  184. throw ce;
  185. }
  186. // This executes the Instruction.
  187. // Therefore the workingFrame object is modified.
  188. //ExecutionVisitor ev = ExecutionVisitor.getInstance(VerifierFactory.getVerifier(method_gen.getClassName()));
  189. ev.setFrame(workingFrame);
  190. getInstruction().accept(ev);
  191. //getInstruction().accept(ExecutionVisitor.withFrame(workingFrame));
  192. outFrames.put(lastExecutionJSR(), workingFrame);
  193. return true; // new inFrame was different from old inFrame so merging them
  194. // yielded a different this.inFrame.
  195. }
  196. /**
  197. * Returns a simple String representation of this InstructionContext.
  198. */
  199. public String toString(){
  200. //TODO: Put information in the brackets, e.g.
  201. // Is this an ExceptionHandler? Is this a RET? Is this the start of
  202. // a subroutine?
  203. String ret = getInstruction().toString(false)+"\t[InstructionContext]";
  204. return ret;
  205. }
  206. /**
  207. * Does the actual merging (vmspec2, page 146).
  208. * Returns true IFF this.inFrame was changed in course of merging with inFrame.
  209. */
  210. private boolean mergeInFrames(Frame inFrame){
  211. // TODO: Can be performance-improved.
  212. Frame inF = (Frame) inFrames.get(lastExecutionJSR());
  213. OperandStack oldstack = inF.getStack().getClone();
  214. LocalVariables oldlocals = inF.getLocals().getClone();
  215. try{
  216. inF.getStack().merge(inFrame.getStack());
  217. inF.getLocals().merge(inFrame.getLocals());
  218. }
  219. catch (StructuralCodeConstraintException sce){
  220. extendMessageWithFlow(sce);
  221. throw sce;
  222. }
  223. if ( oldstack.equals(inF.getStack()) &&
  224. oldlocals.equals(inF.getLocals()) ){
  225. return false;
  226. }
  227. else{
  228. return true;
  229. }
  230. }
  231. /**
  232. * Returns the control flow execution chain. This is built
  233. * while execute(Frame, ArrayList)-ing the code represented
  234. * by the surrounding ControlFlowGraph.
  235. */
  236. private String getExecutionChain(){
  237. String s = this.toString();
  238. for (int i=executionPredecessors.size()-1; i>=0; i--){
  239. s = executionPredecessors.get(i)+"\n" + s;
  240. }
  241. return s;
  242. }
  243. /**
  244. * Extends the StructuralCodeConstraintException ("e") object with an at-the-end-extended message.
  245. * This extended message will then reflect the execution flow needed to get to the constraint
  246. * violation that triggered the throwing of the "e" object.
  247. */
  248. private void extendMessageWithFlow(StructuralCodeConstraintException e){
  249. String s = "Execution flow:\n";
  250. e.extendMessage("", s+getExecutionChain());
  251. }
  252. /*
  253. * Fulfils the contract of InstructionContext.getInstruction().
  254. */
  255. public InstructionHandle getInstruction(){
  256. return instruction;
  257. }
  258. /**
  259. * Returns the InstructionContextImpl with an JSR/JSR_W
  260. * that was last in the ExecutionChain, without
  261. * a corresponding RET, i.e.
  262. * we were called by this one.
  263. * Returns null if we were called from the top level.
  264. */
  265. private InstructionContextImpl lastExecutionJSR(){
  266. int size = executionPredecessors.size();
  267. int retcount = 0;
  268. for (int i=size-1; i>=0; i--){
  269. InstructionContextImpl current = (InstructionContextImpl) (executionPredecessors.get(i));
  270. Instruction currentlast = current.getInstruction().getInstruction();
  271. if (currentlast instanceof RET) retcount++;
  272. if (currentlast instanceof JsrInstruction){
  273. retcount--;
  274. if (retcount == -1) return current;
  275. }
  276. }
  277. return null;
  278. }
  279. /* Satisfies InstructionContext.getSuccessors(). */
  280. public InstructionContext[] getSuccessors(){
  281. return contextsOf(_getSuccessors());
  282. }
  283. /**
  284. * A utility method that calculates the successors of a given InstructionHandle
  285. * That means, a RET does have successors as defined here.
  286. * A JsrInstruction has its target as its successor
  287. * (opposed to its physical successor) as defined here.
  288. */
  289. // TODO: implement caching!
  290. private InstructionHandle[] _getSuccessors(){
  291. final InstructionHandle[] empty = new InstructionHandle[0];
  292. final InstructionHandle[] single = new InstructionHandle[1];
  293. final InstructionHandle[] pair = new InstructionHandle[2];
  294. Instruction inst = getInstruction().getInstruction();
  295. if (inst instanceof RET){
  296. Subroutine s = subroutines.subroutineOf(getInstruction());
  297. if (s==null){ //return empty; // RET in dead code. "empty" would be the correct answer, but we know something about the surrounding project...
  298. throw new AssertionViolatedException("Asking for successors of a RET in dead code?!");
  299. }
  300. //TODO: remove
  301. throw new AssertionViolatedException("DID YOU REALLY WANT TO ASK FOR RET'S SUCCS?");
  302. /*
  303. InstructionHandle[] jsrs = s.getEnteringJsrInstructions();
  304. InstructionHandle[] ret = new InstructionHandle[jsrs.length];
  305. for (int i=0; i<jsrs.length; i++){
  306. ret[i] = jsrs[i].getNext();
  307. }
  308. return ret;
  309. */
  310. }
  311. // Terminates method normally.
  312. if (inst instanceof ReturnInstruction){
  313. return empty;
  314. }
  315. // Terminates method abnormally, because JustIce mandates
  316. // subroutines not to be protected by exception handlers.
  317. if (inst instanceof ATHROW){
  318. return empty;
  319. }
  320. // See method comment.
  321. if (inst instanceof JsrInstruction){
  322. single[0] = ((JsrInstruction) inst).getTarget();
  323. return single;
  324. }
  325. if (inst instanceof GotoInstruction){
  326. single[0] = ((GotoInstruction) inst).getTarget();
  327. return single;
  328. }
  329. if (inst instanceof BranchInstruction){
  330. if (inst instanceof Select){
  331. // BCEL's getTargets() returns only the non-default targets,
  332. // thanks to Eli Tilevich for reporting.
  333. InstructionHandle[] matchTargets = ((Select) inst).getTargets();
  334. InstructionHandle[] ret = new InstructionHandle[matchTargets.length+1];
  335. ret[0] = ((Select) inst).getTarget();
  336. System.arraycopy(matchTargets, 0, ret, 1, matchTargets.length);
  337. return ret;
  338. }
  339. else{
  340. pair[0] = getInstruction().getNext();
  341. pair[1] = ((BranchInstruction) inst).getTarget();
  342. return pair;
  343. }
  344. }
  345. // default case: Fall through.
  346. single[0] = getInstruction().getNext();
  347. return single;
  348. }
  349. } // End Inner InstructionContextImpl Class.
  350. /** The MethofGen object we're working on. */
  351. private final MethodGen method_gen;
  352. /** The Subroutines object for the method whose control flow is represented by this ControlFlowGraph. */
  353. private final Subroutines subroutines;
  354. /** The ExceptionHandlers object for the method whose control flow is represented by this ControlFlowGraph. */
  355. private final ExceptionHandlers exceptionhandlers;
  356. /** All InstructionContext instances of this ControlFlowGraph. */
  357. private Hashtable instructionContexts = new Hashtable(); //keys: InstructionHandle, values: InstructionContextImpl
  358. /**
  359. * A Control Flow Graph.
  360. */
  361. public ControlFlowGraph(MethodGen method_gen){
  362. subroutines = new Subroutines(method_gen);
  363. exceptionhandlers = new ExceptionHandlers(method_gen);
  364. InstructionHandle[] instructionhandles = method_gen.getInstructionList().getInstructionHandles();
  365. for (int i=0; i<instructionhandles.length; i++){
  366. instructionContexts.put(instructionhandles[i], new InstructionContextImpl(instructionhandles[i]));
  367. }
  368. this.method_gen = method_gen;
  369. }
  370. /**
  371. * Returns the InstructionContext of a given instruction.
  372. */
  373. public InstructionContext contextOf(InstructionHandle inst){
  374. InstructionContext ic = (InstructionContext) instructionContexts.get(inst);
  375. if (ic == null){
  376. throw new AssertionViolatedException("InstructionContext requested for an InstructionHandle that's not known!");
  377. }
  378. return ic;
  379. }
  380. /**
  381. * Returns the InstructionContext[] of a given InstructionHandle[],
  382. * in a naturally ordered manner.
  383. */
  384. public InstructionContext[] contextsOf(InstructionHandle[] insts){
  385. InstructionContext[] ret = new InstructionContext[insts.length];
  386. for (int i=0; i<insts.length; i++){
  387. ret[i] = contextOf(insts[i]);
  388. }
  389. return ret;
  390. }
  391. /**
  392. * Returns an InstructionContext[] with all the InstructionContext instances
  393. * for the method whose control flow is represented by this ControlFlowGraph
  394. * <B>(NOT ORDERED!)</B>.
  395. */
  396. public InstructionContext[] getInstructionContexts(){
  397. InstructionContext[] ret = new InstructionContext[instructionContexts.values().size()];
  398. return (InstructionContext[]) instructionContexts.values().toArray(ret);
  399. }
  400. /**
  401. * Returns true, if and only if the said instruction is not reachable; that means,
  402. * if it not part of this ControlFlowGraph.
  403. */
  404. public boolean isDead(InstructionHandle i){
  405. return instructionContexts.containsKey(i);
  406. }
  407. }