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.

Pass2Verifier.java 63KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490
  1. package org.aspectj.apache.bcel.verifier.statics;
  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.HashMap;
  56. import java.util.HashSet;
  57. import org.aspectj.apache.bcel.Constants;
  58. import org.aspectj.apache.bcel.Repository;
  59. import org.aspectj.apache.bcel.classfile.Attribute;
  60. import org.aspectj.apache.bcel.classfile.Code;
  61. import org.aspectj.apache.bcel.classfile.CodeException;
  62. import org.aspectj.apache.bcel.classfile.Constant;
  63. import org.aspectj.apache.bcel.classfile.ConstantClass;
  64. import org.aspectj.apache.bcel.classfile.ConstantDouble;
  65. import org.aspectj.apache.bcel.classfile.ConstantFieldref;
  66. import org.aspectj.apache.bcel.classfile.ConstantFloat;
  67. import org.aspectj.apache.bcel.classfile.ConstantInteger;
  68. import org.aspectj.apache.bcel.classfile.ConstantInterfaceMethodref;
  69. import org.aspectj.apache.bcel.classfile.ConstantLong;
  70. import org.aspectj.apache.bcel.classfile.ConstantMethodref;
  71. import org.aspectj.apache.bcel.classfile.ConstantNameAndType;
  72. import org.aspectj.apache.bcel.classfile.ConstantPool;
  73. import org.aspectj.apache.bcel.classfile.ConstantString;
  74. import org.aspectj.apache.bcel.classfile.ConstantUtf8;
  75. import org.aspectj.apache.bcel.classfile.ConstantValue;
  76. import org.aspectj.apache.bcel.classfile.Deprecated;
  77. import org.aspectj.apache.bcel.classfile.ExceptionTable;
  78. import org.aspectj.apache.bcel.classfile.Field;
  79. import org.aspectj.apache.bcel.classfile.InnerClass;
  80. import org.aspectj.apache.bcel.classfile.InnerClasses;
  81. import org.aspectj.apache.bcel.classfile.JavaClass;
  82. import org.aspectj.apache.bcel.classfile.LineNumber;
  83. import org.aspectj.apache.bcel.classfile.LineNumberTable;
  84. import org.aspectj.apache.bcel.classfile.LocalVariable;
  85. import org.aspectj.apache.bcel.classfile.LocalVariableTable;
  86. import org.aspectj.apache.bcel.classfile.Method;
  87. import org.aspectj.apache.bcel.classfile.Node;
  88. import org.aspectj.apache.bcel.classfile.SourceFile;
  89. import org.aspectj.apache.bcel.classfile.Synthetic;
  90. import org.aspectj.apache.bcel.classfile.Unknown;
  91. import org.aspectj.apache.bcel.generic.ArrayType;
  92. import org.aspectj.apache.bcel.generic.ObjectType;
  93. import org.aspectj.apache.bcel.generic.Type;
  94. import org.aspectj.apache.bcel.verifier.DescendingVisitor;
  95. import org.aspectj.apache.bcel.verifier.EmptyClassVisitor;
  96. import org.aspectj.apache.bcel.verifier.PassVerifier;
  97. import org.aspectj.apache.bcel.verifier.VerificationResult;
  98. import org.aspectj.apache.bcel.verifier.Verifier;
  99. import org.aspectj.apache.bcel.verifier.VerifierFactory;
  100. import org.aspectj.apache.bcel.verifier.exc.AssertionViolatedException;
  101. import org.aspectj.apache.bcel.verifier.exc.ClassConstraintException;
  102. import org.aspectj.apache.bcel.verifier.exc.LocalVariableInfoInconsistentException;
  103. /**
  104. * This PassVerifier verifies a class file according to pass 2 as described in The Java Virtual Machine Specification, 2nd edition.
  105. * More detailed information is to be found at the do_verify() method's documentation.
  106. *
  107. * @version $Id: Pass2Verifier.java,v 1.5 2009/09/10 15:35:05 aclement Exp $
  108. * @author <A HREF="https://www.inf.fu-berlin.de/~ehaase"/>Enver Haase</A>
  109. * @see #do_verify()
  110. */
  111. public final class Pass2Verifier extends PassVerifier implements Constants {
  112. /**
  113. * The LocalVariableInfo instances used by Pass3bVerifier. localVariablesInfos[i] denotes the information for the local
  114. * variables of method number i in the JavaClass this verifier operates on.
  115. */
  116. private LocalVariablesInfo[] localVariablesInfos;
  117. /** The Verifier that created this. */
  118. private Verifier myOwner;
  119. /**
  120. * Should only be instantiated by a Verifier.
  121. *
  122. * @see Verifier
  123. */
  124. public Pass2Verifier(Verifier owner) {
  125. myOwner = owner;
  126. }
  127. /**
  128. * Returns a LocalVariablesInfo object containing information about the usage of the local variables in the Code attribute of
  129. * the said method or <B>null</B> if the class file this Pass2Verifier operates on could not be pass-2-verified correctly. The
  130. * method number method_nr is the method you get using
  131. * <B>Repository.lookupClass(myOwner.getClassname()).getMethods()[method_nr];</B>. You should not add own information. Leave
  132. * that to JustIce.
  133. */
  134. public LocalVariablesInfo getLocalVariablesInfo(int method_nr) {
  135. if (this.verify() != VerificationResult.VR_OK)
  136. return null; // It's cached, don't worry.
  137. if (method_nr < 0 || method_nr >= localVariablesInfos.length) {
  138. throw new AssertionViolatedException("Method number out of range.");
  139. }
  140. return localVariablesInfos[method_nr];
  141. }
  142. /**
  143. * Pass 2 is the pass where static properties of the class file are checked without looking into "Code" arrays of methods. This
  144. * verification pass is usually invoked when a class is resolved; and it may be possible that this verification pass has to load
  145. * in other classes such as superclasses or implemented interfaces. Therefore, Pass 1 is run on them.<BR>
  146. * Note that most referenced classes are <B>not</B> loaded in for verification or for an existance check by this pass; only the
  147. * syntactical correctness of their names and descriptors (a.k.a. signatures) is checked.<BR>
  148. * Very few checks that conceptually belong here are delayed until pass 3a in JustIce. JustIce does not only check for
  149. * syntactical correctness but also for semantical sanity - therefore it needs access to the "Code" array of methods in a few
  150. * cases. Please see the pass 3a documentation, too.
  151. *
  152. * @see org.aspectj.apache.bcel.verifier.statics.Pass3aVerifier
  153. */
  154. @Override
  155. public VerificationResult do_verify() {
  156. VerificationResult vr1 = myOwner.doPass1();
  157. if (vr1.equals(VerificationResult.VR_OK)) {
  158. // For every method, we could have information about the local variables out of LocalVariableTable attributes of
  159. // the Code attributes.
  160. localVariablesInfos = new LocalVariablesInfo[Repository.lookupClass(myOwner.getClassName()).getMethods().length];
  161. VerificationResult vr = VerificationResult.VR_OK; // default.
  162. try {
  163. constant_pool_entries_satisfy_static_constraints();
  164. field_and_method_refs_are_valid();
  165. every_class_has_an_accessible_superclass();
  166. final_methods_are_not_overridden();
  167. } catch (ClassConstraintException cce) {
  168. vr = new VerificationResult(VerificationResult.VERIFIED_REJECTED, cce.getMessage());
  169. }
  170. return vr;
  171. } else
  172. return VerificationResult.VR_NOTYET;
  173. }
  174. /**
  175. * Ensures that every class has a super class and that <B>final</B> classes are not subclassed. This means, the class this
  176. * Pass2Verifier operates on has proper super classes (transitively) up to java.lang.Object. The reason for really loading (and
  177. * Pass1-verifying) all of those classes here is that we need them in Pass2 anyway to verify no final methods are overridden
  178. * (that could be declared anywhere in the ancestor hierarchy).
  179. *
  180. * @throws ClassConstraintException otherwise.
  181. */
  182. private void every_class_has_an_accessible_superclass() {
  183. HashSet<String> hs = new HashSet<String>(); // save class names to detect circular inheritance
  184. JavaClass jc = Repository.lookupClass(myOwner.getClassName());
  185. int supidx = -1;
  186. while (supidx != 0) {
  187. supidx = jc.getSuperclassNameIndex();
  188. if (supidx == 0) {
  189. if (jc != Repository.lookupClass(Type.OBJECT.getClassName())) {
  190. throw new ClassConstraintException("Superclass of '" + jc.getClassName() + "' missing but not "
  191. + Type.OBJECT.getClassName() + " itself!");
  192. }
  193. } else {
  194. String supername = jc.getSuperclassName();
  195. if (!hs.add(supername)) { // If supername already is in the list
  196. throw new ClassConstraintException("Circular superclass hierarchy detected.");
  197. }
  198. Verifier v = VerifierFactory.getVerifier(supername);
  199. VerificationResult vr = v.doPass1();
  200. if (vr != VerificationResult.VR_OK) {
  201. throw new ClassConstraintException("Could not load in ancestor class '" + supername + "'.");
  202. }
  203. jc = Repository.lookupClass(supername);
  204. if (jc.isFinal()) {
  205. throw new ClassConstraintException("Ancestor class '" + supername
  206. + "' has the FINAL access modifier and must therefore not be subclassed.");
  207. }
  208. }
  209. }
  210. }
  211. /**
  212. * Ensures that <B>final</B> methods are not overridden. <B>Precondition to run this method:
  213. * constant_pool_entries_satisfy_static_constraints() and every_class_has_an_accessible_superclass() have to be invoked before
  214. * (in that order).</B>
  215. *
  216. * @throws ClassConstraintException otherwise.
  217. * @see #constant_pool_entries_satisfy_static_constraints()
  218. * @see #every_class_has_an_accessible_superclass()
  219. */
  220. private void final_methods_are_not_overridden() {
  221. HashMap<String, String> hashmap = new HashMap<String, String>();
  222. JavaClass jc = Repository.lookupClass(myOwner.getClassName());
  223. int supidx = -1;
  224. while (supidx != 0) {
  225. supidx = jc.getSuperclassNameIndex();
  226. Method[] methods = jc.getMethods();
  227. for (int i = 0; i < methods.length; i++) {
  228. String name_and_sig = (methods[i].getName() + methods[i].getSignature());
  229. if (hashmap.containsKey(name_and_sig)) {
  230. if (methods[i].isFinal()) {
  231. throw new ClassConstraintException("Method '" + name_and_sig + "' in class '" + hashmap.get(name_and_sig)
  232. + "' overrides the final (not-overridable) definition in class '" + jc.getClassName() + "'.");
  233. } else {
  234. if (!methods[i].isStatic()) { // static methods don't inherit
  235. hashmap.put(name_and_sig, jc.getClassName());
  236. }
  237. }
  238. } else {
  239. if (!methods[i].isStatic()) { // static methods don't inherit
  240. hashmap.put(name_and_sig, jc.getClassName());
  241. }
  242. }
  243. }
  244. jc = Repository.lookupClass(jc.getSuperclassName()); // Well, for OBJECT this returns OBJECT so it works (could return
  245. // anything but must not throw an Exception).
  246. }
  247. }
  248. /**
  249. * Ensures that the constant pool entries satisfy the static constraints as described in The Java Virtual Machine Specification,
  250. * 2nd Edition.
  251. *
  252. * @throws ClassConstraintException otherwise.
  253. */
  254. private void constant_pool_entries_satisfy_static_constraints() {
  255. // Most of the consistency is handled internally by BCEL; here
  256. // we only have to verify if the indices of the constants point
  257. // to constants of the appropriate type and such.
  258. JavaClass jc = Repository.lookupClass(myOwner.getClassName());
  259. new CPESSC_Visitor(jc); // constructor implicitely traverses jc
  260. }
  261. /**
  262. * A Visitor class that ensures the constant pool satisfies the static constraints. The visitXXX() methods throw
  263. * ClassConstraintException instances otherwise.
  264. *
  265. * @see #constant_pool_entries_satisfy_static_constraints()
  266. */
  267. private class CPESSC_Visitor extends org.aspectj.apache.bcel.verifier.EmptyClassVisitor {
  268. private Class CONST_Class;
  269. /*
  270. * private Class CONST_Fieldref; private Class CONST_Methodref; private Class CONST_InterfaceMethodref;
  271. */
  272. private Class<ConstantString> CONST_String;
  273. private Class<ConstantInteger> CONST_Integer;
  274. private Class<ConstantFloat> CONST_Float;
  275. private Class<ConstantLong> CONST_Long;
  276. private Class<ConstantDouble> CONST_Double;
  277. private Class CONST_NameAndType;
  278. private Class CONST_Utf8;
  279. private final JavaClass jc;
  280. private final ConstantPool cp; // ==jc.getConstantPool() -- only here to save typing work and computing power.
  281. private final int cplen; // == cp.getLength() -- to save computing power.
  282. private DescendingVisitor carrier;
  283. private HashSet<String> field_names = new HashSet<String>();
  284. private HashSet<String> field_names_and_desc = new HashSet<String>();
  285. private HashSet<String> method_names_and_desc = new HashSet<String>();
  286. private CPESSC_Visitor(JavaClass _jc) {
  287. jc = _jc;
  288. cp = _jc.getConstantPool();
  289. cplen = cp.getLength();
  290. CONST_Class = org.aspectj.apache.bcel.classfile.ConstantClass.class;
  291. /*
  292. * CONST_Fieldref = org.aspectj.apache.bcel.classfile.ConstantFieldref.class; CONST_Methodref =
  293. * org.aspectj.apache.bcel.classfile.ConstantMethodref.class; CONST_InterfaceMethodref =
  294. * org.aspectj.apache.bcel.classfile.ConstantInterfaceMethodref.class;
  295. */
  296. CONST_String = org.aspectj.apache.bcel.classfile.ConstantString.class;
  297. CONST_Integer = org.aspectj.apache.bcel.classfile.ConstantInteger.class;
  298. CONST_Float = org.aspectj.apache.bcel.classfile.ConstantFloat.class;
  299. CONST_Long = org.aspectj.apache.bcel.classfile.ConstantLong.class;
  300. CONST_Double = org.aspectj.apache.bcel.classfile.ConstantDouble.class;
  301. CONST_NameAndType = org.aspectj.apache.bcel.classfile.ConstantNameAndType.class;
  302. CONST_Utf8 = org.aspectj.apache.bcel.classfile.ConstantUtf8.class;
  303. carrier = new DescendingVisitor(_jc, this);
  304. carrier.visit();
  305. }
  306. private void checkIndex(Node referrer, int index, Class shouldbe) {
  307. if ((index < 0) || (index >= cplen)) {
  308. throw new ClassConstraintException("Invalid index '" + index + "' used by '" + tostring(referrer) + "'.");
  309. }
  310. Constant c = cp.getConstant(index);
  311. if (!shouldbe.isInstance(c)) {
  312. /* String isnot = shouldbe.toString().substring(shouldbe.toString().lastIndexOf(".")+1); //Cut all before last "." */
  313. throw new ClassCastException("Illegal constant '" + tostring(c) + "' at index '" + index + "'. '"
  314. + tostring(referrer) + "' expects a '" + shouldbe + "'.");
  315. }
  316. }
  317. // /////////////////////////////////////
  318. // ClassFile structure (vmspec2 4.1) //
  319. // /////////////////////////////////////
  320. @Override
  321. public void visitJavaClass(JavaClass obj) {
  322. Attribute[] atts = obj.getAttributes();
  323. boolean foundSourceFile = false;
  324. boolean foundInnerClasses = false;
  325. // Is there an InnerClass referenced?
  326. // This is a costly check; existing verifiers don't do it!
  327. boolean hasInnerClass = new InnerClassDetector(jc).innerClassReferenced();
  328. for (int i = 0; i < atts.length; i++) {
  329. if ((!(atts[i] instanceof SourceFile)) && (!(atts[i] instanceof Deprecated))
  330. && (!(atts[i] instanceof InnerClasses)) && (!(atts[i] instanceof Synthetic))) {
  331. addMessage("Attribute '" + tostring(atts[i]) + "' as an attribute of the ClassFile structure '" + tostring(obj)
  332. + "' is unknown and will therefore be ignored.");
  333. }
  334. if (atts[i] instanceof SourceFile) {
  335. if (foundSourceFile == false)
  336. foundSourceFile = true;
  337. else
  338. throw new ClassConstraintException("A ClassFile structure (like '" + tostring(obj)
  339. + "') may have no more than one SourceFile attribute."); // vmspec2 4.7.7
  340. }
  341. if (atts[i] instanceof InnerClasses) {
  342. if (foundInnerClasses == false)
  343. foundInnerClasses = true;
  344. else {
  345. if (hasInnerClass) {
  346. throw new ClassConstraintException(
  347. "A Classfile structure (like '"
  348. + tostring(obj)
  349. + "') must have exactly one InnerClasses attribute if at least one Inner Class is referenced (which is the case). More than one InnerClasses attribute was found.");
  350. }
  351. }
  352. if (!hasInnerClass) {
  353. addMessage("No referenced Inner Class found, but InnerClasses attribute '" + tostring(atts[i])
  354. + "' found. Strongly suggest removal of that attribute.");
  355. }
  356. }
  357. }
  358. if (hasInnerClass && !foundInnerClasses) {
  359. // throw new
  360. // ClassConstraintException("A Classfile structure (like '"+tostring(obj)+"') must have exactly one InnerClasses attribute if at least one Inner Class is referenced (which is the case). No InnerClasses attribute was found.");
  361. // vmspec2, page 125 says it would be a constraint: but existing verifiers
  362. // don't check it and javac doesn't satisfy it when it comes to anonymous
  363. // inner classes
  364. addMessage("A Classfile structure (like '"
  365. + tostring(obj)
  366. + "') must have exactly one InnerClasses attribute if at least one Inner Class is referenced (which is the case). No InnerClasses attribute was found.");
  367. }
  368. }
  369. // ///////////////////////////
  370. // CONSTANTS (vmspec2 4.4) //
  371. // ///////////////////////////
  372. @Override
  373. public void visitConstantClass(ConstantClass obj) {
  374. if (obj.getTag() != Constants.CONSTANT_Class) {
  375. throw new ClassConstraintException("Wrong constant tag in '" + tostring(obj) + "'.");
  376. }
  377. checkIndex(obj, obj.getNameIndex(), CONST_Utf8);
  378. }
  379. @Override
  380. public void visitConstantFieldref(ConstantFieldref obj) {
  381. if (obj.getTag() != Constants.CONSTANT_Fieldref) {
  382. throw new ClassConstraintException("Wrong constant tag in '" + tostring(obj) + "'.");
  383. }
  384. checkIndex(obj, obj.getClassIndex(), CONST_Class);
  385. checkIndex(obj, obj.getNameAndTypeIndex(), CONST_NameAndType);
  386. }
  387. @Override
  388. public void visitConstantMethodref(ConstantMethodref obj) {
  389. if (obj.getTag() != Constants.CONSTANT_Methodref) {
  390. throw new ClassConstraintException("Wrong constant tag in '" + tostring(obj) + "'.");
  391. }
  392. checkIndex(obj, obj.getClassIndex(), CONST_Class);
  393. checkIndex(obj, obj.getNameAndTypeIndex(), CONST_NameAndType);
  394. }
  395. @Override
  396. public void visitConstantInterfaceMethodref(ConstantInterfaceMethodref obj) {
  397. if (obj.getTag() != Constants.CONSTANT_InterfaceMethodref) {
  398. throw new ClassConstraintException("Wrong constant tag in '" + tostring(obj) + "'.");
  399. }
  400. checkIndex(obj, obj.getClassIndex(), CONST_Class);
  401. checkIndex(obj, obj.getNameAndTypeIndex(), CONST_NameAndType);
  402. }
  403. @Override
  404. public void visitConstantString(ConstantString obj) {
  405. if (obj.getTag() != Constants.CONSTANT_String) {
  406. throw new ClassConstraintException("Wrong constant tag in '" + tostring(obj) + "'.");
  407. }
  408. checkIndex(obj, obj.getStringIndex(), CONST_Utf8);
  409. }
  410. @Override
  411. public void visitConstantInteger(ConstantInteger obj) {
  412. if (obj.getTag() != Constants.CONSTANT_Integer) {
  413. throw new ClassConstraintException("Wrong constant tag in '" + tostring(obj) + "'.");
  414. }
  415. // no indices to check
  416. }
  417. @Override
  418. public void visitConstantFloat(ConstantFloat obj) {
  419. if (obj.getTag() != Constants.CONSTANT_Float) {
  420. throw new ClassConstraintException("Wrong constant tag in '" + tostring(obj) + "'.");
  421. }
  422. // no indices to check
  423. }
  424. @Override
  425. public void visitConstantLong(ConstantLong obj) {
  426. if (obj.getTag() != Constants.CONSTANT_Long) {
  427. throw new ClassConstraintException("Wrong constant tag in '" + tostring(obj) + "'.");
  428. }
  429. // no indices to check
  430. }
  431. @Override
  432. public void visitConstantDouble(ConstantDouble obj) {
  433. if (obj.getTag() != Constants.CONSTANT_Double) {
  434. throw new ClassConstraintException("Wrong constant tag in '" + tostring(obj) + "'.");
  435. }
  436. // no indices to check
  437. }
  438. @Override
  439. public void visitConstantNameAndType(ConstantNameAndType obj) {
  440. if (obj.getTag() != Constants.CONSTANT_NameAndType) {
  441. throw new ClassConstraintException("Wrong constant tag in '" + tostring(obj) + "'.");
  442. }
  443. checkIndex(obj, obj.getNameIndex(), CONST_Utf8);
  444. // checkIndex(obj, obj.getDescriptorIndex(), CONST_Utf8); //inconsistently named in BCEL, see below.
  445. checkIndex(obj, obj.getSignatureIndex(), CONST_Utf8);
  446. }
  447. @Override
  448. public void visitConstantUtf8(ConstantUtf8 obj) {
  449. if (obj.getTag() != Constants.CONSTANT_Utf8) {
  450. throw new ClassConstraintException("Wrong constant tag in '" + tostring(obj) + "'.");
  451. }
  452. // no indices to check
  453. }
  454. // ////////////////////////
  455. // FIELDS (vmspec2 4.5) //
  456. // ////////////////////////
  457. @Override
  458. public void visitField(Field obj) {
  459. if (jc.isClass()) {
  460. int maxone = 0;
  461. if (obj.isPrivate())
  462. maxone++;
  463. if (obj.isProtected())
  464. maxone++;
  465. if (obj.isPublic())
  466. maxone++;
  467. if (maxone > 1) {
  468. throw new ClassConstraintException("Field '" + tostring(obj)
  469. + "' must only have at most one of its ACC_PRIVATE, ACC_PROTECTED, ACC_PUBLIC modifiers set.");
  470. }
  471. if (obj.isFinal() && obj.isVolatile()) {
  472. throw new ClassConstraintException("Field '" + tostring(obj)
  473. + "' must only have at most one of its ACC_FINAL, ACC_VOLATILE modifiers set.");
  474. }
  475. } else { // isInterface!
  476. if (!obj.isPublic()) {
  477. throw new ClassConstraintException("Interface field '" + tostring(obj)
  478. + "' must have the ACC_PUBLIC modifier set but hasn't!");
  479. }
  480. if (!obj.isStatic()) {
  481. throw new ClassConstraintException("Interface field '" + tostring(obj)
  482. + "' must have the ACC_STATIC modifier set but hasn't!");
  483. }
  484. if (!obj.isFinal()) {
  485. throw new ClassConstraintException("Interface field '" + tostring(obj)
  486. + "' must have the ACC_FINAL modifier set but hasn't!");
  487. }
  488. }
  489. if ((obj.getModifiers() & ~(ACC_PUBLIC | ACC_PRIVATE | ACC_PROTECTED | ACC_STATIC | ACC_FINAL | ACC_VOLATILE | ACC_TRANSIENT)) > 0) {
  490. addMessage("Field '"
  491. + tostring(obj)
  492. + "' has access flag(s) other than ACC_PUBLIC, ACC_PRIVATE, ACC_PROTECTED, ACC_STATIC, ACC_FINAL, ACC_VOLATILE, ACC_TRANSIENT set (ignored).");
  493. }
  494. checkIndex(obj, obj.getNameIndex(), CONST_Utf8);
  495. String name = obj.getName();
  496. if (!validFieldName(name)) {
  497. throw new ClassConstraintException("Field '" + tostring(obj) + "' has illegal name '" + obj.getName() + "'.");
  498. }
  499. // A descriptor is often named signature in BCEL
  500. checkIndex(obj, obj.getSignatureIndex(), CONST_Utf8);
  501. String sig = ((ConstantUtf8) (cp.getConstant(obj.getSignatureIndex()))).getValue(); // Field or Method
  502. // signature(=descriptor)
  503. try {
  504. Type.getType(sig); /* Don't need the return value */
  505. } catch (ClassFormatError cfe) { // sometimes BCEL is a little harsh describing exceptional situations.
  506. throw new ClassConstraintException("Illegal descriptor (==signature) '" + sig + "' used by '" + tostring(obj)
  507. + "'.");
  508. }
  509. String nameanddesc = (name + sig);
  510. if (field_names_and_desc.contains(nameanddesc)) {
  511. throw new ClassConstraintException("No two fields (like '" + tostring(obj)
  512. + "') are allowed have same names and descriptors!");
  513. }
  514. if (field_names.contains(name)) {
  515. addMessage("More than one field of name '" + name
  516. + "' detected (but with different type descriptors). This is very unusual.");
  517. }
  518. field_names_and_desc.add(nameanddesc);
  519. field_names.add(name);
  520. Attribute[] atts = obj.getAttributes();
  521. for (int i = 0; i < atts.length; i++) {
  522. if ((!(atts[i] instanceof ConstantValue)) && (!(atts[i] instanceof Synthetic))
  523. && (!(atts[i] instanceof Deprecated))) {
  524. addMessage("Attribute '" + tostring(atts[i]) + "' as an attribute of Field '" + tostring(obj)
  525. + "' is unknown and will therefore be ignored.");
  526. }
  527. if (!(atts[i] instanceof ConstantValue)) {
  528. addMessage("Attribute '" + tostring(atts[i]) + "' as an attribute of Field '" + tostring(obj)
  529. + "' is not a ConstantValue and is therefore only of use for debuggers and such.");
  530. }
  531. }
  532. }
  533. // /////////////////////////
  534. // METHODS (vmspec2 4.6) //
  535. // /////////////////////////
  536. @Override
  537. public void visitMethod(Method obj) {
  538. checkIndex(obj, obj.getNameIndex(), CONST_Utf8);
  539. String name = obj.getName();
  540. if (!validMethodName(name, true)) {
  541. throw new ClassConstraintException("Method '" + tostring(obj) + "' has illegal name '" + name + "'.");
  542. }
  543. // A descriptor is often named signature in BCEL
  544. checkIndex(obj, obj.getSignatureIndex(), CONST_Utf8);
  545. String sig = ((ConstantUtf8) (cp.getConstant(obj.getSignatureIndex()))).getValue(); // Method's signature(=descriptor)
  546. Type t;
  547. Type[] ts; // needed below the try block.
  548. try {
  549. t = Type.getReturnType(sig);
  550. ts = Type.getArgumentTypes(sig);
  551. } catch (ClassFormatError cfe) {
  552. // Well, BCEL sometimes is a little harsh describing exceptional situations.
  553. throw new ClassConstraintException("Illegal descriptor (==signature) '" + sig + "' used by Method '"
  554. + tostring(obj) + "'.");
  555. }
  556. // Check if referenced objects exist.
  557. Type act = t;
  558. if (act instanceof ArrayType)
  559. act = ((ArrayType) act).getBasicType();
  560. if (act instanceof ObjectType) {
  561. Verifier v = VerifierFactory.getVerifier(((ObjectType) act).getClassName());
  562. VerificationResult vr = v.doPass1();
  563. if (vr != VerificationResult.VR_OK) {
  564. throw new ClassConstraintException("Method '" + tostring(obj)
  565. + "' has a return type that does not pass verification pass 1: '" + vr + "'.");
  566. }
  567. }
  568. for (int i = 0; i < ts.length; i++) {
  569. act = ts[i];
  570. if (act instanceof ArrayType)
  571. act = ((ArrayType) act).getBasicType();
  572. if (act instanceof ObjectType) {
  573. Verifier v = VerifierFactory.getVerifier(((ObjectType) act).getClassName());
  574. VerificationResult vr = v.doPass1();
  575. if (vr != VerificationResult.VR_OK) {
  576. throw new ClassConstraintException("Method '" + tostring(obj)
  577. + "' has an argument type that does not pass verification pass 1: '" + vr + "'.");
  578. }
  579. }
  580. }
  581. // Nearly forgot this! Funny return values are allowed, but a non-empty arguments list makes a different method out of
  582. // it!
  583. if (name.equals(STATIC_INITIALIZER_NAME) && (ts.length != 0)) {
  584. throw new ClassConstraintException(
  585. "Method '"
  586. + tostring(obj)
  587. + "' has illegal name '"
  588. + name
  589. + "'. It's name resembles the class or interface initialization method which it isn't because of its arguments (==descriptor).");
  590. }
  591. if (jc.isClass()) {
  592. int maxone = 0;
  593. if (obj.isPrivate())
  594. maxone++;
  595. if (obj.isProtected())
  596. maxone++;
  597. if (obj.isPublic())
  598. maxone++;
  599. if (maxone > 1) {
  600. throw new ClassConstraintException("Method '" + tostring(obj)
  601. + "' must only have at most one of its ACC_PRIVATE, ACC_PROTECTED, ACC_PUBLIC modifiers set.");
  602. }
  603. if (obj.isAbstract()) {
  604. if (obj.isFinal())
  605. throw new ClassConstraintException("Abstract method '" + tostring(obj)
  606. + "' must not have the ACC_FINAL modifier set.");
  607. if (obj.isNative())
  608. throw new ClassConstraintException("Abstract method '" + tostring(obj)
  609. + "' must not have the ACC_NATIVE modifier set.");
  610. if (obj.isPrivate())
  611. throw new ClassConstraintException("Abstract method '" + tostring(obj)
  612. + "' must not have the ACC_PRIVATE modifier set.");
  613. if (obj.isStatic())
  614. throw new ClassConstraintException("Abstract method '" + tostring(obj)
  615. + "' must not have the ACC_STATIC modifier set.");
  616. if (obj.isStrictfp())
  617. throw new ClassConstraintException("Abstract method '" + tostring(obj)
  618. + "' must not have the ACC_STRICT modifier set.");
  619. if (obj.isSynchronized())
  620. throw new ClassConstraintException("Abstract method '" + tostring(obj)
  621. + "' must not have the ACC_SYNCHRONIZED modifier set.");
  622. }
  623. } else { // isInterface!
  624. if (!name.equals(STATIC_INITIALIZER_NAME)) {// vmspec2, p.116, 2nd paragraph
  625. if (!obj.isPublic()) {
  626. throw new ClassConstraintException("Interface method '" + tostring(obj)
  627. + "' must have the ACC_PUBLIC modifier set but hasn't!");
  628. }
  629. if (!obj.isAbstract()) {
  630. throw new ClassConstraintException("Interface method '" + tostring(obj)
  631. + "' must have the ACC_STATIC modifier set but hasn't!");
  632. }
  633. if (obj.isPrivate() || obj.isProtected() || obj.isStatic() || obj.isFinal() || obj.isSynchronized()
  634. || obj.isNative() || obj.isStrictfp()) {
  635. throw new ClassConstraintException(
  636. "Interface method '"
  637. + tostring(obj)
  638. + "' must not have any of the ACC_PRIVATE, ACC_PROTECTED, ACC_STATIC, ACC_FINAL, ACC_SYNCHRONIZED, ACC_NATIVE, ACC_ABSTRACT, ACC_STRICT modifiers set.");
  639. }
  640. }
  641. }
  642. // A specific instance initialization method... (vmspec2,Page 116).
  643. if (name.equals(CONSTRUCTOR_NAME)) {
  644. // ..may have at most one of ACC_PRIVATE, ACC_PROTECTED, ACC_PUBLIC set: is checked above.
  645. // ..may also have ACC_STRICT set, but none of the other flags in table 4.5 (vmspec2, page 115)
  646. if (obj.isStatic() || obj.isFinal() || obj.isSynchronized() || obj.isNative() || obj.isAbstract()) {
  647. throw new ClassConstraintException(
  648. "Instance initialization method '"
  649. + tostring(obj)
  650. + "' must not have any of the ACC_STATIC, ACC_FINAL, ACC_SYNCHRONIZED, ACC_NATIVE, ACC_ABSTRACT modifiers set.");
  651. }
  652. }
  653. // Class and interface initialization methods...
  654. if (name.equals(STATIC_INITIALIZER_NAME)) {
  655. if ((obj.getModifiers() & (~ACC_STRICT)) > 0) {
  656. addMessage("Class or interface initialization method '" + tostring(obj)
  657. + "' has superfluous access modifier(s) set: everything but ACC_STRICT is ignored.");
  658. }
  659. if (obj.isAbstract()) {
  660. throw new ClassConstraintException(
  661. "Class or interface initialization method '"
  662. + tostring(obj)
  663. + "' must not be abstract. This contradicts the Java Language Specification, Second Edition (which omits this constraint) but is common practice of existing verifiers.");
  664. }
  665. }
  666. if ((obj.getModifiers() & ~(ACC_PUBLIC | ACC_PRIVATE | ACC_PROTECTED | ACC_STATIC | ACC_FINAL | ACC_SYNCHRONIZED
  667. | ACC_NATIVE | ACC_ABSTRACT | ACC_STRICT)) > 0) {
  668. addMessage("Method '"
  669. + tostring(obj)
  670. + "' has access flag(s) other than ACC_PUBLIC, ACC_PRIVATE, ACC_PROTECTED, ACC_STATIC, ACC_FINAL, ACC_SYNCHRONIZED, ACC_NATIVE, ACC_ABSTRACT, ACC_STRICT set (ignored).");
  671. }
  672. String nameanddesc = (name + sig);
  673. if (method_names_and_desc.contains(nameanddesc)) {
  674. throw new ClassConstraintException("No two methods (like '" + tostring(obj)
  675. + "') are allowed have same names and desciptors!");
  676. }
  677. method_names_and_desc.add(nameanddesc);
  678. Attribute[] atts = obj.getAttributes();
  679. int num_code_atts = 0;
  680. for (int i = 0; i < atts.length; i++) {
  681. if ((!(atts[i] instanceof Code)) && (!(atts[i] instanceof ExceptionTable)) && (!(atts[i] instanceof Synthetic))
  682. && (!(atts[i] instanceof Deprecated))) {
  683. addMessage("Attribute '" + tostring(atts[i]) + "' as an attribute of Method '" + tostring(obj)
  684. + "' is unknown and will therefore be ignored.");
  685. }
  686. if ((!(atts[i] instanceof Code)) && (!(atts[i] instanceof ExceptionTable))) {
  687. addMessage("Attribute '" + tostring(atts[i]) + "' as an attribute of Method '" + tostring(obj)
  688. + "' is neither Code nor Exceptions and is therefore only of use for debuggers and such.");
  689. }
  690. if ((atts[i] instanceof Code) && (obj.isNative() || obj.isAbstract())) {
  691. throw new ClassConstraintException("Native or abstract methods like '" + tostring(obj)
  692. + "' must not have a Code attribute like '" + tostring(atts[i]) + "'."); // vmspec2 page120, 4.7.3
  693. }
  694. if (atts[i] instanceof Code)
  695. num_code_atts++;
  696. }
  697. if (!obj.isNative() && !obj.isAbstract() && num_code_atts != 1) {
  698. throw new ClassConstraintException("Non-native, non-abstract methods like '" + tostring(obj)
  699. + "' must have exactly one Code attribute (found: " + num_code_atts + ").");
  700. }
  701. }
  702. // /////////////////////////////////////////////////////
  703. // ClassFile-structure-ATTRIBUTES (vmspec2 4.1, 4.7) //
  704. // /////////////////////////////////////////////////////
  705. public void visitSourceFile(SourceFile obj) {// vmspec2 4.7.7
  706. // zero or one SourceFile attr per ClassFile: see visitJavaClass()
  707. checkIndex(obj, obj.getNameIndex(), CONST_Utf8);
  708. String name = ((ConstantUtf8) cp.getConstant(obj.getNameIndex())).getValue();
  709. if (!name.equals("SourceFile")) {
  710. throw new ClassConstraintException("The SourceFile attribute '" + tostring(obj)
  711. + "' is not correctly named 'SourceFile' but '" + name + "'.");
  712. }
  713. checkIndex(obj, obj.getSourceFileIndex(), CONST_Utf8);
  714. String sourcefilename = ((ConstantUtf8) cp.getConstant(obj.getSourceFileIndex())).getValue(); // ==obj.getSourceFileName()
  715. // ?
  716. String sourcefilenamelc = sourcefilename.toLowerCase();
  717. if ((sourcefilename.indexOf('/') != -1) || (sourcefilename.indexOf('\\') != -1) || (sourcefilename.indexOf(':') != -1)
  718. || (sourcefilenamelc.lastIndexOf(".java") == -1)) {
  719. addMessage("SourceFile attribute '"
  720. + tostring(obj)
  721. + "' has a funny name: remember not to confuse certain parsers working on javap's output. Also, this name ('"
  722. + sourcefilename + "') is considered an unqualified (simple) file name only.");
  723. }
  724. }
  725. public void visitDeprecated(Deprecated obj) {// vmspec2 4.7.10
  726. checkIndex(obj, obj.getNameIndex(), CONST_Utf8);
  727. String name = ((ConstantUtf8) cp.getConstant(obj.getNameIndex())).getValue();
  728. if (!name.equals("Deprecated")) {
  729. throw new ClassConstraintException("The Deprecated attribute '" + tostring(obj)
  730. + "' is not correctly named 'Deprecated' but '" + name + "'.");
  731. }
  732. }
  733. public void visitSynthetic(Synthetic obj) {// vmspec2 4.7.6
  734. checkIndex(obj, obj.getNameIndex(), CONST_Utf8);
  735. String name = ((ConstantUtf8) cp.getConstant(obj.getNameIndex())).getValue();
  736. if (!name.equals("Synthetic")) {
  737. throw new ClassConstraintException("The Synthetic attribute '" + tostring(obj)
  738. + "' is not correctly named 'Synthetic' but '" + name + "'.");
  739. }
  740. }
  741. public void visitInnerClasses(InnerClasses obj) {// vmspec2 4.7.5
  742. // exactly one InnerClasses attr per ClassFile if some inner class is refernced: see visitJavaClass()
  743. checkIndex(obj, obj.getNameIndex(), CONST_Utf8);
  744. String name = ((ConstantUtf8) cp.getConstant(obj.getNameIndex())).getValue();
  745. if (!name.equals("InnerClasses")) {
  746. throw new ClassConstraintException("The InnerClasses attribute '" + tostring(obj)
  747. + "' is not correctly named 'InnerClasses' but '" + name + "'.");
  748. }
  749. InnerClass[] ics = obj.getInnerClasses();
  750. for (int i = 0; i < ics.length; i++) {
  751. checkIndex(obj, ics[i].getInnerClassIndex(), CONST_Class);
  752. int outer_idx = ics[i].getOuterClassIndex();
  753. if (outer_idx != 0) {
  754. checkIndex(obj, outer_idx, CONST_Class);
  755. }
  756. int innername_idx = ics[i].getInnerNameIndex();
  757. if (innername_idx != 0) {
  758. checkIndex(obj, innername_idx, CONST_Utf8);
  759. }
  760. int acc = ics[i].getInnerAccessFlags();
  761. acc = acc & (~(ACC_PUBLIC | ACC_PRIVATE | ACC_PROTECTED | ACC_STATIC | ACC_FINAL | ACC_INTERFACE | ACC_ABSTRACT));
  762. if (acc != 0) {
  763. addMessage("Unknown access flag for inner class '" + tostring(ics[i]) + "' set (InnerClasses attribute '"
  764. + tostring(obj) + "').");
  765. }
  766. }
  767. // Semantical consistency is not yet checked by Sun, see vmspec2 4.7.5.
  768. // [marked TODO in JustIce]
  769. }
  770. // //////////////////////////////////////////////////////
  771. // field_info-structure-ATTRIBUTES (vmspec2 4.5, 4.7) //
  772. // //////////////////////////////////////////////////////
  773. public void visitConstantValue(ConstantValue obj) {// vmspec2 4.7.2
  774. // Despite its name, this really is an Attribute,
  775. // not a constant!
  776. checkIndex(obj, obj.getNameIndex(), CONST_Utf8);
  777. String name = ((ConstantUtf8) cp.getConstant(obj.getNameIndex())).getValue();
  778. if (!name.equals("ConstantValue")) {
  779. throw new ClassConstraintException("The ConstantValue attribute '" + tostring(obj)
  780. + "' is not correctly named 'ConstantValue' but '" + name + "'.");
  781. }
  782. Object pred = carrier.predecessor();
  783. if (pred instanceof Field) { // ConstantValue attributes are quite senseless if the predecessor is not a field.
  784. Field f = (Field) pred;
  785. // Field constraints have been checked before -- so we are safe using their type information.
  786. Type field_type = Type.getType(((ConstantUtf8) (cp.getConstant(f.getSignatureIndex()))).getValue());
  787. int index = obj.getConstantValueIndex();
  788. if ((index < 0) || (index >= cplen)) {
  789. throw new ClassConstraintException("Invalid index '" + index + "' used by '" + tostring(obj) + "'.");
  790. }
  791. Constant c = cp.getConstant(index);
  792. if (CONST_Long.isInstance(c) && field_type.equals(Type.LONG)) {
  793. return;
  794. }
  795. if (CONST_Float.isInstance(c) && field_type.equals(Type.FLOAT)) {
  796. return;
  797. }
  798. if (CONST_Double.isInstance(c) && field_type.equals(Type.DOUBLE)) {
  799. return;
  800. }
  801. if (CONST_Integer.isInstance(c)
  802. && (field_type.equals(Type.INT) || field_type.equals(Type.SHORT) || field_type.equals(Type.CHAR)
  803. || field_type.equals(Type.BYTE) || field_type.equals(Type.BOOLEAN))) {
  804. return;
  805. }
  806. if (CONST_String.isInstance(c) && field_type.equals(Type.STRING)) {
  807. return;
  808. }
  809. throw new ClassConstraintException("Illegal type of ConstantValue '" + obj + "' embedding Constant '" + c
  810. + "'. It is referenced by field '" + tostring(f) + "' expecting a different type: '" + field_type + "'.");
  811. }
  812. }
  813. // SYNTHETIC: see above
  814. // DEPRECATED: see above
  815. // ///////////////////////////////////////////////////////
  816. // method_info-structure-ATTRIBUTES (vmspec2 4.6, 4.7) //
  817. // ///////////////////////////////////////////////////////
  818. public void visitCode(Code obj) {// vmspec2 4.7.3
  819. // No code attribute allowed for native or abstract methods: see visitMethod(Method).
  820. // Code array constraints are checked in Pass3 (3a and 3b).
  821. checkIndex(obj, obj.getNameIndex(), CONST_Utf8);
  822. String name = ((ConstantUtf8) cp.getConstant(obj.getNameIndex())).getValue();
  823. if (!name.equals("Code")) {
  824. throw new ClassConstraintException("The Code attribute '" + tostring(obj) + "' is not correctly named 'Code' but '"
  825. + name + "'.");
  826. }
  827. Method m = null; // satisfy compiler
  828. if (!(carrier.predecessor() instanceof Method)) {
  829. addMessage("Code attribute '" + tostring(obj) + "' is not declared in a method_info structure but in '"
  830. + carrier.predecessor() + "'. Ignored.");
  831. return;
  832. } else {
  833. m = (Method) carrier.predecessor(); // we can assume this method was visited before;
  834. // i.e. the data consistency was verified.
  835. }
  836. if (obj.getCode().length == 0) {
  837. throw new ClassConstraintException("Code array of Code attribute '" + tostring(obj) + "' (method '" + m
  838. + "') must not be empty.");
  839. }
  840. // In JustIce, the check for correct offsets into the code array is delayed to Pass 3a.
  841. CodeException[] exc_table = obj.getExceptionTable();
  842. for (int i = 0; i < exc_table.length; i++) {
  843. int exc_index = exc_table[i].getCatchType();
  844. if (exc_index != 0) { // if 0, it catches all Throwables
  845. checkIndex(obj, exc_index, CONST_Class);
  846. ConstantClass cc = (ConstantClass) (cp.getConstant(exc_index));
  847. checkIndex(cc, cc.getNameIndex(), CONST_Utf8); // cannot be sure this ConstantClass has already been visited
  848. // (checked)!
  849. String cname = ((ConstantUtf8) cp.getConstant(cc.getNameIndex())).getValue().replace('/', '.');
  850. Verifier v = VerifierFactory.getVerifier(cname);
  851. VerificationResult vr = v.doPass1();
  852. if (vr != VerificationResult.VR_OK) {
  853. throw new ClassConstraintException("Code attribute '" + tostring(obj) + "' (method '" + m
  854. + "') has an exception_table entry '" + tostring(exc_table[i]) + "' that references '" + cname
  855. + "' as an Exception but it does not pass verification pass 1: " + vr);
  856. } else {
  857. // We cannot safely trust any other "instanceof" mechanism. We need to transitively verify
  858. // the ancestor hierarchy.
  859. JavaClass e = Repository.lookupClass(cname);
  860. JavaClass t = Repository.lookupClass(Type.THROWABLE.getClassName());
  861. JavaClass o = Repository.lookupClass(Type.OBJECT.getClassName());
  862. while (e != o) {
  863. if (e == t)
  864. break; // It's a subclass of Throwable, OKAY, leave.
  865. v = VerifierFactory.getVerifier(e.getSuperclassName());
  866. vr = v.doPass1();
  867. if (vr != VerificationResult.VR_OK) {
  868. throw new ClassConstraintException("Code attribute '" + tostring(obj) + "' (method '" + m
  869. + "') has an exception_table entry '" + tostring(exc_table[i]) + "' that references '"
  870. + cname + "' as an Exception but '" + e.getSuperclassName()
  871. + "' in the ancestor hierachy does not pass verification pass 1: " + vr);
  872. } else {
  873. e = Repository.lookupClass(e.getSuperclassName());
  874. }
  875. }
  876. if (e != t)
  877. throw new ClassConstraintException("Code attribute '" + tostring(obj) + "' (method '" + m
  878. + "') has an exception_table entry '" + tostring(exc_table[i]) + "' that references '" + cname
  879. + "' as an Exception but it is not a subclass of '" + t.getClassName() + "'.");
  880. }
  881. }
  882. }
  883. // Create object for local variables information
  884. // This is highly unelegant due to usage of the Visitor pattern.
  885. // TODO: rework it.
  886. int method_number = -1;
  887. Method[] ms = Repository.lookupClass(myOwner.getClassName()).getMethods();
  888. for (int mn = 0; mn < ms.length; mn++) {
  889. if (m == ms[mn]) {
  890. method_number = mn;
  891. break;
  892. }
  893. }
  894. if (method_number < 0) { // Mmmmh. Can we be sure BCEL does not sometimes instantiate new objects?
  895. throw new AssertionViolatedException(
  896. "Could not find a known BCEL Method object in the corresponding BCEL JavaClass object.");
  897. }
  898. localVariablesInfos[method_number] = new LocalVariablesInfo(obj.getMaxLocals());
  899. int num_of_lvt_attribs = 0;
  900. // Now iterate through the attributes the Code attribute has.
  901. Attribute[] atts = obj.getAttributes();
  902. for (int a = 0; a < atts.length; a++) {
  903. if ((!(atts[a] instanceof LineNumberTable)) && (!(atts[a] instanceof LocalVariableTable))) {
  904. addMessage("Attribute '" + tostring(atts[a]) + "' as an attribute of Code attribute '" + tostring(obj)
  905. + "' (method '" + m + "') is unknown and will therefore be ignored.");
  906. } else {// LineNumberTable or LocalVariableTable
  907. addMessage("Attribute '" + tostring(atts[a]) + "' as an attribute of Code attribute '" + tostring(obj)
  908. + "' (method '" + m + "') will effectively be ignored and is only useful for debuggers and such.");
  909. }
  910. // LocalVariableTable check (partially delayed to Pass3a).
  911. // Here because its easier to collect the information of the
  912. // (possibly more than one) LocalVariableTables belonging to
  913. // one certain Code attribute.
  914. if (atts[a] instanceof LocalVariableTable) { // checks conforming to vmspec2 4.7.9
  915. LocalVariableTable lvt = (LocalVariableTable) atts[a];
  916. checkIndex(lvt, lvt.getNameIndex(), CONST_Utf8);
  917. String lvtname = ((ConstantUtf8) cp.getConstant(lvt.getNameIndex())).getValue();
  918. if (!lvtname.equals("LocalVariableTable")) {
  919. throw new ClassConstraintException("The LocalVariableTable attribute '" + tostring(lvt)
  920. + "' is not correctly named 'LocalVariableTable' but '" + lvtname + "'.");
  921. }
  922. Code code = obj;
  923. // In JustIce, the check for correct offsets into the code array is delayed to Pass 3a.
  924. LocalVariable[] localvariables = lvt.getLocalVariableTable();
  925. for (int i = 0; i < localvariables.length; i++) {
  926. checkIndex(lvt, localvariables[i].getNameIndex(), CONST_Utf8);
  927. String localname = ((ConstantUtf8) cp.getConstant(localvariables[i].getNameIndex())).getValue();
  928. if (!validJavaIdentifier(localname)) {
  929. throw new ClassConstraintException("LocalVariableTable '" + tostring(lvt)
  930. + "' references a local variable by the name '" + localname
  931. + "' which is not a legal Java simple name.");
  932. }
  933. checkIndex(lvt, localvariables[i].getSignatureIndex(), CONST_Utf8);
  934. String localsig = ((ConstantUtf8) (cp.getConstant(localvariables[i].getSignatureIndex()))).getValue(); // Local
  935. // signature(=descriptor)
  936. Type t;
  937. try {
  938. t = Type.getType(localsig);
  939. } catch (ClassFormatError cfe) { // sometimes BCEL is a little harsh describing exceptional situations.
  940. throw new ClassConstraintException("Illegal descriptor (==signature) '" + localsig
  941. + "' used by LocalVariable '" + tostring(localvariables[i]) + "' referenced by '"
  942. + tostring(lvt) + "'.");
  943. }
  944. int localindex = localvariables[i].getIndex();
  945. if (((t == Type.LONG || t == Type.DOUBLE) ? localindex + 1 : localindex) >= code.getMaxLocals()) {
  946. throw new ClassConstraintException("LocalVariableTable attribute '" + tostring(lvt)
  947. + "' references a LocalVariable '" + tostring(localvariables[i])
  948. + "' with an index that exceeds the surrounding Code attribute's max_locals value of '"
  949. + code.getMaxLocals() + "'.");
  950. }
  951. try {
  952. localVariablesInfos[method_number].add(localindex, localname, localvariables[i].getStartPC(),
  953. localvariables[i].getLength(), t);
  954. } catch (LocalVariableInfoInconsistentException lviie) {
  955. throw new ClassConstraintException("Conflicting information in LocalVariableTable '" + tostring(lvt)
  956. + "' found in Code attribute '" + tostring(obj) + "' (method '" + tostring(m) + "'). "
  957. + lviie.getMessage());
  958. }
  959. }// for all local variables localvariables[i] in the LocalVariableTable attribute atts[a] END
  960. num_of_lvt_attribs++;
  961. if (num_of_lvt_attribs > obj.getMaxLocals()) {
  962. throw new ClassConstraintException(
  963. "Number of LocalVariableTable attributes of Code attribute '"
  964. + tostring(obj)
  965. + "' (method '"
  966. + tostring(m)
  967. + "') exceeds number of local variable slots '"
  968. + obj.getMaxLocals()
  969. + "' ('There may be no more than one LocalVariableTable attribute per local variable in the Code attribute.').");
  970. }
  971. }// if atts[a] instanceof LocalVariableTable END
  972. }// for all attributes atts[a] END
  973. }// visitCode(Code) END
  974. public void visitExceptionTable(ExceptionTable obj) {// vmspec2 4.7.4
  975. // incorrectly named, it's the Exceptions attribute (vmspec2 4.7.4)
  976. checkIndex(obj, obj.getNameIndex(), CONST_Utf8);
  977. String name = ((ConstantUtf8) cp.getConstant(obj.getNameIndex())).getValue();
  978. if (!name.equals("Exceptions")) {
  979. throw new ClassConstraintException("The Exceptions attribute '" + tostring(obj)
  980. + "' is not correctly named 'Exceptions' but '" + name + "'.");
  981. }
  982. int[] exc_indices = obj.getExceptionIndexTable();
  983. for (int i = 0; i < exc_indices.length; i++) {
  984. checkIndex(obj, exc_indices[i], CONST_Class);
  985. ConstantClass cc = (ConstantClass) (cp.getConstant(exc_indices[i]));
  986. checkIndex(cc, cc.getNameIndex(), CONST_Utf8); // cannot be sure this ConstantClass has already been visited
  987. // (checked)!
  988. String cname = ((ConstantUtf8) cp.getConstant(cc.getNameIndex())).getValue().replace('/', '.'); // convert internal
  989. // notation
  990. // on-the-fly to
  991. // external notation
  992. Verifier v = VerifierFactory.getVerifier(cname);
  993. VerificationResult vr = v.doPass1();
  994. if (vr != VerificationResult.VR_OK) {
  995. throw new ClassConstraintException("Exceptions attribute '" + tostring(obj) + "' references '" + cname
  996. + "' as an Exception but it does not pass verification pass 1: " + vr);
  997. } else {
  998. // We cannot safely trust any other "instanceof" mechanism. We need to transitively verify
  999. // the ancestor hierarchy.
  1000. JavaClass e = Repository.lookupClass(cname);
  1001. JavaClass t = Repository.lookupClass(Type.THROWABLE.getClassName());
  1002. JavaClass o = Repository.lookupClass(Type.OBJECT.getClassName());
  1003. while (e != o) {
  1004. if (e == t)
  1005. break; // It's a subclass of Throwable, OKAY, leave.
  1006. v = VerifierFactory.getVerifier(e.getSuperclassName());
  1007. vr = v.doPass1();
  1008. if (vr != VerificationResult.VR_OK) {
  1009. throw new ClassConstraintException("Exceptions attribute '" + tostring(obj) + "' references '" + cname
  1010. + "' as an Exception but '" + e.getSuperclassName()
  1011. + "' in the ancestor hierachy does not pass verification pass 1: " + vr);
  1012. } else {
  1013. e = Repository.lookupClass(e.getSuperclassName());
  1014. }
  1015. }
  1016. if (e != t)
  1017. throw new ClassConstraintException("Exceptions attribute '" + tostring(obj) + "' references '" + cname
  1018. + "' as an Exception but it is not a subclass of '" + t.getClassName() + "'.");
  1019. }
  1020. }
  1021. }
  1022. // SYNTHETIC: see above
  1023. // DEPRECATED: see above
  1024. // ////////////////////////////////////////////////////////////
  1025. // code_attribute-structure-ATTRIBUTES (vmspec2 4.7.3, 4.7) //
  1026. // ////////////////////////////////////////////////////////////
  1027. public void visitLineNumberTable(LineNumberTable obj) {// vmspec2 4.7.8
  1028. checkIndex(obj, obj.getNameIndex(), CONST_Utf8);
  1029. String name = ((ConstantUtf8) cp.getConstant(obj.getNameIndex())).getValue();
  1030. if (!name.equals("LineNumberTable")) {
  1031. throw new ClassConstraintException("The LineNumberTable attribute '" + tostring(obj)
  1032. + "' is not correctly named 'LineNumberTable' but '" + name + "'.");
  1033. }
  1034. // In JustIce,this check is delayed to Pass 3a.
  1035. // LineNumber[] linenumbers = obj.getLineNumberTable();
  1036. // ...validity check...
  1037. }
  1038. public void visitLocalVariableTable(LocalVariableTable obj) {// vmspec2 4.7.9
  1039. // In JustIce,this check is partially delayed to Pass 3a.
  1040. // The other part can be found in the visitCode(Code) method.
  1041. }
  1042. // //////////////////////////////////////////////////
  1043. // MISC-structure-ATTRIBUTES (vmspec2 4.7.1, 4.7) //
  1044. // //////////////////////////////////////////////////
  1045. public void visitUnknown(Unknown obj) {// vmspec2 4.7.1
  1046. // Represents an unknown attribute.
  1047. checkIndex(obj, obj.getNameIndex(), CONST_Utf8);
  1048. // Maybe only misnamed? Give a (warning) message.
  1049. addMessage("Unknown attribute '" + tostring(obj) + "'. This attribute is not known in any context!");
  1050. }
  1051. // ////////
  1052. // BCEL //
  1053. // ////////
  1054. public void visitLocalVariable(LocalVariable obj) {
  1055. // This does not represent an Attribute but is only
  1056. // related to internal BCEL data representation.
  1057. // see visitLocalVariableTable(LocalVariableTable)
  1058. }
  1059. public void visitCodeException(CodeException obj) {
  1060. // Code constraints are checked in Pass3 (3a and 3b).
  1061. // This does not represent an Attribute but is only
  1062. // related to internal BCEL data representation.
  1063. // see visitCode(Code)
  1064. }
  1065. public void visitConstantPool(ConstantPool obj) {
  1066. // No need to. We're piggybacked by the DescendingVisitor.
  1067. // This does not represent an Attribute but is only
  1068. // related to internal BCEL data representation.
  1069. }
  1070. public void visitInnerClass(InnerClass obj) {
  1071. // This does not represent an Attribute but is only
  1072. // related to internal BCEL data representation.
  1073. }
  1074. public void visitLineNumber(LineNumber obj) {
  1075. // This does not represent an Attribute but is only
  1076. // related to internal BCEL data representation.
  1077. // see visitLineNumberTable(LineNumberTable)
  1078. }
  1079. }
  1080. /**
  1081. * Ensures that the ConstantCP-subclassed entries of the constant pool are valid. According to
  1082. * "Yellin: Low Level Security in Java", this method does not verify the existence of referenced entities (such as classes) but
  1083. * only the formal correctness (such as well-formed signatures). The visitXXX() methods throw ClassConstraintException instances
  1084. * otherwise. <B>Precondition: index-style cross referencing in the constant pool must be valid. Simply invoke
  1085. * constant_pool_entries_satisfy_static_constraints() before.</B>
  1086. *
  1087. * @throws ClassConstraintException otherwise.
  1088. * @see #constant_pool_entries_satisfy_static_constraints()
  1089. */
  1090. private void field_and_method_refs_are_valid() {
  1091. JavaClass jc = Repository.lookupClass(myOwner.getClassName());
  1092. DescendingVisitor v = new DescendingVisitor(jc, new FAMRAV_Visitor(jc));
  1093. v.visit();
  1094. }
  1095. /**
  1096. * A Visitor class that ensures the ConstantCP-subclassed entries of the constant pool are valid. <B>Precondition: index-style
  1097. * cross referencing in the constant pool must be valid.</B>
  1098. *
  1099. * @see #constant_pool_entries_satisfy_static_constraints()
  1100. * @see org.aspectj.apache.bcel.classfile.ConstantCP
  1101. */
  1102. private class FAMRAV_Visitor extends EmptyClassVisitor {
  1103. private final ConstantPool cp; // ==jc.getConstantPool() -- only here to save typing work.
  1104. private FAMRAV_Visitor(JavaClass _jc) {
  1105. cp = _jc.getConstantPool();
  1106. }
  1107. public void visitConstantFieldref(ConstantFieldref obj) {
  1108. if (obj.getTag() != Constants.CONSTANT_Fieldref) {
  1109. throw new ClassConstraintException("ConstantFieldref '" + tostring(obj) + "' has wrong tag!");
  1110. }
  1111. int name_and_type_index = obj.getNameAndTypeIndex();
  1112. ConstantNameAndType cnat = (ConstantNameAndType) (cp.getConstant(name_and_type_index));
  1113. String name = ((ConstantUtf8) (cp.getConstant(cnat.getNameIndex()))).getValue(); // Field or Method name
  1114. if (!validFieldName(name)) {
  1115. throw new ClassConstraintException("Invalid field name '" + name + "' referenced by '" + tostring(obj) + "'.");
  1116. }
  1117. int class_index = obj.getClassIndex();
  1118. ConstantClass cc = (ConstantClass) (cp.getConstant(class_index));
  1119. String className = ((ConstantUtf8) (cp.getConstant(cc.getNameIndex()))).getValue(); // Class Name in internal form
  1120. if (!validClassName(className)) {
  1121. throw new ClassConstraintException("Illegal class name '" + className + "' used by '" + tostring(obj) + "'.");
  1122. }
  1123. String sig = ((ConstantUtf8) (cp.getConstant(cnat.getSignatureIndex()))).getValue(); // Field or Method
  1124. // signature(=descriptor)
  1125. try {
  1126. Type.getType(sig); /* Don't need the return value */
  1127. } catch (ClassFormatError cfe) {
  1128. // Well, BCEL sometimes is a little harsh describing exceptional situations.
  1129. throw new ClassConstraintException("Illegal descriptor (==signature) '" + sig + "' used by '" + tostring(obj)
  1130. + "'.");
  1131. }
  1132. }
  1133. public void visitConstantMethodref(ConstantMethodref obj) {
  1134. if (obj.getTag() != Constants.CONSTANT_Methodref) {
  1135. throw new ClassConstraintException("ConstantMethodref '" + tostring(obj) + "' has wrong tag!");
  1136. }
  1137. int name_and_type_index = obj.getNameAndTypeIndex();
  1138. ConstantNameAndType cnat = (ConstantNameAndType) (cp.getConstant(name_and_type_index));
  1139. String name = ((ConstantUtf8) (cp.getConstant(cnat.getNameIndex()))).getValue(); // Field or Method name
  1140. if (!validClassMethodName(name)) {
  1141. throw new ClassConstraintException("Invalid (non-interface) method name '" + name + "' referenced by '"
  1142. + tostring(obj) + "'.");
  1143. }
  1144. int class_index = obj.getClassIndex();
  1145. ConstantClass cc = (ConstantClass) (cp.getConstant(class_index));
  1146. String className = ((ConstantUtf8) (cp.getConstant(cc.getNameIndex()))).getValue(); // Class Name in internal form
  1147. if (!validClassName(className)) {
  1148. throw new ClassConstraintException("Illegal class name '" + className + "' used by '" + tostring(obj) + "'.");
  1149. }
  1150. String sig = ((ConstantUtf8) (cp.getConstant(cnat.getSignatureIndex()))).getValue(); // Field or Method
  1151. // signature(=descriptor)
  1152. try {
  1153. Type t = Type.getReturnType(sig);
  1154. if (name.equals(CONSTRUCTOR_NAME) && (t != Type.VOID)) {
  1155. throw new ClassConstraintException("Instance initialization method must have VOID return type.");
  1156. }
  1157. } catch (ClassFormatError cfe) {
  1158. // Well, BCEL sometimes is a little harsh describing exceptional situations.
  1159. throw new ClassConstraintException("Illegal descriptor (==signature) '" + sig + "' used by '" + tostring(obj)
  1160. + "'.");
  1161. }
  1162. }
  1163. public void visitConstantInterfaceMethodref(ConstantInterfaceMethodref obj) {
  1164. if (obj.getTag() != Constants.CONSTANT_InterfaceMethodref) {
  1165. throw new ClassConstraintException("ConstantInterfaceMethodref '" + tostring(obj) + "' has wrong tag!");
  1166. }
  1167. int name_and_type_index = obj.getNameAndTypeIndex();
  1168. ConstantNameAndType cnat = (ConstantNameAndType) (cp.getConstant(name_and_type_index));
  1169. String name = ((ConstantUtf8) (cp.getConstant(cnat.getNameIndex()))).getValue(); // Field or Method name
  1170. if (!validInterfaceMethodName(name)) {
  1171. throw new ClassConstraintException("Invalid (interface) method name '" + name + "' referenced by '" + tostring(obj)
  1172. + "'.");
  1173. }
  1174. int class_index = obj.getClassIndex();
  1175. ConstantClass cc = (ConstantClass) (cp.getConstant(class_index));
  1176. String className = ((ConstantUtf8) (cp.getConstant(cc.getNameIndex()))).getValue(); // Class Name in internal form
  1177. if (!validClassName(className)) {
  1178. throw new ClassConstraintException("Illegal class name '" + className + "' used by '" + tostring(obj) + "'.");
  1179. }
  1180. String sig = ((ConstantUtf8) (cp.getConstant(cnat.getSignatureIndex()))).getValue(); // Field or Method
  1181. // signature(=descriptor)
  1182. try {
  1183. Type t = Type.getReturnType(sig);
  1184. if (name.equals(STATIC_INITIALIZER_NAME) && (t != Type.VOID)) {
  1185. addMessage("Class or interface initialization method '" + STATIC_INITIALIZER_NAME
  1186. + "' usually has VOID return type instead of '" + t
  1187. + "'. Note this is really not a requirement of The Java Virtual Machine Specification, Second Edition.");
  1188. }
  1189. } catch (ClassFormatError cfe) {
  1190. // Well, BCEL sometimes is a little harsh describing exceptional situations.
  1191. throw new ClassConstraintException("Illegal descriptor (==signature) '" + sig + "' used by '" + tostring(obj)
  1192. + "'.");
  1193. }
  1194. }
  1195. }
  1196. /**
  1197. * This method returns true if and only if the supplied String represents a valid Java class name.
  1198. */
  1199. private static final boolean validClassName(String name) {
  1200. /*
  1201. * TODO: implement. Are there any restrictions?
  1202. */
  1203. return true;
  1204. }
  1205. /**
  1206. * This method returns true if and only if the supplied String represents a valid method name. This is basically the same as a
  1207. * valid identifier name in the Java programming language, but the special name for the instance initialization method is
  1208. * allowed and the special name for the class/interface initialization method may be allowed.
  1209. */
  1210. private static boolean validMethodName(String name, boolean allowStaticInit) {
  1211. if (validJavaLangMethodName(name))
  1212. return true;
  1213. if (allowStaticInit) {
  1214. return (name.equals(CONSTRUCTOR_NAME) || name.equals(STATIC_INITIALIZER_NAME));
  1215. } else {
  1216. return name.equals(CONSTRUCTOR_NAME);
  1217. }
  1218. }
  1219. /**
  1220. * This method returns true if and only if the supplied String represents a valid method name that may be referenced by
  1221. * ConstantMethodref objects.
  1222. */
  1223. private static boolean validClassMethodName(String name) {
  1224. return validMethodName(name, false);
  1225. }
  1226. /**
  1227. * This method returns true if and only if the supplied String represents a valid Java programming language method name stored
  1228. * as a simple (non-qualified) name. Conforming to: The Java Virtual Machine Specification, Second Edition, �2.7, �2.7.1, �2.2.
  1229. */
  1230. private static boolean validJavaLangMethodName(String name) {
  1231. if (!Character.isJavaIdentifierStart(name.charAt(0)))
  1232. return false;
  1233. for (int i = 1; i < name.length(); i++) {
  1234. if (!Character.isJavaIdentifierPart(name.charAt(i)))
  1235. return false;
  1236. }
  1237. return true;
  1238. }
  1239. /**
  1240. * This method returns true if and only if the supplied String represents a valid Java interface method name that may be
  1241. * referenced by ConstantInterfaceMethodref objects.
  1242. */
  1243. private static boolean validInterfaceMethodName(String name) {
  1244. // I guess we should assume special names forbidden here.
  1245. if (name.startsWith("<"))
  1246. return false;
  1247. return validJavaLangMethodName(name);
  1248. }
  1249. /**
  1250. * This method returns true if and only if the supplied String represents a valid Java identifier (so-called simple name).
  1251. */
  1252. private static boolean validJavaIdentifier(String name) {
  1253. // vmspec2 2.7, vmspec2 2.2
  1254. if (!Character.isJavaIdentifierStart(name.charAt(0)))
  1255. return false;
  1256. for (int i = 1; i < name.length(); i++) {
  1257. if (!Character.isJavaIdentifierPart(name.charAt(i)))
  1258. return false;
  1259. }
  1260. return true;
  1261. }
  1262. /**
  1263. * This method returns true if and only if the supplied String represents a valid Java field name.
  1264. */
  1265. private static boolean validFieldName(String name) {
  1266. // vmspec2 2.7, vmspec2 2.2
  1267. return validJavaIdentifier(name);
  1268. }
  1269. /**
  1270. * This class serves for finding out if a given JavaClass' ConstantPool references an Inner Class. The Java Virtual Machine
  1271. * Specification, Second Edition is not very precise about when an "InnerClasses" attribute has to appear. However, it states
  1272. * that there has to be exactly one InnerClasses attribute in the ClassFile structure if the constant pool of a class or
  1273. * interface refers to any class or interface "that is not a member of a package". Sun does not mean "member of the default
  1274. * package". In "Inner Classes Specification" they point out how a "bytecode name" is derived so one has to deduce what a class
  1275. * name of a class "that is not a member of a package" looks like: there is at least one character in the byte- code name that
  1276. * cannot be part of a legal Java Language Class name (and not equal to '/'). This assumption is wrong as the delimiter is '$'
  1277. * for which Character.isJavaIdentifierPart() == true. Hence, you really run into trouble if you have a toplevel class called
  1278. * "A$XXX" and another toplevel class called "A" with in inner class called "XXX". JustIce cannot repair this; please note that
  1279. * existing verifiers at this time even fail to detect missing InnerClasses attributes in pass 2.
  1280. */
  1281. private class InnerClassDetector extends EmptyClassVisitor {
  1282. private boolean hasInnerClass = false;
  1283. private JavaClass jc;
  1284. private ConstantPool cp;
  1285. private InnerClassDetector() {
  1286. } // Don't use.
  1287. /** Constructs an InnerClassDetector working on the JavaClass _jc. */
  1288. public InnerClassDetector(JavaClass _jc) {
  1289. jc = _jc;
  1290. cp = jc.getConstantPool();
  1291. (new DescendingVisitor(jc, this)).visit();
  1292. }
  1293. /**
  1294. * Returns if the JavaClass this InnerClassDetector is working on has an Inner Class reference in its constant pool.
  1295. */
  1296. public boolean innerClassReferenced() {
  1297. return hasInnerClass;
  1298. }
  1299. /** This method casually visits ConstantClass references. */
  1300. public void visitConstantClass(ConstantClass obj) {
  1301. Constant c = cp.getConstant(obj.getNameIndex());
  1302. if (c instanceof ConstantUtf8) { // Ignore the case where it's not a ConstantUtf8 here, we'll find out later.
  1303. String classname = ((ConstantUtf8) c).getValue();
  1304. if (classname.startsWith(jc.getClassName().replace('.', '/') + "$")) {
  1305. hasInnerClass = true;
  1306. }
  1307. }
  1308. }
  1309. }
  1310. /**
  1311. * This method is here to save typing work and improve code readability.
  1312. */
  1313. private static String tostring(Node n) {
  1314. return new StringRepresentation(n).toString();
  1315. }
  1316. }