You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ControlFlowGraph.java 17KB

14 yıl önce
14 yıl önce
14 yıl önce
14 yıl önce
14 yıl önce
14 yıl önce
14 yıl önce
14 yıl önce
14 yıl önce
14 yıl önce
14 yıl önce
14 yıl önce
14 yıl önce
14 yıl önce
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456
  1. package org.aspectj.apache.bcel.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 (https://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. * <https://www.apache.org/>.
  54. */
  55. import java.util.ArrayList;
  56. import java.util.HashMap;
  57. import java.util.Hashtable;
  58. import org.aspectj.apache.bcel.Constants;
  59. import org.aspectj.apache.bcel.generic.Instruction;
  60. import org.aspectj.apache.bcel.generic.InstructionBranch;
  61. import org.aspectj.apache.bcel.generic.InstructionHandle;
  62. import org.aspectj.apache.bcel.generic.InstructionSelect;
  63. import org.aspectj.apache.bcel.generic.MethodGen;
  64. import org.aspectj.apache.bcel.generic.RET;
  65. import org.aspectj.apache.bcel.verifier.InstructionWalker;
  66. import org.aspectj.apache.bcel.verifier.exc.AssertionViolatedException;
  67. import org.aspectj.apache.bcel.verifier.exc.StructuralCodeConstraintException;
  68. /**
  69. * This class represents a control flow graph of a method.
  70. *
  71. * @version $Id: ControlFlowGraph.java,v 1.4 2009/09/09 19:56:20 aclement Exp $
  72. * @author <A HREF="https://www.inf.fu-berlin.de/~ehaase"/>Enver Haase</A>
  73. */
  74. public class ControlFlowGraph {
  75. /**
  76. * Objects of this class represent a node in a ControlFlowGraph. These nodes are instructions, not basic blocks.
  77. */
  78. private class InstructionContextImpl implements InstructionContext {
  79. /**
  80. * The TAG field is here for external temporary flagging, such as graph colouring.
  81. *
  82. * @see #getTag()
  83. * @see #setTag(int)
  84. */
  85. private int TAG;
  86. /**
  87. * The InstructionHandle this InstructionContext is wrapped around.
  88. */
  89. private final InstructionHandle instruction;
  90. /**
  91. * The 'incoming' execution Frames.
  92. */
  93. private final HashMap<InstructionContextImpl, Frame> inFrames; // key: the last-executed JSR
  94. /**
  95. * The 'outgoing' execution Frames.
  96. */
  97. private final HashMap<InstructionContextImpl, Frame> outFrames; // key: the last-executed JSR
  98. /**
  99. * The 'execution predecessors' - a list of type InstructionContext of those instances that have been execute()d before in
  100. * that order.
  101. */
  102. private ArrayList<InstructionContext> executionPredecessors = null; // Type: InstructionContext
  103. /**
  104. * Creates an InstructionHandleImpl object from an InstructionHandle. Creation of one per InstructionHandle suffices. Don't
  105. * create more.
  106. */
  107. public InstructionContextImpl(InstructionHandle inst) {
  108. if (inst == null) {
  109. throw new AssertionViolatedException("Cannot instantiate InstructionContextImpl from NULL.");
  110. }
  111. instruction = inst;
  112. inFrames = new java.util.HashMap<InstructionContextImpl, Frame>();
  113. outFrames = new java.util.HashMap<InstructionContextImpl, Frame>();
  114. }
  115. /* Satisfies InstructionContext.getTag(). */
  116. public int getTag() {
  117. return TAG;
  118. }
  119. /* Satisfies InstructionContext.setTag(int). */
  120. public void setTag(int tag) {
  121. TAG = tag;
  122. }
  123. /**
  124. * Returns the exception handlers of this instruction.
  125. */
  126. public ExceptionHandler[] getExceptionHandlers() {
  127. return exceptionhandlers.getExceptionHandlers(getInstruction());
  128. }
  129. /**
  130. * Returns a clone of the "outgoing" frame situation with respect to the given ExecutionChain.
  131. */
  132. public Frame getOutFrame(ArrayList<InstructionContext> execChain) {
  133. executionPredecessors = execChain;
  134. Frame org;
  135. InstructionContext jsr = lastExecutionJSR();
  136. org = outFrames.get(jsr);
  137. if (org == null) {
  138. throw new AssertionViolatedException("outFrame not set! This:\n" + this + "\nExecutionChain: "
  139. + getExecutionChain() + "\nOutFrames: '" + outFrames + "'.");
  140. }
  141. return org.getClone();
  142. }
  143. /**
  144. * "Merges in" (vmspec2, page 146) the "incoming" frame situation; executes the instructions symbolically and therefore
  145. * calculates the "outgoing" frame situation. Returns: True iff the "incoming" frame situation changed after merging with
  146. * "inFrame". The execPreds ArrayList must contain the InstructionContext objects executed so far in the correct order. This
  147. * is just one execution path [out of many]. This is needed to correctly "merge" in the special case of a RET's successor.
  148. * <B>The InstConstraintVisitor and ExecutionVisitor instances must be set up correctly.</B>
  149. *
  150. * @return true - if and only if the "outgoing" frame situation changed from the one before execute()ing.
  151. */
  152. public boolean execute(Frame inFrame, ArrayList<InstructionContext> execPreds, InstConstraintVisitor icv, ExecutionVisitor ev) {
  153. executionPredecessors = (ArrayList<InstructionContext>) execPreds.clone();
  154. // sanity check
  155. if (lastExecutionJSR() == null && subroutines.subroutineOf(getInstruction()) != subroutines.getTopLevel()) {
  156. throw new AssertionViolatedException("Huh?! Am I '" + this + "' part of a subroutine or not?");
  157. }
  158. if (lastExecutionJSR() != null && subroutines.subroutineOf(getInstruction()) == subroutines.getTopLevel()) {
  159. throw new AssertionViolatedException("Huh?! Am I '" + this + "' part of a subroutine or not?");
  160. }
  161. Frame inF = inFrames.get(lastExecutionJSR());
  162. if (inF == null) {// no incoming frame was set, so set it.
  163. inFrames.put(lastExecutionJSR(), inFrame);
  164. inF = inFrame;
  165. } else {// if there was an "old" inFrame
  166. if (inF.equals(inFrame)) { // shortcut: no need to merge equal frames.
  167. return false;
  168. }
  169. if (!mergeInFrames(inFrame)) {
  170. return false;
  171. }
  172. }
  173. // Now we're sure the inFrame has changed!
  174. // new inFrame is already merged in, see above.
  175. Frame workingFrame = inF.getClone();
  176. try {
  177. // This verifies the InstructionConstraint for the current
  178. // instruction, but does not modify the workingFrame object.
  179. // InstConstraintVisitor icv =
  180. // InstConstraintVisitor.getInstance(VerifierFactory.getVerifier(method_gen.getClassName()));
  181. icv.setFrame(workingFrame);
  182. InstructionWalker.accept(getInstruction().getInstruction(), icv);
  183. } catch (StructuralCodeConstraintException ce) {
  184. ce.extendMessage("", "\nInstructionHandle: " + getInstruction() + "\n");
  185. ce.extendMessage("", "\nExecution Frame:\n" + workingFrame);
  186. extendMessageWithFlow(ce);
  187. throw ce;
  188. }
  189. // This executes the Instruction.
  190. // Therefore the workingFrame object is modified.
  191. // ExecutionVisitor ev = ExecutionVisitor.getInstance(VerifierFactory.getVerifier(method_gen.getClassName()));
  192. ev.setFrame(workingFrame);
  193. InstructionWalker.accept(getInstruction().getInstruction(), ev);
  194. // getInstruction().accept(ExecutionVisitor.withFrame(workingFrame));
  195. outFrames.put(lastExecutionJSR(), workingFrame);
  196. return true; // new inFrame was different from old inFrame so merging them
  197. // yielded a different this.inFrame.
  198. }
  199. /**
  200. * Returns a simple String representation of this InstructionContext.
  201. */
  202. public String toString() {
  203. // TODO: Put information in the brackets, e.g.
  204. // Is this an ExceptionHandler? Is this a RET? Is this the start of
  205. // a subroutine?
  206. String ret = getInstruction().toString(false) + "\t[InstructionContext]";
  207. return ret;
  208. }
  209. /**
  210. * Does the actual merging (vmspec2, page 146). Returns true IFF this.inFrame was changed in course of merging with inFrame.
  211. */
  212. private boolean mergeInFrames(Frame inFrame) {
  213. // TODO: Can be performance-improved.
  214. Frame inF = inFrames.get(lastExecutionJSR());
  215. OperandStack oldstack = inF.getStack().getClone();
  216. LocalVariables oldlocals = inF.getLocals().getClone();
  217. try {
  218. inF.getStack().merge(inFrame.getStack());
  219. inF.getLocals().merge(inFrame.getLocals());
  220. } catch (StructuralCodeConstraintException sce) {
  221. extendMessageWithFlow(sce);
  222. throw sce;
  223. }
  224. if (oldstack.equals(inF.getStack()) && oldlocals.equals(inF.getLocals())) {
  225. return false;
  226. } else {
  227. return true;
  228. }
  229. }
  230. /**
  231. * Returns the control flow execution chain. This is built while execute(Frame, ArrayList)-ing the code represented by the
  232. * surrounding ControlFlowGraph.
  233. */
  234. private String getExecutionChain() {
  235. String s = this.toString();
  236. for (int i = executionPredecessors.size() - 1; i >= 0; i--) {
  237. s = executionPredecessors.get(i) + "\n" + s;
  238. }
  239. return s;
  240. }
  241. /**
  242. * Extends the StructuralCodeConstraintException ("e") object with an at-the-end-extended message. This extended message
  243. * will then reflect the execution flow needed to get to the constraint violation that triggered the throwing of the "e"
  244. * object.
  245. */
  246. private void extendMessageWithFlow(StructuralCodeConstraintException e) {
  247. String s = "Execution flow:\n";
  248. e.extendMessage("", s + getExecutionChain());
  249. }
  250. /*
  251. * Fulfils the contract of InstructionContext.getInstruction().
  252. */
  253. public InstructionHandle getInstruction() {
  254. return instruction;
  255. }
  256. /**
  257. * Returns the InstructionContextImpl with an JSR/JSR_W that was last in the ExecutionChain, without a corresponding RET,
  258. * i.e. we were called by this one. Returns null if we were called from the top level.
  259. */
  260. private InstructionContextImpl lastExecutionJSR() {
  261. int size = executionPredecessors.size();
  262. int retcount = 0;
  263. for (int i = size - 1; i >= 0; i--) {
  264. InstructionContextImpl current = (InstructionContextImpl) executionPredecessors.get(i);
  265. Instruction currentlast = current.getInstruction().getInstruction();
  266. if (currentlast instanceof RET) {
  267. retcount++;
  268. }
  269. if (currentlast.isJsrInstruction()) {
  270. retcount--;
  271. if (retcount == -1) {
  272. return current;
  273. }
  274. }
  275. }
  276. return null;
  277. }
  278. /* Satisfies InstructionContext.getSuccessors(). */
  279. public InstructionContext[] getSuccessors() {
  280. return contextsOf(_getSuccessors());
  281. }
  282. /**
  283. * A utility method that calculates the successors of a given InstructionHandle That means, a RET does have successors as
  284. * defined here. A JsrInstruction has its target as its successor (opposed to its physical successor) as defined here.
  285. */
  286. // TODO: implement caching!
  287. private InstructionHandle[] _getSuccessors() {
  288. final InstructionHandle[] empty = new InstructionHandle[0];
  289. final InstructionHandle[] single = new InstructionHandle[1];
  290. final InstructionHandle[] pair = new InstructionHandle[2];
  291. Instruction inst = getInstruction().getInstruction();
  292. if (inst instanceof RET) {
  293. Subroutine s = subroutines.subroutineOf(getInstruction());
  294. if (s == null) { // return empty; // RET in dead code. "empty" would be the correct answer, but we know something
  295. // about the surrounding project...
  296. throw new AssertionViolatedException("Asking for successors of a RET in dead code?!");
  297. }
  298. // TODO: remove
  299. throw new AssertionViolatedException("DID YOU REALLY WANT TO ASK FOR RET'S SUCCS?");
  300. /*
  301. * InstructionHandle[] jsrs = s.getEnteringJsrInstructions(); InstructionHandle[] ret = new
  302. * InstructionHandle[jsrs.length]; for (int i=0; i<jsrs.length; i++){ ret[i] = jsrs[i].getNext(); } return ret;
  303. */
  304. }
  305. // Terminates method normally.
  306. if (inst.isReturnInstruction()) {
  307. return empty;
  308. }
  309. // Terminates method abnormally, because JustIce mandates
  310. // subroutines not to be protected by exception handlers.
  311. if (inst.getOpcode() == Constants.ATHROW) {
  312. return empty;
  313. }
  314. // See method comment.
  315. if (inst.isJsrInstruction()) {
  316. single[0] = ((InstructionBranch) inst).getTarget();
  317. return single;
  318. }
  319. if (inst.getOpcode() == Constants.GOTO || inst.getOpcode() == Constants.GOTO_W) {
  320. single[0] = ((InstructionBranch) inst).getTarget();
  321. return single;
  322. }
  323. if (inst instanceof InstructionBranch) {
  324. if (inst instanceof InstructionSelect) {
  325. // BCEL's getTargets() returns only the non-default targets,
  326. // thanks to Eli Tilevich for reporting.
  327. InstructionHandle[] matchTargets = ((InstructionSelect) inst).getTargets();
  328. InstructionHandle[] ret = new InstructionHandle[matchTargets.length + 1];
  329. ret[0] = ((InstructionSelect) inst).getTarget();
  330. System.arraycopy(matchTargets, 0, ret, 1, matchTargets.length);
  331. return ret;
  332. } else {
  333. pair[0] = getInstruction().getNext();
  334. pair[1] = ((InstructionBranch) inst).getTarget();
  335. return pair;
  336. }
  337. }
  338. // default case: Fall through.
  339. single[0] = getInstruction().getNext();
  340. return single;
  341. }
  342. } // End Inner InstructionContextImpl Class.
  343. /** The MethofGen object we're working on. */
  344. private final MethodGen method_gen;
  345. /** The Subroutines object for the method whose control flow is represented by this ControlFlowGraph. */
  346. private final Subroutines subroutines;
  347. /** The ExceptionHandlers object for the method whose control flow is represented by this ControlFlowGraph. */
  348. private final ExceptionHandlers exceptionhandlers;
  349. /** All InstructionContext instances of this ControlFlowGraph. */
  350. private final Hashtable<InstructionHandle, InstructionContextImpl> instructionContexts = new Hashtable<InstructionHandle, InstructionContextImpl>(); // keys: InstructionHandle, values: InstructionContextImpl
  351. /**
  352. * A Control Flow Graph.
  353. */
  354. public ControlFlowGraph(MethodGen method_gen) {
  355. subroutines = new Subroutines(method_gen);
  356. exceptionhandlers = new ExceptionHandlers(method_gen);
  357. InstructionHandle[] instructionhandles = method_gen.getInstructionList().getInstructionHandles();
  358. for (int i = 0; i < instructionhandles.length; i++) {
  359. instructionContexts.put(instructionhandles[i], new InstructionContextImpl(instructionhandles[i]));
  360. }
  361. this.method_gen = method_gen;
  362. }
  363. /**
  364. * Returns the InstructionContext of a given instruction.
  365. */
  366. public InstructionContext contextOf(InstructionHandle inst) {
  367. InstructionContext ic = instructionContexts.get(inst);
  368. if (ic == null) {
  369. throw new AssertionViolatedException("InstructionContext requested for an InstructionHandle that's not known!");
  370. }
  371. return ic;
  372. }
  373. /**
  374. * Returns the InstructionContext[] of a given InstructionHandle[], in a naturally ordered manner.
  375. */
  376. public InstructionContext[] contextsOf(InstructionHandle[] insts) {
  377. InstructionContext[] ret = new InstructionContext[insts.length];
  378. for (int i = 0; i < insts.length; i++) {
  379. ret[i] = contextOf(insts[i]);
  380. }
  381. return ret;
  382. }
  383. /**
  384. * Returns an InstructionContext[] with all the InstructionContext instances for the method whose control flow is represented by
  385. * this ControlFlowGraph <B>(NOT ORDERED!)</B>.
  386. */
  387. public InstructionContext[] getInstructionContexts() {
  388. InstructionContext[] ret = new InstructionContext[instructionContexts.values().size()];
  389. return instructionContexts.values().toArray(ret);
  390. }
  391. /**
  392. * Returns true, if and only if the said instruction is not reachable; that means, if it not part of this ControlFlowGraph.
  393. */
  394. public boolean isDead(InstructionHandle i) {
  395. return instructionContexts.containsKey(i);
  396. }
  397. }