Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

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