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 java.io.*;
  56. import java.util.ArrayList;
  57. import java.util.Iterator;
  58. import java.util.Random;
  59. import java.util.Vector;
  60. import com.sun.org.apache.bcel.internal.Constants;
  61. import com.sun.org.apache.bcel.internal.Repository;
  62. import com.sun.org.apache.bcel.internal.classfile.*;
  63. import com.sun.org.apache.bcel.internal.generic.*;
  64. import com.sun.org.apache.bcel.internal.verifier.*;
  65. import com.sun.org.apache.bcel.internal.verifier.statics.*;
  66. import com.sun.org.apache.bcel.internal.verifier.exc.*;
  67. /**
  68. * This PassVerifier verifies a method of class file according to pass 3,
  69. * so-called structural verification as described in The Java Virtual Machine
  70. * Specification, 2nd edition.
  71. * More detailed information is to be found at the do_verify() method's
  72. * documentation.
  73. *
  74. * @version $Id: Pass3bVerifier.java,v 1.1.1.1 2001/10/29 20:00:42 jvanzyl Exp $
  75. * @author <A HREF="http://www.inf.fu-berlin.de/~ehaase"/>Enver Haase</A>
  76. * @see #do_verify()
  77. */
  78. public final class Pass3bVerifier extends PassVerifier{
  79. /* TODO: Throughout pass 3b, upper halves of LONG and DOUBLE
  80. are represented by Type.UNKNOWN. This should be changed
  81. in favour of LONG_Upper and DOUBLE_Upper as in pass 2. */
  82. /**
  83. * An InstructionContextQueue is a utility class that holds
  84. * (InstructionContext, ArrayList) pairs in a Queue data structure.
  85. * This is used to hold information about InstructionContext objects
  86. * externally --- i.e. that information is not saved inside the
  87. * InstructionContext object itself. This is useful to save the
  88. * execution path of the symbolic execution of the
  89. * Pass3bVerifier - this is not information
  90. * that belongs into the InstructionContext object itself.
  91. * Only at "execute()"ing
  92. * time, an InstructionContext object will get the current information
  93. * we have about its symbolic execution predecessors.
  94. */
  95. private static final class InstructionContextQueue{
  96. private Vector ics = new Vector(); // Type: InstructionContext
  97. private Vector ecs = new Vector(); // Type: ArrayList (of InstructionContext)
  98. public void add(InstructionContext ic, ArrayList executionChain){
  99. ics.add(ic);
  100. ecs.add(executionChain);
  101. }
  102. public boolean isEmpty(){
  103. return ics.isEmpty();
  104. }
  105. public void remove(){
  106. this.remove(0);
  107. }
  108. public void remove(int i){
  109. ics.remove(i);
  110. ecs.remove(i);
  111. }
  112. public InstructionContext getIC(int i){
  113. return (InstructionContext) ics.get(i);
  114. }
  115. public ArrayList getEC(int i){
  116. return (ArrayList) ecs.get(i);
  117. }
  118. public int size(){
  119. return ics.size();
  120. }
  121. } // end Inner Class InstructionContextQueue
  122. /** In DEBUG mode, the verification algorithm is not randomized. */
  123. private static final boolean DEBUG = true;
  124. /** The Verifier that created this. */
  125. private Verifier myOwner;
  126. /** The method number to verify. */
  127. private int method_no;
  128. /**
  129. * This class should only be instantiated by a Verifier.
  130. *
  131. * @see com.sun.org.apache.bcel.internal.verifier.Verifier
  132. */
  133. public Pass3bVerifier(Verifier owner, int method_no){
  134. myOwner = owner;
  135. this.method_no = method_no;
  136. }
  137. /**
  138. * Whenever the outgoing frame
  139. * situation of an InstructionContext changes, all its successors are
  140. * put [back] into the queue [as if they were unvisited].
  141. * The proof of termination is about the existence of a
  142. * fix point of frame merging.
  143. */
  144. private void circulationPump(ControlFlowGraph cfg, InstructionContext start, Frame vanillaFrame, InstConstraintVisitor icv, ExecutionVisitor ev){
  145. final Random random = new Random();
  146. InstructionContextQueue icq = new InstructionContextQueue();
  147. start.execute(vanillaFrame, new ArrayList(), icv, ev); // new ArrayList() <=> no Instruction was executed before
  148. // => Top-Level routine (no jsr call before)
  149. icq.add(start, new ArrayList());
  150. // LOOP!
  151. while (!icq.isEmpty()){
  152. InstructionContext u;
  153. ArrayList ec;
  154. if (!DEBUG){
  155. int r = random.nextInt(icq.size());
  156. u = icq.getIC(r);
  157. ec = icq.getEC(r);
  158. icq.remove(r);
  159. }
  160. else{
  161. u = icq.getIC(0);
  162. ec = icq.getEC(0);
  163. icq.remove(0);
  164. }
  165. ArrayList oldchain = (ArrayList) (ec.clone());
  166. ArrayList newchain = (ArrayList) (ec.clone());
  167. newchain.add(u);
  168. if ((u.getInstruction().getInstruction()) instanceof RET){
  169. //System.err.println(u);
  170. // We can only follow _one_ successor, the one after the
  171. // JSR that was recently executed.
  172. RET ret = (RET) (u.getInstruction().getInstruction());
  173. ReturnaddressType t = (ReturnaddressType) u.getOutFrame(oldchain).getLocals().get(ret.getIndex());
  174. InstructionContext theSuccessor = cfg.contextOf(t.getTarget());
  175. // Sanity check
  176. InstructionContext lastJSR = null;
  177. int skip_jsr = 0;
  178. for (int ss=oldchain.size()-1; ss >= 0; ss--){
  179. if (skip_jsr < 0){
  180. throw new AssertionViolatedException("More RET than JSR in execution chain?!");
  181. }
  182. //System.err.println("+"+oldchain.get(ss));
  183. if (((InstructionContext) oldchain.get(ss)).getInstruction().getInstruction() instanceof JsrInstruction){
  184. if (skip_jsr == 0){
  185. lastJSR = (InstructionContext) oldchain.get(ss);
  186. break;
  187. }
  188. else{
  189. skip_jsr--;
  190. }
  191. }
  192. if (((InstructionContext) oldchain.get(ss)).getInstruction().getInstruction() instanceof RET){
  193. skip_jsr++;
  194. }
  195. }
  196. if (lastJSR == null){
  197. throw new AssertionViolatedException("RET without a JSR before in ExecutionChain?! EC: '"+oldchain+"'.");
  198. }
  199. JsrInstruction jsr = (JsrInstruction) (lastJSR.getInstruction().getInstruction());
  200. if ( theSuccessor != (cfg.contextOf(jsr.physicalSuccessor())) ){
  201. throw new AssertionViolatedException("RET '"+u.getInstruction()+"' info inconsistent: jump back to '"+theSuccessor+"' or '"+cfg.contextOf(jsr.physicalSuccessor())+"'?");
  202. }
  203. if (theSuccessor.execute(u.getOutFrame(oldchain), newchain, icv, ev)){
  204. icq.add(theSuccessor, (ArrayList) newchain.clone());
  205. }
  206. }
  207. else{// "not a ret"
  208. // Normal successors. Add them to the queue of successors.
  209. InstructionContext[] succs = u.getSuccessors();
  210. for (int s=0; s<succs.length; s++){
  211. InstructionContext v = succs[s];
  212. if (v.execute(u.getOutFrame(oldchain), newchain, icv, ev)){
  213. icq.add(v, (ArrayList) newchain.clone());
  214. }
  215. }
  216. }// end "not a ret"
  217. // Exception Handlers. Add them to the queue of successors.
  218. // [subroutines are never protected; mandated by JustIce]
  219. ExceptionHandler[] exc_hds = u.getExceptionHandlers();
  220. for (int s=0; s<exc_hds.length; s++){
  221. InstructionContext v = cfg.contextOf(exc_hds[s].getHandlerStart());
  222. // TODO: the "oldchain" and "newchain" is used to determine the subroutine
  223. // we're in (by searching for the last JSR) by the InstructionContext
  224. // implementation. Therefore, we should not use this chain mechanism
  225. // when dealing with exception handlers.
  226. // Example: a JSR with an exception handler as its successor does not
  227. // mean we're in a subroutine if we go to the exception handler.
  228. // We should address this problem later; by now we simply "cut" the chain
  229. // by using an empty chain for the exception handlers.
  230. //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){
  231. //icq.add(v, (ArrayList) newchain.clone());
  232. 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(), icv, ev)){
  233. icq.add(v, new ArrayList());
  234. }
  235. }
  236. }// while (!icq.isEmpty()) END
  237. InstructionHandle ih = start.getInstruction();
  238. do{
  239. if ((ih.getInstruction() instanceof ReturnInstruction) && (!(cfg.isDead(ih)))) {
  240. InstructionContext ic = cfg.contextOf(ih);
  241. Frame f = ic.getOutFrame(new ArrayList()); // TODO: This is buggy, we check only the top-level return instructions this way.
  242. LocalVariables lvs = f.getLocals();
  243. for (int i=0; i<lvs.maxLocals(); i++){
  244. if (lvs.get(i) instanceof UninitializedObjectType){
  245. this.addMessage("Warning: ReturnInstruction '"+ic+"' may leave method with an uninitialized object in the local variables array '"+lvs+"'.");
  246. }
  247. }
  248. OperandStack os = f.getStack();
  249. for (int i=0; i<os.size(); i++){
  250. if (os.peek(i) instanceof UninitializedObjectType){
  251. this.addMessage("Warning: ReturnInstruction '"+ic+"' may leave method with an uninitialized object on the operand stack '"+os+"'.");
  252. }
  253. }
  254. }
  255. }while ((ih = ih.getNext()) != null);
  256. }
  257. /**
  258. * Pass 3b implements the data flow analysis as described in the Java Virtual
  259. * Machine Specification, Second Edition.
  260. * Later versions will use LocalVariablesInfo objects to verify if the
  261. * verifier-inferred types and the class file's debug information (LocalVariables
  262. * attributes) match [TODO].
  263. *
  264. * @see com.sun.org.apache.bcel.internal.verifier.statics.LocalVariablesInfo
  265. * @see com.sun.org.apache.bcel.internal.verifier.statics.Pass2Verifier#getLocalVariablesInfo(int)
  266. */
  267. public VerificationResult do_verify(){
  268. if (! myOwner.doPass3a(method_no).equals(VerificationResult.VR_OK)){
  269. return VerificationResult.VR_NOTYET;
  270. }
  271. // Pass 3a ran before, so it's safe to assume the JavaClass object is
  272. // in the BCEL repository.
  273. JavaClass jc = Repository.lookupClass(myOwner.getClassName());
  274. ConstantPoolGen constantPoolGen = new ConstantPoolGen(jc.getConstantPool());
  275. // Init Visitors
  276. InstConstraintVisitor icv = new InstConstraintVisitor();
  277. icv.setConstantPoolGen(constantPoolGen);
  278. ExecutionVisitor ev = new ExecutionVisitor();
  279. ev.setConstantPoolGen(constantPoolGen);
  280. Method[] methods = jc.getMethods(); // Method no "method_no" exists, we ran Pass3a before on it!
  281. try{
  282. MethodGen mg = new MethodGen(methods[method_no], myOwner.getClassName(), constantPoolGen);
  283. icv.setMethodGen(mg);
  284. ////////////// DFA BEGINS HERE ////////////////
  285. if (! (mg.isAbstract() || mg.isNative()) ){ // IF mg HAS CODE (See pass 2)
  286. ControlFlowGraph cfg = new ControlFlowGraph(mg);
  287. // Build the initial frame situation for this method.
  288. Frame f = new Frame(mg.getMaxLocals(),mg.getMaxStack());
  289. if ( !mg.isStatic() ){
  290. if (mg.getName().equals(Constants.CONSTRUCTOR_NAME)){
  291. f._this = new UninitializedObjectType(new ObjectType(jc.getClassName()));
  292. f.getLocals().set(0, f._this);
  293. }
  294. else{
  295. f._this = null;
  296. f.getLocals().set(0, new ObjectType(jc.getClassName()));
  297. }
  298. }
  299. Type[] argtypes = mg.getArgumentTypes();
  300. int twoslotoffset = 0;
  301. for (int j=0; j<argtypes.length; j++){
  302. if (argtypes[j] == Type.SHORT || argtypes[j] == Type.BYTE || argtypes[j] == Type.CHAR || argtypes[j] == Type.BOOLEAN){
  303. argtypes[j] = Type.INT;
  304. }
  305. f.getLocals().set(twoslotoffset + j + (mg.isStatic()?0:1), argtypes[j]);
  306. if (argtypes[j].getSize() == 2){
  307. twoslotoffset++;
  308. f.getLocals().set(twoslotoffset + j + (mg.isStatic()?0:1), Type.UNKNOWN);
  309. }
  310. }
  311. circulationPump(cfg, cfg.contextOf(mg.getInstructionList().getStart()), f, icv, ev);
  312. }
  313. }
  314. catch (VerifierConstraintViolatedException ce){
  315. ce.extendMessage("Constraint violated in method '"+methods[method_no]+"':\n","");
  316. return new VerificationResult(VerificationResult.VERIFIED_REJECTED, ce.getMessage());
  317. }
  318. catch (RuntimeException re){
  319. // These are internal errors
  320. StringWriter sw = new StringWriter();
  321. PrintWriter pw = new PrintWriter(sw);
  322. re.printStackTrace(pw);
  323. 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");
  324. }
  325. return VerificationResult.VR_OK;
  326. }
  327. /** Returns the method number as supplied when instantiating. */
  328. public int getMethodNo(){
  329. return method_no;
  330. }
  331. }