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.

CtClassType.java 53KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722
  1. /*
  2. * Javassist, a Java-bytecode translator toolkit.
  3. * Copyright (C) 1999- Shigeru Chiba. All Rights Reserved.
  4. *
  5. * The contents of this file are subject to the Mozilla Public License Version
  6. * 1.1 (the "License"); you may not use this file except in compliance with
  7. * the License. Alternatively, the contents of this file may be used under
  8. * the terms of the GNU Lesser General Public License Version 2.1 or later,
  9. * or the Apache License Version 2.0.
  10. *
  11. * Software distributed under the License is distributed on an "AS IS" basis,
  12. * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
  13. * for the specific language governing rights and limitations under the
  14. * License.
  15. */
  16. package javassist;
  17. import java.lang.ref.WeakReference;
  18. import java.io.BufferedInputStream;
  19. import java.io.ByteArrayOutputStream;
  20. import java.io.ByteArrayInputStream;
  21. import java.io.DataInputStream;
  22. import java.io.DataOutputStream;
  23. import java.io.IOException;
  24. import java.io.InputStream;
  25. import java.net.URL;
  26. import java.util.ArrayList;
  27. import java.util.HashMap;
  28. import java.util.Hashtable;
  29. import java.util.List;
  30. import java.util.Set;
  31. import javassist.bytecode.AccessFlag;
  32. import javassist.bytecode.AttributeInfo;
  33. import javassist.bytecode.AnnotationsAttribute;
  34. import javassist.bytecode.BadBytecode;
  35. import javassist.bytecode.Bytecode;
  36. import javassist.bytecode.ClassFile;
  37. import javassist.bytecode.CodeAttribute;
  38. import javassist.bytecode.ConstantAttribute;
  39. import javassist.bytecode.CodeIterator;
  40. import javassist.bytecode.ConstPool;
  41. import javassist.bytecode.Descriptor;
  42. import javassist.bytecode.EnclosingMethodAttribute;
  43. import javassist.bytecode.FieldInfo;
  44. import javassist.bytecode.InnerClassesAttribute;
  45. import javassist.bytecode.MethodInfo;
  46. import javassist.bytecode.ParameterAnnotationsAttribute;
  47. import javassist.bytecode.SignatureAttribute;
  48. import javassist.bytecode.annotation.Annotation;
  49. import javassist.compiler.AccessorMaker;
  50. import javassist.compiler.CompileError;
  51. import javassist.compiler.Javac;
  52. import javassist.expr.ExprEditor;
  53. /**
  54. * Class types.
  55. */
  56. class CtClassType extends CtClass {
  57. ClassPool classPool;
  58. boolean wasChanged;
  59. private boolean wasFrozen;
  60. boolean wasPruned;
  61. boolean gcConstPool; // if true, the constant pool entries will be garbage collected.
  62. ClassFile classfile;
  63. byte[] rawClassfile; // backup storage
  64. private WeakReference memberCache;
  65. private AccessorMaker accessors;
  66. private FieldInitLink fieldInitializers;
  67. private Hashtable hiddenMethods; // must be synchronous
  68. private int uniqueNumberSeed;
  69. private boolean doPruning = ClassPool.doPruning;
  70. private int getCount;
  71. private static final int GET_THRESHOLD = 2; // see compress()
  72. CtClassType(String name, ClassPool cp) {
  73. super(name);
  74. classPool = cp;
  75. wasChanged = wasFrozen = wasPruned = gcConstPool = false;
  76. classfile = null;
  77. rawClassfile = null;
  78. memberCache = null;
  79. accessors = null;
  80. fieldInitializers = null;
  81. hiddenMethods = null;
  82. uniqueNumberSeed = 0;
  83. getCount = 0;
  84. }
  85. CtClassType(InputStream ins, ClassPool cp) throws IOException {
  86. this((String)null, cp);
  87. classfile = new ClassFile(new DataInputStream(ins));
  88. qualifiedName = classfile.getName();
  89. }
  90. protected void extendToString(StringBuffer buffer) {
  91. if (wasChanged)
  92. buffer.append("changed ");
  93. if (wasFrozen)
  94. buffer.append("frozen ");
  95. if (wasPruned)
  96. buffer.append("pruned ");
  97. buffer.append(Modifier.toString(getModifiers()));
  98. buffer.append(" class ");
  99. buffer.append(getName());
  100. try {
  101. CtClass ext = getSuperclass();
  102. if (ext != null) {
  103. String name = ext.getName();
  104. if (!name.equals("java.lang.Object"))
  105. buffer.append(" extends " + ext.getName());
  106. }
  107. }
  108. catch (NotFoundException e) {
  109. buffer.append(" extends ??");
  110. }
  111. try {
  112. CtClass[] intf = getInterfaces();
  113. if (intf.length > 0)
  114. buffer.append(" implements ");
  115. for (int i = 0; i < intf.length; ++i) {
  116. buffer.append(intf[i].getName());
  117. buffer.append(", ");
  118. }
  119. }
  120. catch (NotFoundException e) {
  121. buffer.append(" extends ??");
  122. }
  123. CtMember.Cache memCache = getMembers();
  124. exToString(buffer, " fields=",
  125. memCache.fieldHead(), memCache.lastField());
  126. exToString(buffer, " constructors=",
  127. memCache.consHead(), memCache.lastCons());
  128. exToString(buffer, " methods=",
  129. memCache.methodHead(), memCache.lastMethod());
  130. }
  131. private void exToString(StringBuffer buffer, String msg,
  132. CtMember head, CtMember tail) {
  133. buffer.append(msg);
  134. while (head != tail) {
  135. head = head.next();
  136. buffer.append(head);
  137. buffer.append(", ");
  138. }
  139. }
  140. public AccessorMaker getAccessorMaker() {
  141. if (accessors == null)
  142. accessors = new AccessorMaker(this);
  143. return accessors;
  144. }
  145. public ClassFile getClassFile2() {
  146. ClassFile cfile = classfile;
  147. if (cfile != null)
  148. return cfile;
  149. classPool.compress();
  150. if (rawClassfile != null) {
  151. try {
  152. classfile = new ClassFile(new DataInputStream(
  153. new ByteArrayInputStream(rawClassfile)));
  154. rawClassfile = null;
  155. getCount = GET_THRESHOLD;
  156. return classfile;
  157. }
  158. catch (IOException e) {
  159. throw new RuntimeException(e.toString(), e);
  160. }
  161. }
  162. InputStream fin = null;
  163. try {
  164. fin = classPool.openClassfile(getName());
  165. if (fin == null)
  166. throw new NotFoundException(getName());
  167. fin = new BufferedInputStream(fin);
  168. ClassFile cf = new ClassFile(new DataInputStream(fin));
  169. if (!cf.getName().equals(qualifiedName))
  170. throw new RuntimeException("cannot find " + qualifiedName + ": "
  171. + cf.getName() + " found in "
  172. + qualifiedName.replace('.', '/') + ".class");
  173. classfile = cf;
  174. return cf;
  175. }
  176. catch (NotFoundException e) {
  177. throw new RuntimeException(e.toString(), e);
  178. }
  179. catch (IOException e) {
  180. throw new RuntimeException(e.toString(), e);
  181. }
  182. finally {
  183. if (fin != null)
  184. try {
  185. fin.close();
  186. }
  187. catch (IOException e) {}
  188. }
  189. }
  190. /* Inherited from CtClass. Called by get() in ClassPool.
  191. *
  192. * @see javassist.CtClass#incGetCounter()
  193. * @see #toBytecode(DataOutputStream)
  194. */
  195. final void incGetCounter() { ++getCount; }
  196. /**
  197. * Invoked from ClassPool#compress().
  198. * It releases the class files that have not been recently used
  199. * if they are unmodified.
  200. */
  201. void compress() {
  202. if (getCount < GET_THRESHOLD)
  203. if (!isModified() && ClassPool.releaseUnmodifiedClassFile)
  204. removeClassFile();
  205. else if (isFrozen() && !wasPruned)
  206. saveClassFile();
  207. getCount = 0;
  208. }
  209. /**
  210. * Converts a ClassFile object into a byte array
  211. * for saving memory space.
  212. */
  213. private synchronized void saveClassFile() {
  214. /* getMembers() and releaseClassFile() are also synchronized.
  215. */
  216. if (classfile == null || hasMemberCache() != null)
  217. return;
  218. ByteArrayOutputStream barray = new ByteArrayOutputStream();
  219. DataOutputStream out = new DataOutputStream(barray);
  220. try {
  221. classfile.write(out);
  222. barray.close();
  223. rawClassfile = barray.toByteArray();
  224. classfile = null;
  225. }
  226. catch (IOException e) {}
  227. }
  228. private synchronized void removeClassFile() {
  229. if (classfile != null && !isModified() && hasMemberCache() == null)
  230. classfile = null;
  231. }
  232. public ClassPool getClassPool() { return classPool; }
  233. void setClassPool(ClassPool cp) { classPool = cp; }
  234. public URL getURL() throws NotFoundException {
  235. URL url = classPool.find(getName());
  236. if (url == null)
  237. throw new NotFoundException(getName());
  238. else
  239. return url;
  240. }
  241. public boolean isModified() { return wasChanged; }
  242. public boolean isFrozen() { return wasFrozen; }
  243. public void freeze() { wasFrozen = true; }
  244. void checkModify() throws RuntimeException {
  245. if (isFrozen()) {
  246. String msg = getName() + " class is frozen";
  247. if (wasPruned)
  248. msg += " and pruned";
  249. throw new RuntimeException(msg);
  250. }
  251. wasChanged = true;
  252. }
  253. public void defrost() {
  254. checkPruned("defrost");
  255. wasFrozen = false;
  256. }
  257. public boolean subtypeOf(CtClass clazz) throws NotFoundException {
  258. int i;
  259. String cname = clazz.getName();
  260. if (this == clazz || getName().equals(cname))
  261. return true;
  262. ClassFile file = getClassFile2();
  263. String supername = file.getSuperclass();
  264. if (supername != null && supername.equals(cname))
  265. return true;
  266. String[] ifs = file.getInterfaces();
  267. int num = ifs.length;
  268. for (i = 0; i < num; ++i)
  269. if (ifs[i].equals(cname))
  270. return true;
  271. if (supername != null && classPool.get(supername).subtypeOf(clazz))
  272. return true;
  273. for (i = 0; i < num; ++i)
  274. if (classPool.get(ifs[i]).subtypeOf(clazz))
  275. return true;
  276. return false;
  277. }
  278. public void setName(String name) throws RuntimeException {
  279. String oldname = getName();
  280. if (name.equals(oldname))
  281. return;
  282. // check this in advance although classNameChanged() below does.
  283. classPool.checkNotFrozen(name);
  284. ClassFile cf = getClassFile2();
  285. super.setName(name);
  286. cf.setName(name);
  287. nameReplaced();
  288. classPool.classNameChanged(oldname, this);
  289. }
  290. public String getGenericSignature() {
  291. SignatureAttribute sa
  292. = (SignatureAttribute)getClassFile2().getAttribute(SignatureAttribute.tag);
  293. return sa == null ? null : sa.getSignature();
  294. }
  295. public void setGenericSignature(String sig) {
  296. ClassFile cf = getClassFile();
  297. SignatureAttribute sa = new SignatureAttribute(cf.getConstPool(), sig);
  298. cf.addAttribute(sa);
  299. }
  300. public void replaceClassName(ClassMap classnames)
  301. throws RuntimeException
  302. {
  303. String oldClassName = getName();
  304. String newClassName
  305. = (String)classnames.get(Descriptor.toJvmName(oldClassName));
  306. if (newClassName != null) {
  307. newClassName = Descriptor.toJavaName(newClassName);
  308. // check this in advance although classNameChanged() below does.
  309. classPool.checkNotFrozen(newClassName);
  310. }
  311. super.replaceClassName(classnames);
  312. ClassFile cf = getClassFile2();
  313. cf.renameClass(classnames);
  314. nameReplaced();
  315. if (newClassName != null) {
  316. super.setName(newClassName);
  317. classPool.classNameChanged(oldClassName, this);
  318. }
  319. }
  320. public void replaceClassName(String oldname, String newname)
  321. throws RuntimeException
  322. {
  323. String thisname = getName();
  324. if (thisname.equals(oldname))
  325. setName(newname);
  326. else {
  327. super.replaceClassName(oldname, newname);
  328. getClassFile2().renameClass(oldname, newname);
  329. nameReplaced();
  330. }
  331. }
  332. public boolean isInterface() {
  333. return Modifier.isInterface(getModifiers());
  334. }
  335. public boolean isAnnotation() {
  336. return Modifier.isAnnotation(getModifiers());
  337. }
  338. public boolean isEnum() {
  339. return Modifier.isEnum(getModifiers());
  340. }
  341. public int getModifiers() {
  342. ClassFile cf = getClassFile2();
  343. int acc = cf.getAccessFlags();
  344. acc = AccessFlag.clear(acc, AccessFlag.SUPER);
  345. int inner = cf.getInnerAccessFlags();
  346. if (inner != -1 && (inner & AccessFlag.STATIC) != 0)
  347. acc |= AccessFlag.STATIC;
  348. return AccessFlag.toModifier(acc);
  349. }
  350. public CtClass[] getNestedClasses() throws NotFoundException {
  351. ClassFile cf = getClassFile2();
  352. InnerClassesAttribute ica
  353. = (InnerClassesAttribute)cf.getAttribute(InnerClassesAttribute.tag);
  354. if (ica == null)
  355. return new CtClass[0];
  356. String thisName = cf.getName() + "$";
  357. int n = ica.tableLength();
  358. ArrayList list = new ArrayList(n);
  359. for (int i = 0; i < n; i++) {
  360. String name = ica.innerClass(i);
  361. if (name != null)
  362. if (name.startsWith(thisName)) {
  363. // if it is an immediate nested class
  364. if (name.lastIndexOf('$') < thisName.length())
  365. list.add(classPool.get(name));
  366. }
  367. }
  368. return (CtClass[])list.toArray(new CtClass[list.size()]);
  369. }
  370. public void setModifiers(int mod) {
  371. ClassFile cf = getClassFile2();
  372. if (Modifier.isStatic(mod)) {
  373. int flags = cf.getInnerAccessFlags();
  374. if (flags != -1 && (flags & AccessFlag.STATIC) != 0)
  375. mod = mod & ~Modifier.STATIC;
  376. else
  377. throw new RuntimeException("cannot change " + getName() + " into a static class");
  378. }
  379. checkModify();
  380. cf.setAccessFlags(AccessFlag.of(mod));
  381. }
  382. public boolean hasAnnotation(Class clz) {
  383. ClassFile cf = getClassFile2();
  384. AnnotationsAttribute ainfo = (AnnotationsAttribute)
  385. cf.getAttribute(AnnotationsAttribute.invisibleTag);
  386. AnnotationsAttribute ainfo2 = (AnnotationsAttribute)
  387. cf.getAttribute(AnnotationsAttribute.visibleTag);
  388. return hasAnnotationType(clz, getClassPool(), ainfo, ainfo2);
  389. }
  390. static boolean hasAnnotationType(Class clz, ClassPool cp,
  391. AnnotationsAttribute a1, AnnotationsAttribute a2)
  392. {
  393. Annotation[] anno1, anno2;
  394. if (a1 == null)
  395. anno1 = null;
  396. else
  397. anno1 = a1.getAnnotations();
  398. if (a2 == null)
  399. anno2 = null;
  400. else
  401. anno2 = a2.getAnnotations();
  402. String typeName = clz.getName();
  403. if (anno1 != null)
  404. for (int i = 0; i < anno1.length; i++)
  405. if (anno1[i].getTypeName().equals(typeName))
  406. return true;
  407. if (anno2 != null)
  408. for (int i = 0; i < anno2.length; i++)
  409. if (anno2[i].getTypeName().equals(typeName))
  410. return true;
  411. return false;
  412. }
  413. public Object getAnnotation(Class clz) throws ClassNotFoundException {
  414. ClassFile cf = getClassFile2();
  415. AnnotationsAttribute ainfo = (AnnotationsAttribute)
  416. cf.getAttribute(AnnotationsAttribute.invisibleTag);
  417. AnnotationsAttribute ainfo2 = (AnnotationsAttribute)
  418. cf.getAttribute(AnnotationsAttribute.visibleTag);
  419. return getAnnotationType(clz, getClassPool(), ainfo, ainfo2);
  420. }
  421. static Object getAnnotationType(Class clz, ClassPool cp,
  422. AnnotationsAttribute a1, AnnotationsAttribute a2)
  423. throws ClassNotFoundException
  424. {
  425. Annotation[] anno1, anno2;
  426. if (a1 == null)
  427. anno1 = null;
  428. else
  429. anno1 = a1.getAnnotations();
  430. if (a2 == null)
  431. anno2 = null;
  432. else
  433. anno2 = a2.getAnnotations();
  434. String typeName = clz.getName();
  435. if (anno1 != null)
  436. for (int i = 0; i < anno1.length; i++)
  437. if (anno1[i].getTypeName().equals(typeName))
  438. return toAnnoType(anno1[i], cp);
  439. if (anno2 != null)
  440. for (int i = 0; i < anno2.length; i++)
  441. if (anno2[i].getTypeName().equals(typeName))
  442. return toAnnoType(anno2[i], cp);
  443. return null;
  444. }
  445. public Object[] getAnnotations() throws ClassNotFoundException {
  446. return getAnnotations(false);
  447. }
  448. public Object[] getAvailableAnnotations(){
  449. try {
  450. return getAnnotations(true);
  451. }
  452. catch (ClassNotFoundException e) {
  453. throw new RuntimeException("Unexpected exception ", e);
  454. }
  455. }
  456. private Object[] getAnnotations(boolean ignoreNotFound)
  457. throws ClassNotFoundException
  458. {
  459. ClassFile cf = getClassFile2();
  460. AnnotationsAttribute ainfo = (AnnotationsAttribute)
  461. cf.getAttribute(AnnotationsAttribute.invisibleTag);
  462. AnnotationsAttribute ainfo2 = (AnnotationsAttribute)
  463. cf.getAttribute(AnnotationsAttribute.visibleTag);
  464. return toAnnotationType(ignoreNotFound, getClassPool(), ainfo, ainfo2);
  465. }
  466. static Object[] toAnnotationType(boolean ignoreNotFound, ClassPool cp,
  467. AnnotationsAttribute a1, AnnotationsAttribute a2)
  468. throws ClassNotFoundException
  469. {
  470. Annotation[] anno1, anno2;
  471. int size1, size2;
  472. if (a1 == null) {
  473. anno1 = null;
  474. size1 = 0;
  475. }
  476. else {
  477. anno1 = a1.getAnnotations();
  478. size1 = anno1.length;
  479. }
  480. if (a2 == null) {
  481. anno2 = null;
  482. size2 = 0;
  483. }
  484. else {
  485. anno2 = a2.getAnnotations();
  486. size2 = anno2.length;
  487. }
  488. if (!ignoreNotFound){
  489. Object[] result = new Object[size1 + size2];
  490. for (int i = 0; i < size1; i++)
  491. result[i] = toAnnoType(anno1[i], cp);
  492. for (int j = 0; j < size2; j++)
  493. result[j + size1] = toAnnoType(anno2[j], cp);
  494. return result;
  495. }
  496. else{
  497. ArrayList annotations = new ArrayList();
  498. for (int i = 0 ; i < size1 ; i++){
  499. try{
  500. annotations.add(toAnnoType(anno1[i], cp));
  501. }
  502. catch(ClassNotFoundException e){}
  503. }
  504. for (int j = 0; j < size2; j++) {
  505. try{
  506. annotations.add(toAnnoType(anno2[j], cp));
  507. }
  508. catch(ClassNotFoundException e){}
  509. }
  510. return annotations.toArray();
  511. }
  512. }
  513. static Object[][] toAnnotationType(boolean ignoreNotFound, ClassPool cp,
  514. ParameterAnnotationsAttribute a1,
  515. ParameterAnnotationsAttribute a2,
  516. MethodInfo minfo)
  517. throws ClassNotFoundException
  518. {
  519. int numParameters = 0;
  520. if (a1 != null)
  521. numParameters = a1.numParameters();
  522. else if (a2 != null)
  523. numParameters = a2.numParameters();
  524. else
  525. numParameters = Descriptor.numOfParameters(minfo.getDescriptor());
  526. Object[][] result = new Object[numParameters][];
  527. for (int i = 0; i < numParameters; i++) {
  528. Annotation[] anno1, anno2;
  529. int size1, size2;
  530. if (a1 == null) {
  531. anno1 = null;
  532. size1 = 0;
  533. }
  534. else {
  535. anno1 = a1.getAnnotations()[i];
  536. size1 = anno1.length;
  537. }
  538. if (a2 == null) {
  539. anno2 = null;
  540. size2 = 0;
  541. }
  542. else {
  543. anno2 = a2.getAnnotations()[i];
  544. size2 = anno2.length;
  545. }
  546. if (!ignoreNotFound){
  547. result[i] = new Object[size1 + size2];
  548. for (int j = 0; j < size1; ++j)
  549. result[i][j] = toAnnoType(anno1[j], cp);
  550. for (int j = 0; j < size2; ++j)
  551. result[i][j + size1] = toAnnoType(anno2[j], cp);
  552. }
  553. else{
  554. ArrayList annotations = new ArrayList();
  555. for (int j = 0 ; j < size1 ; j++){
  556. try{
  557. annotations.add(toAnnoType(anno1[j], cp));
  558. }
  559. catch(ClassNotFoundException e){}
  560. }
  561. for (int j = 0; j < size2; j++){
  562. try{
  563. annotations.add(toAnnoType(anno2[j], cp));
  564. }
  565. catch(ClassNotFoundException e){}
  566. }
  567. result[i] = annotations.toArray();
  568. }
  569. }
  570. return result;
  571. }
  572. private static Object toAnnoType(Annotation anno, ClassPool cp)
  573. throws ClassNotFoundException
  574. {
  575. try {
  576. ClassLoader cl = cp.getClassLoader();
  577. return anno.toAnnotationType(cl, cp);
  578. }
  579. catch (ClassNotFoundException e) {
  580. ClassLoader cl2 = cp.getClass().getClassLoader();
  581. return anno.toAnnotationType(cl2, cp);
  582. }
  583. }
  584. public boolean subclassOf(CtClass superclass) {
  585. if (superclass == null)
  586. return false;
  587. String superName = superclass.getName();
  588. CtClass curr = this;
  589. try {
  590. while (curr != null) {
  591. if (curr.getName().equals(superName))
  592. return true;
  593. curr = curr.getSuperclass();
  594. }
  595. }
  596. catch (Exception ignored) {}
  597. return false;
  598. }
  599. public CtClass getSuperclass() throws NotFoundException {
  600. String supername = getClassFile2().getSuperclass();
  601. if (supername == null)
  602. return null;
  603. else
  604. return classPool.get(supername);
  605. }
  606. public void setSuperclass(CtClass clazz) throws CannotCompileException {
  607. checkModify();
  608. if (isInterface())
  609. addInterface(clazz);
  610. else
  611. getClassFile2().setSuperclass(clazz.getName());
  612. }
  613. public CtClass[] getInterfaces() throws NotFoundException {
  614. String[] ifs = getClassFile2().getInterfaces();
  615. int num = ifs.length;
  616. CtClass[] ifc = new CtClass[num];
  617. for (int i = 0; i < num; ++i)
  618. ifc[i] = classPool.get(ifs[i]);
  619. return ifc;
  620. }
  621. public void setInterfaces(CtClass[] list) {
  622. checkModify();
  623. String[] ifs;
  624. if (list == null)
  625. ifs = new String[0];
  626. else {
  627. int num = list.length;
  628. ifs = new String[num];
  629. for (int i = 0; i < num; ++i)
  630. ifs[i] = list[i].getName();
  631. }
  632. getClassFile2().setInterfaces(ifs);
  633. }
  634. public void addInterface(CtClass anInterface) {
  635. checkModify();
  636. if (anInterface != null)
  637. getClassFile2().addInterface(anInterface.getName());
  638. }
  639. public CtClass getDeclaringClass() throws NotFoundException {
  640. ClassFile cf = getClassFile2();
  641. InnerClassesAttribute ica = (InnerClassesAttribute)cf.getAttribute(
  642. InnerClassesAttribute.tag);
  643. if (ica == null)
  644. return null;
  645. String name = getName();
  646. int n = ica.tableLength();
  647. for (int i = 0; i < n; ++i)
  648. if (name.equals(ica.innerClass(i))) {
  649. String outName = ica.outerClass(i);
  650. if (outName != null)
  651. return classPool.get(outName);
  652. else {
  653. // maybe anonymous or local class.
  654. EnclosingMethodAttribute ema
  655. = (EnclosingMethodAttribute)cf.getAttribute(
  656. EnclosingMethodAttribute.tag);
  657. if (ema != null)
  658. return classPool.get(ema.className());
  659. }
  660. }
  661. return null;
  662. }
  663. public CtMethod getEnclosingMethod() throws NotFoundException {
  664. ClassFile cf = getClassFile2();
  665. EnclosingMethodAttribute ema
  666. = (EnclosingMethodAttribute)cf.getAttribute(
  667. EnclosingMethodAttribute.tag);
  668. if (ema != null) {
  669. CtClass enc = classPool.get(ema.className());
  670. return enc.getMethod(ema.methodName(), ema.methodDescriptor());
  671. }
  672. return null;
  673. }
  674. public CtClass makeNestedClass(String name, boolean isStatic) {
  675. if (!isStatic)
  676. throw new RuntimeException(
  677. "sorry, only nested static class is supported");
  678. checkModify();
  679. CtClass c = classPool.makeNestedClass(getName() + "$" + name);
  680. ClassFile cf = getClassFile2();
  681. ClassFile cf2 = c.getClassFile2();
  682. InnerClassesAttribute ica = (InnerClassesAttribute)cf.getAttribute(
  683. InnerClassesAttribute.tag);
  684. if (ica == null) {
  685. ica = new InnerClassesAttribute(cf.getConstPool());
  686. cf.addAttribute(ica);
  687. }
  688. ica.append(c.getName(), this.getName(), name,
  689. (cf2.getAccessFlags() & ~AccessFlag.SUPER) | AccessFlag.STATIC);
  690. cf2.addAttribute(ica.copy(cf2.getConstPool(), null));
  691. return c;
  692. }
  693. /* flush cached names.
  694. */
  695. private void nameReplaced() {
  696. CtMember.Cache cache = hasMemberCache();
  697. if (cache != null) {
  698. CtMember mth = cache.methodHead();
  699. CtMember tail = cache.lastMethod();
  700. while (mth != tail) {
  701. mth = mth.next();
  702. mth.nameReplaced();
  703. }
  704. }
  705. }
  706. /**
  707. * Returns null if members are not cached.
  708. */
  709. protected CtMember.Cache hasMemberCache() {
  710. if (memberCache != null)
  711. return (CtMember.Cache)memberCache.get();
  712. else
  713. return null;
  714. }
  715. protected synchronized CtMember.Cache getMembers() {
  716. CtMember.Cache cache = null;
  717. if (memberCache == null
  718. || (cache = (CtMember.Cache)memberCache.get()) == null) {
  719. cache = new CtMember.Cache(this);
  720. makeFieldCache(cache);
  721. makeBehaviorCache(cache);
  722. memberCache = new WeakReference(cache);
  723. }
  724. return cache;
  725. }
  726. private void makeFieldCache(CtMember.Cache cache) {
  727. List list = getClassFile2().getFields();
  728. int n = list.size();
  729. for (int i = 0; i < n; ++i) {
  730. FieldInfo finfo = (FieldInfo)list.get(i);
  731. CtField newField = new CtField(finfo, this);
  732. cache.addField(newField);
  733. }
  734. }
  735. private void makeBehaviorCache(CtMember.Cache cache) {
  736. List list = getClassFile2().getMethods();
  737. int n = list.size();
  738. for (int i = 0; i < n; ++i) {
  739. MethodInfo minfo = (MethodInfo)list.get(i);
  740. if (minfo.isMethod()) {
  741. CtMethod newMethod = new CtMethod(minfo, this);
  742. cache.addMethod(newMethod);
  743. }
  744. else {
  745. CtConstructor newCons = new CtConstructor(minfo, this);
  746. cache.addConstructor(newCons);
  747. }
  748. }
  749. }
  750. public CtField[] getFields() {
  751. ArrayList alist = new ArrayList();
  752. getFields(alist, this);
  753. return (CtField[])alist.toArray(new CtField[alist.size()]);
  754. }
  755. private static void getFields(ArrayList alist, CtClass cc) {
  756. int i, num;
  757. if (cc == null)
  758. return;
  759. try {
  760. getFields(alist, cc.getSuperclass());
  761. }
  762. catch (NotFoundException e) {}
  763. try {
  764. CtClass[] ifs = cc.getInterfaces();
  765. num = ifs.length;
  766. for (i = 0; i < num; ++i)
  767. getFields(alist, ifs[i]);
  768. }
  769. catch (NotFoundException e) {}
  770. CtMember.Cache memCache = ((CtClassType)cc).getMembers();
  771. CtMember field = memCache.fieldHead();
  772. CtMember tail = memCache.lastField();
  773. while (field != tail) {
  774. field = field.next();
  775. if (!Modifier.isPrivate(field.getModifiers()))
  776. alist.add(field);
  777. }
  778. }
  779. public CtField getField(String name, String desc) throws NotFoundException {
  780. CtField f = getField2(name, desc);
  781. return checkGetField(f, name, desc);
  782. }
  783. private CtField checkGetField(CtField f, String name, String desc)
  784. throws NotFoundException
  785. {
  786. if (f == null) {
  787. String msg = "field: " + name;
  788. if (desc != null)
  789. msg += " type " + desc;
  790. throw new NotFoundException(msg + " in " + getName());
  791. }
  792. else
  793. return f;
  794. }
  795. CtField getField2(String name, String desc) {
  796. CtField df = getDeclaredField2(name, desc);
  797. if (df != null)
  798. return df;
  799. try {
  800. CtClass[] ifs = getInterfaces();
  801. int num = ifs.length;
  802. for (int i = 0; i < num; ++i) {
  803. CtField f = ifs[i].getField2(name, desc);
  804. if (f != null)
  805. return f;
  806. }
  807. CtClass s = getSuperclass();
  808. if (s != null)
  809. return s.getField2(name, desc);
  810. }
  811. catch (NotFoundException e) {}
  812. return null;
  813. }
  814. public CtField[] getDeclaredFields() {
  815. CtMember.Cache memCache = getMembers();
  816. CtMember field = memCache.fieldHead();
  817. CtMember tail = memCache.lastField();
  818. int num = CtMember.Cache.count(field, tail);
  819. CtField[] cfs = new CtField[num];
  820. int i = 0;
  821. while (field != tail) {
  822. field = field.next();
  823. cfs[i++] = (CtField)field;
  824. }
  825. return cfs;
  826. }
  827. public CtField getDeclaredField(String name) throws NotFoundException {
  828. return getDeclaredField(name, null);
  829. }
  830. public CtField getDeclaredField(String name, String desc) throws NotFoundException {
  831. CtField f = getDeclaredField2(name, desc);
  832. return checkGetField(f, name, desc);
  833. }
  834. private CtField getDeclaredField2(String name, String desc) {
  835. CtMember.Cache memCache = getMembers();
  836. CtMember field = memCache.fieldHead();
  837. CtMember tail = memCache.lastField();
  838. while (field != tail) {
  839. field = field.next();
  840. if (field.getName().equals(name)
  841. && (desc == null || desc.equals(field.getSignature())))
  842. return (CtField)field;
  843. }
  844. return null;
  845. }
  846. public CtBehavior[] getDeclaredBehaviors() {
  847. CtMember.Cache memCache = getMembers();
  848. CtMember cons = memCache.consHead();
  849. CtMember consTail = memCache.lastCons();
  850. int cnum = CtMember.Cache.count(cons, consTail);
  851. CtMember mth = memCache.methodHead();
  852. CtMember mthTail = memCache.lastMethod();
  853. int mnum = CtMember.Cache.count(mth, mthTail);
  854. CtBehavior[] cb = new CtBehavior[cnum + mnum];
  855. int i = 0;
  856. while (cons != consTail) {
  857. cons = cons.next();
  858. cb[i++] = (CtBehavior)cons;
  859. }
  860. while (mth != mthTail) {
  861. mth = mth.next();
  862. cb[i++] = (CtBehavior)mth;
  863. }
  864. return cb;
  865. }
  866. public CtConstructor[] getConstructors() {
  867. CtMember.Cache memCache = getMembers();
  868. CtMember cons = memCache.consHead();
  869. CtMember consTail = memCache.lastCons();
  870. int n = 0;
  871. CtMember mem = cons;
  872. while (mem != consTail) {
  873. mem = mem.next();
  874. if (isPubCons((CtConstructor)mem))
  875. n++;
  876. }
  877. CtConstructor[] result = new CtConstructor[n];
  878. int i = 0;
  879. mem = cons;
  880. while (mem != consTail) {
  881. mem = mem.next();
  882. CtConstructor cc = (CtConstructor)mem;
  883. if (isPubCons(cc))
  884. result[i++] = cc;
  885. }
  886. return result;
  887. }
  888. private static boolean isPubCons(CtConstructor cons) {
  889. return !Modifier.isPrivate(cons.getModifiers())
  890. && cons.isConstructor();
  891. }
  892. public CtConstructor getConstructor(String desc)
  893. throws NotFoundException
  894. {
  895. CtMember.Cache memCache = getMembers();
  896. CtMember cons = memCache.consHead();
  897. CtMember consTail = memCache.lastCons();
  898. while (cons != consTail) {
  899. cons = cons.next();
  900. CtConstructor cc = (CtConstructor)cons;
  901. if (cc.getMethodInfo2().getDescriptor().equals(desc)
  902. && cc.isConstructor())
  903. return cc;
  904. }
  905. return super.getConstructor(desc);
  906. }
  907. public CtConstructor[] getDeclaredConstructors() {
  908. CtMember.Cache memCache = getMembers();
  909. CtMember cons = memCache.consHead();
  910. CtMember consTail = memCache.lastCons();
  911. int n = 0;
  912. CtMember mem = cons;
  913. while (mem != consTail) {
  914. mem = mem.next();
  915. CtConstructor cc = (CtConstructor)mem;
  916. if (cc.isConstructor())
  917. n++;
  918. }
  919. CtConstructor[] result = new CtConstructor[n];
  920. int i = 0;
  921. mem = cons;
  922. while (mem != consTail) {
  923. mem = mem.next();
  924. CtConstructor cc = (CtConstructor)mem;
  925. if (cc.isConstructor())
  926. result[i++] = cc;
  927. }
  928. return result;
  929. }
  930. public CtConstructor getClassInitializer() {
  931. CtMember.Cache memCache = getMembers();
  932. CtMember cons = memCache.consHead();
  933. CtMember consTail = memCache.lastCons();
  934. while (cons != consTail) {
  935. cons = cons.next();
  936. CtConstructor cc = (CtConstructor)cons;
  937. if (cc.isClassInitializer())
  938. return cc;
  939. }
  940. return null;
  941. }
  942. public CtMethod[] getMethods() {
  943. HashMap h = new HashMap();
  944. getMethods0(h, this);
  945. return (CtMethod[])h.values().toArray(new CtMethod[h.size()]);
  946. }
  947. private static void getMethods0(HashMap h, CtClass cc) {
  948. try {
  949. CtClass[] ifs = cc.getInterfaces();
  950. int size = ifs.length;
  951. for (int i = 0; i < size; ++i)
  952. getMethods0(h, ifs[i]);
  953. }
  954. catch (NotFoundException e) {}
  955. try {
  956. CtClass s = cc.getSuperclass();
  957. if (s != null)
  958. getMethods0(h, s);
  959. }
  960. catch (NotFoundException e) {}
  961. if (cc instanceof CtClassType) {
  962. CtMember.Cache memCache = ((CtClassType)cc).getMembers();
  963. CtMember mth = memCache.methodHead();
  964. CtMember mthTail = memCache.lastMethod();
  965. while (mth != mthTail) {
  966. mth = mth.next();
  967. if (!Modifier.isPrivate(mth.getModifiers()))
  968. h.put(((CtMethod)mth).getStringRep(), mth);
  969. }
  970. }
  971. }
  972. public CtMethod getMethod(String name, String desc)
  973. throws NotFoundException
  974. {
  975. CtMethod m = getMethod0(this, name, desc);
  976. if (m != null)
  977. return m;
  978. else
  979. throw new NotFoundException(name + "(..) is not found in "
  980. + getName());
  981. }
  982. private static CtMethod getMethod0(CtClass cc,
  983. String name, String desc) {
  984. if (cc instanceof CtClassType) {
  985. CtMember.Cache memCache = ((CtClassType)cc).getMembers();
  986. CtMember mth = memCache.methodHead();
  987. CtMember mthTail = memCache.lastMethod();
  988. while (mth != mthTail) {
  989. mth = mth.next();
  990. if (mth.getName().equals(name)
  991. && ((CtMethod)mth).getMethodInfo2().getDescriptor().equals(desc))
  992. return (CtMethod)mth;
  993. }
  994. }
  995. try {
  996. CtClass s = cc.getSuperclass();
  997. if (s != null) {
  998. CtMethod m = getMethod0(s, name, desc);
  999. if (m != null)
  1000. return m;
  1001. }
  1002. }
  1003. catch (NotFoundException e) {}
  1004. try {
  1005. CtClass[] ifs = cc.getInterfaces();
  1006. int size = ifs.length;
  1007. for (int i = 0; i < size; ++i) {
  1008. CtMethod m = getMethod0(ifs[i], name, desc);
  1009. if (m != null)
  1010. return m;
  1011. }
  1012. }
  1013. catch (NotFoundException e) {}
  1014. return null;
  1015. }
  1016. public CtMethod[] getDeclaredMethods() {
  1017. CtMember.Cache memCache = getMembers();
  1018. CtMember mth = memCache.methodHead();
  1019. CtMember mthTail = memCache.lastMethod();
  1020. int num = CtMember.Cache.count(mth, mthTail);
  1021. CtMethod[] cms = new CtMethod[num];
  1022. int i = 0;
  1023. while (mth != mthTail) {
  1024. mth = mth.next();
  1025. cms[i++] = (CtMethod)mth;
  1026. }
  1027. return cms;
  1028. }
  1029. public CtMethod getDeclaredMethod(String name) throws NotFoundException {
  1030. CtMember.Cache memCache = getMembers();
  1031. CtMember mth = memCache.methodHead();
  1032. CtMember mthTail = memCache.lastMethod();
  1033. while (mth != mthTail) {
  1034. mth = mth.next();
  1035. if (mth.getName().equals(name))
  1036. return (CtMethod)mth;
  1037. }
  1038. throw new NotFoundException(name + "(..) is not found in "
  1039. + getName());
  1040. }
  1041. public CtMethod getDeclaredMethod(String name, CtClass[] params)
  1042. throws NotFoundException
  1043. {
  1044. String desc = Descriptor.ofParameters(params);
  1045. CtMember.Cache memCache = getMembers();
  1046. CtMember mth = memCache.methodHead();
  1047. CtMember mthTail = memCache.lastMethod();
  1048. while (mth != mthTail) {
  1049. mth = mth.next();
  1050. if (mth.getName().equals(name)
  1051. && ((CtMethod)mth).getMethodInfo2().getDescriptor().startsWith(desc))
  1052. return (CtMethod)mth;
  1053. }
  1054. throw new NotFoundException(name + "(..) is not found in "
  1055. + getName());
  1056. }
  1057. public void addField(CtField f, String init)
  1058. throws CannotCompileException
  1059. {
  1060. addField(f, CtField.Initializer.byExpr(init));
  1061. }
  1062. public void addField(CtField f, CtField.Initializer init)
  1063. throws CannotCompileException
  1064. {
  1065. checkModify();
  1066. if (f.getDeclaringClass() != this)
  1067. throw new CannotCompileException("cannot add");
  1068. if (init == null)
  1069. init = f.getInit();
  1070. if (init != null) {
  1071. init.check(f.getSignature());
  1072. int mod = f.getModifiers();
  1073. if (Modifier.isStatic(mod) && Modifier.isFinal(mod))
  1074. try {
  1075. ConstPool cp = getClassFile2().getConstPool();
  1076. int index = init.getConstantValue(cp, f.getType());
  1077. if (index != 0) {
  1078. f.getFieldInfo2().addAttribute(new ConstantAttribute(cp, index));
  1079. init = null;
  1080. }
  1081. }
  1082. catch (NotFoundException e) {}
  1083. }
  1084. getMembers().addField(f);
  1085. getClassFile2().addField(f.getFieldInfo2());
  1086. if (init != null) {
  1087. FieldInitLink fil = new FieldInitLink(f, init);
  1088. FieldInitLink link = fieldInitializers;
  1089. if (link == null)
  1090. fieldInitializers = fil;
  1091. else {
  1092. while (link.next != null)
  1093. link = link.next;
  1094. link.next = fil;
  1095. }
  1096. }
  1097. }
  1098. public void removeField(CtField f) throws NotFoundException {
  1099. checkModify();
  1100. FieldInfo fi = f.getFieldInfo2();
  1101. ClassFile cf = getClassFile2();
  1102. if (cf.getFields().remove(fi)) {
  1103. getMembers().remove(f);
  1104. gcConstPool = true;
  1105. }
  1106. else
  1107. throw new NotFoundException(f.toString());
  1108. }
  1109. public CtConstructor makeClassInitializer()
  1110. throws CannotCompileException
  1111. {
  1112. CtConstructor clinit = getClassInitializer();
  1113. if (clinit != null)
  1114. return clinit;
  1115. checkModify();
  1116. ClassFile cf = getClassFile2();
  1117. Bytecode code = new Bytecode(cf.getConstPool(), 0, 0);
  1118. modifyClassConstructor(cf, code, 0, 0);
  1119. return getClassInitializer();
  1120. }
  1121. public void addConstructor(CtConstructor c)
  1122. throws CannotCompileException
  1123. {
  1124. checkModify();
  1125. if (c.getDeclaringClass() != this)
  1126. throw new CannotCompileException("cannot add");
  1127. getMembers().addConstructor(c);
  1128. getClassFile2().addMethod(c.getMethodInfo2());
  1129. }
  1130. public void removeConstructor(CtConstructor m) throws NotFoundException {
  1131. checkModify();
  1132. MethodInfo mi = m.getMethodInfo2();
  1133. ClassFile cf = getClassFile2();
  1134. if (cf.getMethods().remove(mi)) {
  1135. getMembers().remove(m);
  1136. gcConstPool = true;
  1137. }
  1138. else
  1139. throw new NotFoundException(m.toString());
  1140. }
  1141. public void addMethod(CtMethod m) throws CannotCompileException {
  1142. checkModify();
  1143. if (m.getDeclaringClass() != this)
  1144. throw new CannotCompileException("bad declaring class");
  1145. int mod = m.getModifiers();
  1146. if ((getModifiers() & Modifier.INTERFACE) != 0) {
  1147. m.setModifiers(mod | Modifier.PUBLIC);
  1148. if ((mod & Modifier.ABSTRACT) == 0)
  1149. throw new CannotCompileException(
  1150. "an interface method must be abstract: " + m.toString());
  1151. }
  1152. getMembers().addMethod(m);
  1153. getClassFile2().addMethod(m.getMethodInfo2());
  1154. if ((mod & Modifier.ABSTRACT) != 0)
  1155. setModifiers(getModifiers() | Modifier.ABSTRACT);
  1156. }
  1157. public void removeMethod(CtMethod m) throws NotFoundException {
  1158. checkModify();
  1159. MethodInfo mi = m.getMethodInfo2();
  1160. ClassFile cf = getClassFile2();
  1161. if (cf.getMethods().remove(mi)) {
  1162. getMembers().remove(m);
  1163. gcConstPool = true;
  1164. }
  1165. else
  1166. throw new NotFoundException(m.toString());
  1167. }
  1168. public byte[] getAttribute(String name) {
  1169. AttributeInfo ai = getClassFile2().getAttribute(name);
  1170. if (ai == null)
  1171. return null;
  1172. else
  1173. return ai.get();
  1174. }
  1175. public void setAttribute(String name, byte[] data) {
  1176. checkModify();
  1177. ClassFile cf = getClassFile2();
  1178. cf.addAttribute(new AttributeInfo(cf.getConstPool(), name, data));
  1179. }
  1180. public void instrument(CodeConverter converter)
  1181. throws CannotCompileException
  1182. {
  1183. checkModify();
  1184. ClassFile cf = getClassFile2();
  1185. ConstPool cp = cf.getConstPool();
  1186. List list = cf.getMethods();
  1187. int n = list.size();
  1188. for (int i = 0; i < n; ++i) {
  1189. MethodInfo minfo = (MethodInfo)list.get(i);
  1190. converter.doit(this, minfo, cp);
  1191. }
  1192. }
  1193. public void instrument(ExprEditor editor)
  1194. throws CannotCompileException
  1195. {
  1196. checkModify();
  1197. ClassFile cf = getClassFile2();
  1198. List list = cf.getMethods();
  1199. int n = list.size();
  1200. for (int i = 0; i < n; ++i) {
  1201. MethodInfo minfo = (MethodInfo)list.get(i);
  1202. editor.doit(this, minfo);
  1203. }
  1204. }
  1205. /**
  1206. * @see javassist.CtClass#prune()
  1207. * @see javassist.CtClass#stopPruning(boolean)
  1208. */
  1209. public void prune() {
  1210. if (wasPruned)
  1211. return;
  1212. wasPruned = wasFrozen = true;
  1213. getClassFile2().prune();
  1214. }
  1215. public void rebuildClassFile() { gcConstPool = true; }
  1216. public void toBytecode(DataOutputStream out)
  1217. throws CannotCompileException, IOException
  1218. {
  1219. try {
  1220. if (isModified()) {
  1221. checkPruned("toBytecode");
  1222. ClassFile cf = getClassFile2();
  1223. if (gcConstPool) {
  1224. cf.compact();
  1225. gcConstPool = false;
  1226. }
  1227. modifyClassConstructor(cf);
  1228. modifyConstructors(cf);
  1229. if (debugDump != null)
  1230. dumpClassFile(cf);
  1231. cf.write(out);
  1232. out.flush();
  1233. fieldInitializers = null;
  1234. if (doPruning) {
  1235. // to save memory
  1236. cf.prune();
  1237. wasPruned = true;
  1238. }
  1239. }
  1240. else {
  1241. classPool.writeClassfile(getName(), out);
  1242. // to save memory
  1243. // classfile = null;
  1244. }
  1245. getCount = 0;
  1246. wasFrozen = true;
  1247. }
  1248. catch (NotFoundException e) {
  1249. throw new CannotCompileException(e);
  1250. }
  1251. catch (IOException e) {
  1252. throw new CannotCompileException(e);
  1253. }
  1254. }
  1255. private void dumpClassFile(ClassFile cf) throws IOException {
  1256. DataOutputStream dump = makeFileOutput(debugDump);
  1257. try {
  1258. cf.write(dump);
  1259. }
  1260. finally {
  1261. dump.close();
  1262. }
  1263. }
  1264. /* See also checkModified()
  1265. */
  1266. private void checkPruned(String method) {
  1267. if (wasPruned)
  1268. throw new RuntimeException(method + "(): " + getName()
  1269. + " was pruned.");
  1270. }
  1271. public boolean stopPruning(boolean stop) {
  1272. boolean prev = !doPruning;
  1273. doPruning = !stop;
  1274. return prev;
  1275. }
  1276. private void modifyClassConstructor(ClassFile cf)
  1277. throws CannotCompileException, NotFoundException
  1278. {
  1279. if (fieldInitializers == null)
  1280. return;
  1281. Bytecode code = new Bytecode(cf.getConstPool(), 0, 0);
  1282. Javac jv = new Javac(code, this);
  1283. int stacksize = 0;
  1284. boolean doInit = false;
  1285. for (FieldInitLink fi = fieldInitializers; fi != null; fi = fi.next) {
  1286. CtField f = fi.field;
  1287. if (Modifier.isStatic(f.getModifiers())) {
  1288. doInit = true;
  1289. int s = fi.init.compileIfStatic(f.getType(), f.getName(),
  1290. code, jv);
  1291. if (stacksize < s)
  1292. stacksize = s;
  1293. }
  1294. }
  1295. if (doInit) // need an initializer for static fileds.
  1296. modifyClassConstructor(cf, code, stacksize, 0);
  1297. }
  1298. private void modifyClassConstructor(ClassFile cf, Bytecode code,
  1299. int stacksize, int localsize)
  1300. throws CannotCompileException
  1301. {
  1302. MethodInfo m = cf.getStaticInitializer();
  1303. if (m == null) {
  1304. code.add(Bytecode.RETURN);
  1305. code.setMaxStack(stacksize);
  1306. code.setMaxLocals(localsize);
  1307. m = new MethodInfo(cf.getConstPool(), "<clinit>", "()V");
  1308. m.setAccessFlags(AccessFlag.STATIC);
  1309. m.setCodeAttribute(code.toCodeAttribute());
  1310. cf.addMethod(m);
  1311. CtMember.Cache cache = hasMemberCache();
  1312. if (cache != null)
  1313. cache.addConstructor(new CtConstructor(m, this));
  1314. }
  1315. else {
  1316. CodeAttribute codeAttr = m.getCodeAttribute();
  1317. if (codeAttr == null)
  1318. throw new CannotCompileException("empty <clinit>");
  1319. try {
  1320. CodeIterator it = codeAttr.iterator();
  1321. int pos = it.insertEx(code.get());
  1322. it.insert(code.getExceptionTable(), pos);
  1323. int maxstack = codeAttr.getMaxStack();
  1324. if (maxstack < stacksize)
  1325. codeAttr.setMaxStack(stacksize);
  1326. int maxlocals = codeAttr.getMaxLocals();
  1327. if (maxlocals < localsize)
  1328. codeAttr.setMaxLocals(localsize);
  1329. }
  1330. catch (BadBytecode e) {
  1331. throw new CannotCompileException(e);
  1332. }
  1333. }
  1334. try {
  1335. m.rebuildStackMapIf6(classPool, cf);
  1336. }
  1337. catch (BadBytecode e) {
  1338. throw new CannotCompileException(e);
  1339. }
  1340. }
  1341. private void modifyConstructors(ClassFile cf)
  1342. throws CannotCompileException, NotFoundException
  1343. {
  1344. if (fieldInitializers == null)
  1345. return;
  1346. ConstPool cp = cf.getConstPool();
  1347. List list = cf.getMethods();
  1348. int n = list.size();
  1349. for (int i = 0; i < n; ++i) {
  1350. MethodInfo minfo = (MethodInfo)list.get(i);
  1351. if (minfo.isConstructor()) {
  1352. CodeAttribute codeAttr = minfo.getCodeAttribute();
  1353. if (codeAttr != null)
  1354. try {
  1355. Bytecode init = new Bytecode(cp, 0,
  1356. codeAttr.getMaxLocals());
  1357. CtClass[] params
  1358. = Descriptor.getParameterTypes(
  1359. minfo.getDescriptor(),
  1360. classPool);
  1361. int stacksize = makeFieldInitializer(init, params);
  1362. insertAuxInitializer(codeAttr, init, stacksize);
  1363. minfo.rebuildStackMapIf6(classPool, cf);
  1364. }
  1365. catch (BadBytecode e) {
  1366. throw new CannotCompileException(e);
  1367. }
  1368. }
  1369. }
  1370. }
  1371. private static void insertAuxInitializer(CodeAttribute codeAttr,
  1372. Bytecode initializer,
  1373. int stacksize)
  1374. throws BadBytecode
  1375. {
  1376. CodeIterator it = codeAttr.iterator();
  1377. int index = it.skipSuperConstructor();
  1378. if (index < 0) {
  1379. index = it.skipThisConstructor();
  1380. if (index >= 0)
  1381. return; // this() is called.
  1382. // Neither this() or super() is called.
  1383. }
  1384. int pos = it.insertEx(initializer.get());
  1385. it.insert(initializer.getExceptionTable(), pos);
  1386. int maxstack = codeAttr.getMaxStack();
  1387. if (maxstack < stacksize)
  1388. codeAttr.setMaxStack(stacksize);
  1389. }
  1390. private int makeFieldInitializer(Bytecode code, CtClass[] parameters)
  1391. throws CannotCompileException, NotFoundException
  1392. {
  1393. int stacksize = 0;
  1394. Javac jv = new Javac(code, this);
  1395. try {
  1396. jv.recordParams(parameters, false);
  1397. }
  1398. catch (CompileError e) {
  1399. throw new CannotCompileException(e);
  1400. }
  1401. for (FieldInitLink fi = fieldInitializers; fi != null; fi = fi.next) {
  1402. CtField f = fi.field;
  1403. if (!Modifier.isStatic(f.getModifiers())) {
  1404. int s = fi.init.compile(f.getType(), f.getName(), code,
  1405. parameters, jv);
  1406. if (stacksize < s)
  1407. stacksize = s;
  1408. }
  1409. }
  1410. return stacksize;
  1411. }
  1412. // Methods used by CtNewWrappedMethod
  1413. Hashtable getHiddenMethods() {
  1414. if (hiddenMethods == null)
  1415. hiddenMethods = new Hashtable();
  1416. return hiddenMethods;
  1417. }
  1418. int getUniqueNumber() { return uniqueNumberSeed++; }
  1419. public String makeUniqueName(String prefix) {
  1420. HashMap table = new HashMap();
  1421. makeMemberList(table);
  1422. Set keys = table.keySet();
  1423. String[] methods = new String[keys.size()];
  1424. keys.toArray(methods);
  1425. if (notFindInArray(prefix, methods))
  1426. return prefix;
  1427. int i = 100;
  1428. String name;
  1429. do {
  1430. if (i > 999)
  1431. throw new RuntimeException("too many unique name");
  1432. name = prefix + i++;
  1433. } while (!notFindInArray(name, methods));
  1434. return name;
  1435. }
  1436. private static boolean notFindInArray(String prefix, String[] values) {
  1437. int len = values.length;
  1438. for (int i = 0; i < len; i++)
  1439. if (values[i].startsWith(prefix))
  1440. return false;
  1441. return true;
  1442. }
  1443. private void makeMemberList(HashMap table) {
  1444. int mod = getModifiers();
  1445. if (Modifier.isAbstract(mod) || Modifier.isInterface(mod))
  1446. try {
  1447. CtClass[] ifs = getInterfaces();
  1448. int size = ifs.length;
  1449. for (int i = 0; i < size; i++) {
  1450. CtClass ic =ifs[i];
  1451. if (ic != null && ic instanceof CtClassType)
  1452. ((CtClassType)ic).makeMemberList(table);
  1453. }
  1454. }
  1455. catch (NotFoundException e) {}
  1456. try {
  1457. CtClass s = getSuperclass();
  1458. if (s != null && s instanceof CtClassType)
  1459. ((CtClassType)s).makeMemberList(table);
  1460. }
  1461. catch (NotFoundException e) {}
  1462. List list = getClassFile2().getMethods();
  1463. int n = list.size();
  1464. for (int i = 0; i < n; i++) {
  1465. MethodInfo minfo = (MethodInfo)list.get(i);
  1466. table.put(minfo.getName(), this);
  1467. }
  1468. list = getClassFile2().getFields();
  1469. n = list.size();
  1470. for (int i = 0; i < n; i++) {
  1471. FieldInfo finfo = (FieldInfo)list.get(i);
  1472. table.put(finfo.getName(), this);
  1473. }
  1474. }
  1475. }
  1476. class FieldInitLink {
  1477. FieldInitLink next;
  1478. CtField field;
  1479. CtField.Initializer init;
  1480. FieldInitLink(CtField f, CtField.Initializer i) {
  1481. next = null;
  1482. field = f;
  1483. init = i;
  1484. }
  1485. }