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.

Utility.java 33KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094
  1. package org.aspectj.apache.bcel.classfile;
  2. /* ====================================================================
  3. * The Apache Software License, Version 1.1
  4. *
  5. * Copyright (c) 2001 The Apache Software Foundation. All rights
  6. * reserved.
  7. *
  8. * Redistribution and use in source and binary forms, with or without
  9. * modification, are permitted provided that the following conditions
  10. * are met:
  11. *
  12. * 1. Redistributions of source code must retain the above copyright
  13. * notice, this list of conditions and the following disclaimer.
  14. *
  15. * 2. Redistributions in binary form must reproduce the above copyright
  16. * notice, this list of conditions and the following disclaimer in
  17. * the documentation and/or other materials provided with the
  18. * distribution.
  19. *
  20. * 3. The end-user documentation included with the redistribution,
  21. * if any, must include the following acknowledgment:
  22. * "This product includes software developed by the
  23. * Apache Software Foundation (http://www.apache.org/)."
  24. * Alternately, this acknowledgment may appear in the software itself,
  25. * if and wherever such third-party acknowledgments normally appear.
  26. *
  27. * 4. The names "Apache" and "Apache Software Foundation" and
  28. * "Apache BCEL" must not be used to endorse or promote products
  29. * derived from this software without prior written permission. For
  30. * written permission, please contact apache@apache.org.
  31. *
  32. * 5. Products derived from this software may not be called "Apache",
  33. * "Apache BCEL", nor may "Apache" appear in their name, without
  34. * prior written permission of the Apache Software Foundation.
  35. *
  36. * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
  37. * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  38. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  39. * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
  40. * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  41. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  42. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
  43. * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  44. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  45. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
  46. * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  47. * SUCH DAMAGE.
  48. * ====================================================================
  49. *
  50. * This software consists of voluntary contributions made by many
  51. * individuals on behalf of the Apache Software Foundation. For more
  52. * information on the Apache Software Foundation, please see
  53. * <http://www.apache.org/>.
  54. */
  55. import java.io.ByteArrayOutputStream;
  56. import java.io.DataOutputStream;
  57. import java.io.IOException;
  58. import java.util.ArrayList;
  59. import java.util.Collection;
  60. import java.util.List;
  61. import org.aspectj.apache.bcel.Constants;
  62. import org.aspectj.apache.bcel.classfile.annotation.AnnotationGen;
  63. import org.aspectj.apache.bcel.classfile.annotation.RuntimeAnnos;
  64. import org.aspectj.apache.bcel.classfile.annotation.RuntimeInvisAnnos;
  65. import org.aspectj.apache.bcel.classfile.annotation.RuntimeInvisParamAnnos;
  66. import org.aspectj.apache.bcel.classfile.annotation.RuntimeParamAnnos;
  67. import org.aspectj.apache.bcel.classfile.annotation.RuntimeVisAnnos;
  68. import org.aspectj.apache.bcel.classfile.annotation.RuntimeVisParamAnnos;
  69. import org.aspectj.apache.bcel.generic.Type;
  70. import org.aspectj.apache.bcel.util.ByteSequence;
  71. /**
  72. * Utility functions that do not really belong to any class in particular.
  73. *
  74. * @version $Id: Utility.java,v 1.14 2009/09/28 16:39:46 aclement Exp $
  75. * @author <A HREF="mailto:markus.dahm@berlin.de">M. Dahm</A>
  76. *
  77. * modified: Andy Clement 2-mar-05 Removed unnecessary static and optimized
  78. */
  79. public abstract class Utility {
  80. /*
  81. * The 'WIDE' instruction is used in the byte code to allow 16-bit wide indices for local variables. This opcode precedes an
  82. * 'ILOAD', e.g.. The opcode immediately following takes an extra byte which is combined with the following byte to form a
  83. * 16-bit value.
  84. */
  85. private static boolean wide = false;
  86. /**
  87. * Convert bit field of flags into string such as 'static final'.
  88. *
  89. * @param access_flags Access flags
  90. * @return String representation of flags
  91. */
  92. public static final String accessToString(int access_flags) {
  93. return accessToString(access_flags, false);
  94. }
  95. /**
  96. * Convert bit field of flags into string such as 'static final'.
  97. *
  98. * Special case: Classes compiled with new compilers and with the 'ACC_SUPER' flag would be said to be "synchronized". This is
  99. * because SUN used the same value for the flags 'ACC_SUPER' and 'ACC_SYNCHRONIZED'.
  100. *
  101. * @param access_flags Access flags
  102. * @param for_class access flags are for class qualifiers ?
  103. * @return String representation of flags
  104. */
  105. public static final String accessToString(int access_flags, boolean for_class) {
  106. StringBuilder buf = new StringBuilder();
  107. int p = 0;
  108. for (int i = 0; p < Constants.MAX_ACC_FLAG; i++) { // Loop through known flags
  109. p = pow2(i);
  110. if ((access_flags & p) != 0) {
  111. // Special case: see comment at top of class...
  112. if (for_class && ((p == Constants.ACC_SUPER) || (p == Constants.ACC_INTERFACE))) {
  113. continue;
  114. }
  115. buf.append(Constants.ACCESS_NAMES[i]).append(" ");
  116. }
  117. }
  118. return buf.toString().trim();
  119. }
  120. /**
  121. * @return "class" or "interface", depending on the ACC_INTERFACE flag
  122. */
  123. public static final String classOrInterface(int access_flags) {
  124. return ((access_flags & Constants.ACC_INTERFACE) != 0) ? "interface" : "class";
  125. }
  126. /**
  127. * Disassemble a byte array of JVM byte codes starting from code line 'index' and return the disassembled string representation.
  128. * Decode only 'num' opcodes (including their operands), use -1 if you want to decompile everything.
  129. *
  130. * @param code byte code array
  131. * @param constant_pool Array of constants
  132. * @param index offset in `code' array <EM>(number of opcodes, not bytes!)</EM>
  133. * @param length number of opcodes to decompile, -1 for all
  134. * @param verbose be verbose, e.g. print constant pool index
  135. * @return String representation of byte codes
  136. */
  137. public static final String codeToString(byte[] code, ConstantPool constant_pool, int index, int length, boolean verbose) {
  138. StringBuilder buf = new StringBuilder(code.length * 20); // Should be sufficient
  139. ByteSequence stream = new ByteSequence(code);
  140. try {
  141. for (int i = 0; i < index; i++) {
  142. // Skip `index' lines of code
  143. codeToString(stream, constant_pool, verbose);
  144. }
  145. for (int i = 0; stream.available() > 0; i++) {
  146. if ((length < 0) || (i < length)) {
  147. String indices = fillup(stream.getIndex() + ":", 6, true, ' ');
  148. buf.append(indices + codeToString(stream, constant_pool, verbose) + '\n');
  149. }
  150. }
  151. } catch (IOException e) {
  152. System.out.println(buf.toString());
  153. e.printStackTrace();
  154. throw new ClassFormatException("Byte code error: " + e);
  155. }
  156. return buf.toString();
  157. }
  158. /**
  159. * Disassemble a stream of byte codes and return the string representation.
  160. */
  161. public static final String codeToString(byte[] code, ConstantPool constant_pool, int index, int length) {
  162. return codeToString(code, constant_pool, index, length, true);
  163. }
  164. public static final String codeToString(ByteSequence bytes, ConstantPool constant_pool) throws IOException {
  165. return codeToString(bytes, constant_pool, true);
  166. }
  167. /**
  168. * Shorten long class names, <em>java/lang/String</em> becomes <em>String</em>.
  169. *
  170. * @param str The long class name
  171. * @return Compacted class name
  172. */
  173. public static final String compactClassName(String str) {
  174. return compactClassName(str, true);
  175. }
  176. /**
  177. * Shorten long class name <em>str</em>, i.e., chop off the <em>prefix</em>, if the class name starts with this string and the
  178. * flag <em>chopit</em> is true. Slashes <em>/</em> are converted to dots <em>.</em>.
  179. *
  180. * @param str The long class name
  181. * @param prefix The prefix the get rid off
  182. * @param chopit Flag that determines whether chopping is executed or not
  183. * @return Compacted class name
  184. */
  185. public static final String compactClassName(String str, String prefix, boolean chopit) {
  186. str = str.replace('/', '.');
  187. if (chopit) {
  188. int len = prefix.length();
  189. // If string starts with 'prefix' and contains no further dots
  190. if (str.startsWith(prefix)) {
  191. String result = str.substring(len);
  192. if (result.indexOf('.') == -1) {
  193. str = result;
  194. }
  195. }
  196. }
  197. return str;
  198. }
  199. /**
  200. * Shorten long class names, <em>java/lang/String</em> becomes <em>java.lang.String</em>, e.g.. If <em>chopit</em> is
  201. * <em>true</em> the prefix <em>java.lang</em> is also removed.
  202. *
  203. * @param str The long class name
  204. * @param chopit Flag that determines whether chopping is executed or not
  205. * @return Compacted class name
  206. */
  207. public static final String compactClassName(String str, boolean chopit) {
  208. return compactClassName(str, "java.lang.", chopit);
  209. }
  210. public static final String methodSignatureToString(String signature, String name, String access) {
  211. return methodSignatureToString(signature, name, access, true);
  212. }
  213. public static final String methodSignatureToString(String signature, String name, String access, boolean chopit) {
  214. return methodSignatureToString(signature, name, access, chopit, null);
  215. }
  216. /**
  217. * This method converts such a string into a Java type declaration like 'void main(String[])' and throws a
  218. * 'ClassFormatException' when the parsed type is invalid.
  219. */
  220. public static final String methodSignatureToString(String signature, String name, String access, boolean chopit,
  221. LocalVariableTable vars) throws ClassFormatException {
  222. StringBuilder buf = new StringBuilder("(");
  223. String type;
  224. int index;
  225. int var_index = (access.contains("static")) ? 0 : 1;
  226. try { // Read all declarations between for `(' and `)'
  227. if (signature.charAt(0) != '(') {
  228. throw new ClassFormatException("Invalid method signature: " + signature);
  229. }
  230. index = 1; // current string position
  231. while (signature.charAt(index) != ')') {
  232. ResultHolder rh = signatureToStringInternal(signature.substring(index), chopit);
  233. String param_type = rh.getResult();
  234. buf.append(param_type);
  235. if (vars != null) {
  236. LocalVariable l = vars.getLocalVariable(var_index);
  237. if (l != null) {
  238. buf.append(" " + l.getName());
  239. }
  240. } else {
  241. buf.append(" arg" + var_index);
  242. }
  243. if ("double".equals(param_type) || "long".equals(param_type)) {
  244. var_index += 2;
  245. } else {
  246. var_index++;
  247. }
  248. buf.append(", ");
  249. index += rh.getConsumedChars();
  250. }
  251. index++;
  252. // Read return type after `)'
  253. type = signatureToString(signature.substring(index), chopit);
  254. } catch (StringIndexOutOfBoundsException e) { // Should never occur
  255. throw new ClassFormatException("Invalid method signature: " + signature);
  256. }
  257. if (buf.length() > 1) {
  258. buf.setLength(buf.length() - 2);
  259. }
  260. buf.append(")");
  261. return access + ((access.length() > 0) ? " " : "") + // May be an empty string
  262. type + " " + name + buf.toString();
  263. }
  264. /**
  265. * Replace all occurences of <em>old</em> in <em>str</em> with <em>new</em>.
  266. *
  267. * @param str String to permute
  268. * @param old String to be replaced
  269. * @param new Replacement string
  270. * @return new String object
  271. */
  272. public static final String replace(String str, String old, String new_) {
  273. int index, old_index;
  274. StringBuilder buf = new StringBuilder();
  275. try {
  276. index = str.indexOf(old);
  277. if (index != -1) {
  278. old_index = 0;
  279. // While we have something to replace
  280. while ((index = str.indexOf(old, old_index)) != -1) {
  281. buf.append(str.substring(old_index, index)); // append prefix
  282. buf.append(new_); // append replacement
  283. old_index = index + old.length(); // Skip 'old'.length chars
  284. }
  285. buf.append(str.substring(old_index)); // append rest of string
  286. str = buf.toString();
  287. }
  288. } catch (StringIndexOutOfBoundsException e) {
  289. System.err.println(e);
  290. }
  291. return str;
  292. }
  293. /**
  294. * Converts signature to string with all class names compacted.
  295. *
  296. * @param signature to convert
  297. * @return Human readable signature
  298. */
  299. public static final String signatureToString(String signature) {
  300. return signatureToString(signature, true);
  301. }
  302. public static final String signatureToString(String signature, boolean chopit) {
  303. ResultHolder rh = signatureToStringInternal(signature, chopit);
  304. return rh.getResult();
  305. }
  306. /**
  307. * This method converts this string into a Java type declaration such as 'String[]' and throws a `ClassFormatException' when the
  308. * parsed type is invalid.
  309. */
  310. public static final ResultHolder signatureToStringInternal(String signature, boolean chopit) {
  311. int processedChars = 1; // This is the default, read just one char
  312. try {
  313. switch (signature.charAt(0)) {
  314. case 'B':
  315. return ResultHolder.BYTE;
  316. case 'C':
  317. return ResultHolder.CHAR;
  318. case 'D':
  319. return ResultHolder.DOUBLE;
  320. case 'F':
  321. return ResultHolder.FLOAT;
  322. case 'I':
  323. return ResultHolder.INT;
  324. case 'J':
  325. return ResultHolder.LONG;
  326. case 'L': { // Full class name
  327. int index = signature.indexOf(';'); // Look for closing ';'
  328. if (index < 0) {
  329. throw new ClassFormatException("Invalid signature: " + signature);
  330. }
  331. if (signature.length() > index + 1 && signature.charAt(index + 1) == '>') {
  332. index = index + 2;
  333. }
  334. int genericStart = signature.indexOf('<');
  335. if (genericStart != -1) {
  336. int genericEnd = signature.indexOf('>');
  337. // FIXME asc going to need a lot more work in here for generics
  338. ResultHolder rh = signatureToStringInternal(signature.substring(genericStart + 1, genericEnd), chopit);
  339. StringBuilder sb = new StringBuilder();
  340. sb.append(signature.substring(1, genericStart));
  341. sb.append("<").append(rh.getResult()).append(">");
  342. ResultHolder retval = new ResultHolder(compactClassName(sb.toString(), chopit), genericEnd + 1);
  343. return retval;
  344. } else {
  345. processedChars = index + 1; // "Lblabla;" `L' and `;' are removed
  346. ResultHolder retval = new ResultHolder(compactClassName(signature.substring(1, index), chopit), processedChars);
  347. return retval;
  348. }
  349. }
  350. case 'S':
  351. return ResultHolder.SHORT;
  352. case 'Z':
  353. return ResultHolder.BOOLEAN;
  354. case '[': { // Array declaration
  355. StringBuilder brackets;
  356. int consumedChars, n;
  357. brackets = new StringBuilder(); // Accumulate []'s
  358. // Count opening brackets and look for optional size argument
  359. for (n = 0; signature.charAt(n) == '['; n++) {
  360. brackets.append("[]");
  361. }
  362. consumedChars = n;
  363. ResultHolder restOfIt = signatureToStringInternal(signature.substring(n), chopit);
  364. consumedChars += restOfIt.getConsumedChars();
  365. brackets.insert(0, restOfIt.getResult());
  366. return new ResultHolder(brackets.toString(), consumedChars);
  367. }
  368. case 'V':
  369. return ResultHolder.VOID;
  370. default:
  371. throw new ClassFormatException("Invalid signature: `" + signature + "'");
  372. }
  373. } catch (StringIndexOutOfBoundsException e) { // Should never occur
  374. throw new ClassFormatException("Invalid signature: " + e + ":" + signature);
  375. }
  376. }
  377. /**
  378. * Return type of method signature as a byte value as defined in <em>Constants</em>
  379. *
  380. * @param signature in format described above
  381. * @return type of method signature
  382. * @see Constants
  383. */
  384. public static final byte typeOfMethodSignature(String signature) throws ClassFormatException {
  385. int index;
  386. try {
  387. if (signature.charAt(0) != '(') {
  388. throw new ClassFormatException("Invalid method signature: " + signature);
  389. }
  390. index = signature.lastIndexOf(')') + 1;
  391. return typeOfSignature(signature.substring(index));
  392. } catch (StringIndexOutOfBoundsException e) {
  393. throw new ClassFormatException("Invalid method signature: " + signature);
  394. }
  395. }
  396. /**
  397. * Convert (signed) byte to (unsigned) short value, i.e., all negative values become positive.
  398. */
  399. private static final short byteToShort(byte b) {
  400. return (b < 0) ? (short) (256 + b) : (short) b;
  401. }
  402. /**
  403. * Convert bytes into hexidecimal string
  404. *
  405. * @return bytes as hexidecimal string, e.g. 00 FA 12 ...
  406. */
  407. public static final String toHexString(byte[] bytes) {
  408. StringBuilder buf = new StringBuilder();
  409. for (int i = 0; i < bytes.length; i++) {
  410. short b = byteToShort(bytes[i]);
  411. String hex = Integer.toString(b, 0x10);
  412. // Just one digit, so prepend 0
  413. if (b < 0x10) {
  414. buf.append('0');
  415. }
  416. buf.append(hex);
  417. if (i < bytes.length - 1) {
  418. buf.append(' ');
  419. }
  420. }
  421. return buf.toString();
  422. }
  423. /**
  424. * Return a string for an integer justified left or right and filled up with 'fill' characters if necessary.
  425. *
  426. * @param i integer to format
  427. * @param length length of desired string
  428. * @param left_justify format left or right
  429. * @param fill fill character
  430. * @return formatted int
  431. */
  432. public static final String format(int i, int length, boolean left_justify, char fill) {
  433. return fillup(Integer.toString(i), length, left_justify, fill);
  434. }
  435. /**
  436. * Fillup char with up to length characters with char `fill' and justify it left or right.
  437. *
  438. * @param str string to format
  439. * @param length length of desired string
  440. * @param left_justify format left or right
  441. * @param fill fill character
  442. * @return formatted string
  443. */
  444. public static final String fillup(String str, int length, boolean left_justify, char fill) {
  445. int len = length - str.length();
  446. char[] buf = new char[(len < 0) ? 0 : len];
  447. for (int j = 0; j < buf.length; j++) {
  448. buf[j] = fill;
  449. }
  450. if (left_justify) {
  451. return str + new String(buf);
  452. } else {
  453. return new String(buf) + str;
  454. }
  455. }
  456. /**
  457. * Escape all occurences of newline chars '\n', quotes \", etc.
  458. */
  459. public static final String convertString(String label) {
  460. char[] ch = label.toCharArray();
  461. StringBuilder buf = new StringBuilder();
  462. for (char c : ch) {
  463. switch (c) {
  464. case '\n':
  465. buf.append("\\n");
  466. break;
  467. case '\r':
  468. buf.append("\\r");
  469. break;
  470. case '\"':
  471. buf.append("\\\"");
  472. break;
  473. case '\'':
  474. buf.append("\\'");
  475. break;
  476. case '\\':
  477. buf.append("\\\\");
  478. break;
  479. default:
  480. buf.append(c);
  481. break;
  482. }
  483. }
  484. return buf.toString();
  485. }
  486. /**
  487. * Converts a list of AnnotationGen objects into a set of attributes that can be attached to the class file.
  488. *
  489. * @param cp The constant pool gen where we can create the necessary name refs
  490. * @param annotations A list of AnnotationGen objects
  491. */
  492. public static Collection<RuntimeAnnos> getAnnotationAttributes(ConstantPool cp, List<AnnotationGen> annotations) {
  493. if (annotations.size() == 0) {
  494. return null;
  495. }
  496. try {
  497. int countVisible = 0;
  498. int countInvisible = 0;
  499. // put the annotations in the right output stream
  500. for (AnnotationGen a : annotations) {
  501. if (a.isRuntimeVisible()) {
  502. countVisible++;
  503. } else {
  504. countInvisible++;
  505. }
  506. }
  507. ByteArrayOutputStream rvaBytes = new ByteArrayOutputStream();
  508. ByteArrayOutputStream riaBytes = new ByteArrayOutputStream();
  509. DataOutputStream rvaDos = new DataOutputStream(rvaBytes);
  510. DataOutputStream riaDos = new DataOutputStream(riaBytes);
  511. rvaDos.writeShort(countVisible);
  512. riaDos.writeShort(countInvisible);
  513. // put the annotations in the right output stream
  514. for (AnnotationGen a : annotations) {
  515. if (a.isRuntimeVisible()) {
  516. a.dump(rvaDos);
  517. } else {
  518. a.dump(riaDos);
  519. }
  520. }
  521. rvaDos.close();
  522. riaDos.close();
  523. byte[] rvaData = rvaBytes.toByteArray();
  524. byte[] riaData = riaBytes.toByteArray();
  525. int rvaIndex = -1;
  526. int riaIndex = -1;
  527. if (rvaData.length > 2) {
  528. rvaIndex = cp.addUtf8("RuntimeVisibleAnnotations");
  529. }
  530. if (riaData.length > 2) {
  531. riaIndex = cp.addUtf8("RuntimeInvisibleAnnotations");
  532. }
  533. List<RuntimeAnnos> newAttributes = new ArrayList<>();
  534. if (rvaData.length > 2) {
  535. newAttributes.add(new RuntimeVisAnnos(rvaIndex, rvaData.length, rvaData, cp));
  536. }
  537. if (riaData.length > 2) {
  538. newAttributes.add(new RuntimeInvisAnnos(riaIndex, riaData.length, riaData, cp));
  539. }
  540. return newAttributes;
  541. } catch (IOException e) {
  542. System.err.println("IOException whilst processing annotations");
  543. e.printStackTrace();
  544. }
  545. return null;
  546. }
  547. /**
  548. * Annotations against a class are stored in one of four attribute kinds: - RuntimeVisibleParameterAnnotations -
  549. * RuntimeInvisibleParameterAnnotations
  550. */
  551. // OPTIMIZE looks heavyweight?
  552. public static Attribute[] getParameterAnnotationAttributes(ConstantPool cp, List<AnnotationGen>[] vec) {
  553. int visCount[] = new int[vec.length];
  554. int totalVisCount = 0;
  555. int invisCount[] = new int[vec.length];
  556. int totalInvisCount = 0;
  557. try {
  558. for (int i = 0; i < vec.length; i++) {
  559. List<AnnotationGen> l = vec[i];
  560. if (l != null) {
  561. for (AnnotationGen element : l) {
  562. if (element.isRuntimeVisible()) {
  563. visCount[i]++;
  564. totalVisCount++;
  565. } else {
  566. invisCount[i]++;
  567. totalInvisCount++;
  568. }
  569. }
  570. }
  571. }
  572. // Lets do the visible ones
  573. ByteArrayOutputStream rvaBytes = new ByteArrayOutputStream();
  574. DataOutputStream rvaDos = new DataOutputStream(rvaBytes);
  575. rvaDos.writeByte(vec.length); // First goes number of parameters
  576. for (int i = 0; i < vec.length; i++) {
  577. rvaDos.writeShort(visCount[i]);
  578. if (visCount[i] > 0) {
  579. List<AnnotationGen> l = vec[i];
  580. for (AnnotationGen element : l) {
  581. if (element.isRuntimeVisible()) {
  582. element.dump(rvaDos);
  583. }
  584. }
  585. }
  586. }
  587. rvaDos.close();
  588. // Lets do the invisible ones
  589. ByteArrayOutputStream riaBytes = new ByteArrayOutputStream();
  590. DataOutputStream riaDos = new DataOutputStream(riaBytes);
  591. riaDos.writeByte(vec.length); // First goes number of parameters
  592. for (int i = 0; i < vec.length; i++) {
  593. riaDos.writeShort(invisCount[i]);
  594. if (invisCount[i] > 0) {
  595. List<AnnotationGen> l = vec[i];
  596. for (AnnotationGen element : l) {
  597. if (!element.isRuntimeVisible()) {
  598. element.dump(riaDos);
  599. }
  600. }
  601. }
  602. }
  603. riaDos.close();
  604. byte[] rvaData = rvaBytes.toByteArray();
  605. byte[] riaData = riaBytes.toByteArray();
  606. int rvaIndex = -1;
  607. int riaIndex = -1;
  608. if (totalVisCount > 0) {
  609. rvaIndex = cp.addUtf8("RuntimeVisibleParameterAnnotations");
  610. }
  611. if (totalInvisCount > 0) {
  612. riaIndex = cp.addUtf8("RuntimeInvisibleParameterAnnotations");
  613. }
  614. List<RuntimeParamAnnos> newAttributes = new ArrayList<>();
  615. if (totalVisCount > 0) {
  616. newAttributes.add(new RuntimeVisParamAnnos(rvaIndex, rvaData.length, rvaData, cp));
  617. }
  618. if (totalInvisCount > 0) {
  619. newAttributes.add(new RuntimeInvisParamAnnos(riaIndex, riaData.length, riaData, cp));
  620. }
  621. return newAttributes.toArray(new Attribute[] {});
  622. } catch (IOException e) {
  623. System.err.println("IOException whilst processing parameter annotations");
  624. e.printStackTrace();
  625. }
  626. return null;
  627. }
  628. public static class ResultHolder {
  629. private String result;
  630. private int consumed;
  631. public static final ResultHolder BYTE = new ResultHolder("byte", 1);
  632. public static final ResultHolder CHAR = new ResultHolder("char", 1);
  633. public static final ResultHolder DOUBLE = new ResultHolder("double", 1);
  634. public static final ResultHolder FLOAT = new ResultHolder("float", 1);
  635. public static final ResultHolder INT = new ResultHolder("int", 1);
  636. public static final ResultHolder LONG = new ResultHolder("long", 1);
  637. public static final ResultHolder SHORT = new ResultHolder("short", 1);
  638. public static final ResultHolder BOOLEAN = new ResultHolder("boolean", 1);
  639. public static final ResultHolder VOID = new ResultHolder("void", 1);
  640. public ResultHolder(String s, int c) {
  641. result = s;
  642. consumed = c;
  643. }
  644. public String getResult() {
  645. return result;
  646. }
  647. public int getConsumedChars() {
  648. return consumed;
  649. }
  650. }
  651. /**
  652. * Return type of signature as a byte value as defined in <em>Constants</em>
  653. *
  654. * @param signature in format described above
  655. * @return type of signature
  656. * @see Constants
  657. */
  658. public static final byte typeOfSignature(String signature) throws ClassFormatException {
  659. try {
  660. switch (signature.charAt(0)) {
  661. case 'B':
  662. return Constants.T_BYTE;
  663. case 'C':
  664. return Constants.T_CHAR;
  665. case 'D':
  666. return Constants.T_DOUBLE;
  667. case 'F':
  668. return Constants.T_FLOAT;
  669. case 'I':
  670. return Constants.T_INT;
  671. case 'J':
  672. return Constants.T_LONG;
  673. case 'L':
  674. return Constants.T_REFERENCE;
  675. case '[':
  676. return Constants.T_ARRAY;
  677. case 'V':
  678. return Constants.T_VOID;
  679. case 'Z':
  680. return Constants.T_BOOLEAN;
  681. case 'S':
  682. return Constants.T_SHORT;
  683. default:
  684. throw new ClassFormatException("Invalid method signature: " + signature);
  685. }
  686. } catch (StringIndexOutOfBoundsException e) {
  687. throw new ClassFormatException("Invalid method signature: " + signature);
  688. }
  689. }
  690. public static final byte typeOfSignature(char c) throws ClassFormatException {
  691. switch (c) {
  692. case 'B':
  693. return Constants.T_BYTE;
  694. case 'C':
  695. return Constants.T_CHAR;
  696. case 'D':
  697. return Constants.T_DOUBLE;
  698. case 'F':
  699. return Constants.T_FLOAT;
  700. case 'I':
  701. return Constants.T_INT;
  702. case 'J':
  703. return Constants.T_LONG;
  704. case 'L':
  705. return Constants.T_REFERENCE;
  706. case '[':
  707. return Constants.T_ARRAY;
  708. case 'V':
  709. return Constants.T_VOID;
  710. case 'Z':
  711. return Constants.T_BOOLEAN;
  712. case 'S':
  713. return Constants.T_SHORT;
  714. default:
  715. throw new ClassFormatException("Invalid type of signature: " + c);
  716. }
  717. }
  718. /**
  719. * Disassemble a stream of byte codes and return the string representation.
  720. *
  721. * @param bytes stream of bytes
  722. * @param constant_pool Array of constants
  723. * @param verbose be verbose, e.g. print constant pool index
  724. * @return String representation of byte code
  725. */
  726. public static final String codeToString(ByteSequence bytes, ConstantPool constant_pool, boolean verbose) throws IOException {
  727. short opcode = (short) bytes.readUnsignedByte();
  728. int default_offset = 0, low, high, npairs;
  729. int index, vindex, constant;
  730. int[] match, jump_table;
  731. int no_pad_bytes = 0, offset;
  732. StringBuilder buf = new StringBuilder(Constants.OPCODE_NAMES[opcode]);
  733. /*
  734. * Special case: Skip (0-3) padding bytes, i.e., the following bytes are 4-byte-aligned
  735. */
  736. if ((opcode == Constants.TABLESWITCH) || (opcode == Constants.LOOKUPSWITCH)) {
  737. int remainder = bytes.getIndex() % 4;
  738. no_pad_bytes = (remainder == 0) ? 0 : 4 - remainder;
  739. for (int i = 0; i < no_pad_bytes; i++) {
  740. byte b = bytes.readByte();
  741. if (b != 0) {
  742. System.err.println("Warning: Padding byte != 0 in " + Constants.OPCODE_NAMES[opcode] + ":" + b);
  743. }
  744. }
  745. // Both cases have a field default_offset in common
  746. default_offset = bytes.readInt();
  747. }
  748. switch (opcode) {
  749. /*
  750. * Table switch has variable length arguments.
  751. */
  752. case Constants.TABLESWITCH:
  753. low = bytes.readInt();
  754. high = bytes.readInt();
  755. offset = bytes.getIndex() - 12 - no_pad_bytes - 1;
  756. default_offset += offset;
  757. buf.append("\tdefault = " + default_offset + ", low = " + low + ", high = " + high + "(");
  758. jump_table = new int[high - low + 1];
  759. for (int i = 0; i < jump_table.length; i++) {
  760. jump_table[i] = offset + bytes.readInt();
  761. buf.append(jump_table[i]);
  762. if (i < jump_table.length - 1) {
  763. buf.append(", ");
  764. }
  765. }
  766. buf.append(")");
  767. break;
  768. /*
  769. * Lookup switch has variable length arguments.
  770. */
  771. case Constants.LOOKUPSWITCH: {
  772. npairs = bytes.readInt();
  773. offset = bytes.getIndex() - 8 - no_pad_bytes - 1;
  774. match = new int[npairs];
  775. jump_table = new int[npairs];
  776. default_offset += offset;
  777. buf.append("\tdefault = " + default_offset + ", npairs = " + npairs + " (");
  778. for (int i = 0; i < npairs; i++) {
  779. match[i] = bytes.readInt();
  780. jump_table[i] = offset + bytes.readInt();
  781. buf.append("(" + match[i] + ", " + jump_table[i] + ")");
  782. if (i < npairs - 1) {
  783. buf.append(", ");
  784. }
  785. }
  786. buf.append(")");
  787. }
  788. break;
  789. // Two address bytes + offset from start of byte stream form the jump target
  790. case Constants.GOTO:
  791. case Constants.IFEQ:
  792. case Constants.IFGE:
  793. case Constants.IFGT:
  794. case Constants.IFLE:
  795. case Constants.IFLT:
  796. case Constants.JSR:
  797. case Constants.IFNE:
  798. case Constants.IFNONNULL:
  799. case Constants.IFNULL:
  800. case Constants.IF_ACMPEQ:
  801. case Constants.IF_ACMPNE:
  802. case Constants.IF_ICMPEQ:
  803. case Constants.IF_ICMPGE:
  804. case Constants.IF_ICMPGT:
  805. case Constants.IF_ICMPLE:
  806. case Constants.IF_ICMPLT:
  807. case Constants.IF_ICMPNE:
  808. buf.append("\t\t#" + ((bytes.getIndex() - 1) + bytes.readShort()));
  809. break;
  810. // 32-bit wide jumps
  811. case Constants.GOTO_W:
  812. case Constants.JSR_W:
  813. buf.append("\t\t#" + ((bytes.getIndex() - 1) + bytes.readInt()));
  814. break;
  815. // Index byte references local variable (register)
  816. case Constants.ALOAD:
  817. case Constants.ASTORE:
  818. case Constants.DLOAD:
  819. case Constants.DSTORE:
  820. case Constants.FLOAD:
  821. case Constants.FSTORE:
  822. case Constants.ILOAD:
  823. case Constants.ISTORE:
  824. case Constants.LLOAD:
  825. case Constants.LSTORE:
  826. case Constants.RET:
  827. if (wide) {
  828. vindex = bytes.readUnsignedShort();
  829. wide = false; // Clear flag
  830. } else {
  831. vindex = bytes.readUnsignedByte();
  832. }
  833. buf.append("\t\t%" + vindex);
  834. break;
  835. /*
  836. * Remember wide byte which is used to form a 16-bit address in the following instruction. Relies on that the method is
  837. * called again with the following opcode.
  838. */
  839. case Constants.WIDE:
  840. wide = true;
  841. buf.append("\t(wide)");
  842. break;
  843. // Array of basic type
  844. case Constants.NEWARRAY:
  845. buf.append("\t\t<" + Constants.TYPE_NAMES[bytes.readByte()] + ">");
  846. break;
  847. // Access object/class fields
  848. case Constants.GETFIELD:
  849. case Constants.GETSTATIC:
  850. case Constants.PUTFIELD:
  851. case Constants.PUTSTATIC:
  852. index = bytes.readUnsignedShort();
  853. buf.append("\t\t" + constant_pool.constantToString(index, Constants.CONSTANT_Fieldref)
  854. + (verbose ? " (" + index + ")" : ""));
  855. break;
  856. // Operands are references to classes in constant pool
  857. case Constants.NEW:
  858. case Constants.CHECKCAST:
  859. buf.append("\t");
  860. case Constants.INSTANCEOF:
  861. index = bytes.readUnsignedShort();
  862. buf.append("\t<" + constant_pool.constantToString(index) + ">" + (verbose ? " (" + index + ")" : ""));
  863. break;
  864. // Operands are references to methods in constant pool
  865. case Constants.INVOKESPECIAL:
  866. case Constants.INVOKESTATIC:
  867. case Constants.INVOKEVIRTUAL:
  868. index = bytes.readUnsignedShort();
  869. buf.append("\t" + constant_pool.constantToString(index) + (verbose ? " (" + index + ")" : ""));
  870. break;
  871. case Constants.INVOKEINTERFACE:
  872. index = bytes.readUnsignedShort();
  873. int nargs = bytes.readUnsignedByte(); // historical, redundant
  874. buf.append("\t" + constant_pool.constantToString(index) + (verbose ? " (" + index + ")\t" : "") + nargs + "\t"
  875. + bytes.readUnsignedByte()); // Last byte is a reserved
  876. // space
  877. break;
  878. case Constants.INVOKEDYNAMIC://http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-6.html#jvms-6.5.invokedynamic
  879. index = bytes.readUnsignedShort();
  880. bytes.readUnsignedShort(); // zeroes
  881. buf.append("\t" + constant_pool.constantToString(index) + (verbose ? " (" + index + ")" : ""));
  882. break;
  883. // Operands are references to items in constant pool
  884. case Constants.LDC_W:
  885. case Constants.LDC2_W:
  886. index = bytes.readUnsignedShort();
  887. buf.append("\t\t" + constant_pool.constantToString(index) + (verbose ? " (" + index + ")" : ""));
  888. break;
  889. case Constants.LDC:
  890. index = bytes.readUnsignedByte();
  891. buf.append("\t\t" + constant_pool.constantToString(index) + (verbose ? " (" + index + ")" : ""));
  892. break;
  893. // Array of references
  894. case Constants.ANEWARRAY:
  895. index = bytes.readUnsignedShort();
  896. buf.append("\t\t<" + compactClassName(constant_pool.getConstantString(index, Constants.CONSTANT_Class), false) + ">"
  897. + (verbose ? " (" + index + ")" : ""));
  898. break;
  899. // Multidimensional array of references
  900. case Constants.MULTIANEWARRAY: {
  901. index = bytes.readUnsignedShort();
  902. int dimensions = bytes.readUnsignedByte();
  903. buf.append("\t<" + compactClassName(constant_pool.getConstantString(index, Constants.CONSTANT_Class), false) + ">\t"
  904. + dimensions + (verbose ? " (" + index + ")" : ""));
  905. }
  906. break;
  907. // Increment local variable
  908. case Constants.IINC:
  909. if (wide) {
  910. vindex = bytes.readUnsignedShort();
  911. constant = bytes.readShort();
  912. wide = false;
  913. } else {
  914. vindex = bytes.readUnsignedByte();
  915. constant = bytes.readByte();
  916. }
  917. buf.append("\t\t%" + vindex + "\t" + constant);
  918. break;
  919. default:
  920. if ((Constants.iLen[opcode] - 1) > 0) {
  921. for (int i = 0; i < Constants.TYPE_OF_OPERANDS[opcode].length; i++) {
  922. buf.append("\t\t");
  923. switch (Constants.TYPE_OF_OPERANDS[opcode][i]) {
  924. case Constants.T_BYTE:
  925. buf.append(bytes.readByte());
  926. break;
  927. case Constants.T_SHORT:
  928. buf.append(bytes.readShort());
  929. break;
  930. case Constants.T_INT:
  931. buf.append(bytes.readInt());
  932. break;
  933. default: // Never reached
  934. System.err.println("Unreachable default case reached!");
  935. System.exit(-1);
  936. }
  937. }
  938. }
  939. }
  940. return buf.toString();
  941. }
  942. // private helpers
  943. private static final int pow2(int n) {
  944. return 1 << n;
  945. }
  946. /**
  947. * Convert type to Java method signature, e.g. int[] f(java.lang.String x) becomes (Ljava/lang/String;)[I
  948. *
  949. * @param returnType what the method returns
  950. * @param argTypes what are the argument types
  951. * @return method signature for given type(s).
  952. */
  953. public static String toMethodSignature(Type returnType, Type[] argTypes) {
  954. StringBuilder buf = new StringBuilder("(");
  955. int length = (argTypes == null) ? 0 : argTypes.length;
  956. for (int i = 0; i < length; i++) {
  957. buf.append(argTypes[i].getSignature());
  958. }
  959. buf.append(')');
  960. buf.append(returnType.getSignature());
  961. return buf.toString();
  962. }
  963. }