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.

BCELifier.java 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  1. package org.aspectj.apache.bcel.verifier.util;
  2. /* ====================================================================
  3. * The Apache Software License, Version 1.1
  4. *
  5. * Copyright (c) 2002 The Apache Software Foundation. All rights
  6. * reserved.
  7. *
  8. * Redistribution and use in source and binary forms, with or without
  9. * modification, are permitted provided that the following conditions
  10. * are met:
  11. *
  12. * 1. Redistributions of source code must retain the above copyright
  13. * notice, this list of conditions and the following disclaimer.
  14. *
  15. * 2. Redistributions in binary form must reproduce the above copyright
  16. * notice, this list of conditions and the following disclaimer in
  17. * the documentation and/or other materials provided with the
  18. * distribution.
  19. *
  20. * 3. The end-user documentation included with the redistribution,
  21. * if any, must include the following acknowledgment:
  22. * "This product includes software developed by the
  23. * Apache Software Foundation (https://www.apache.org/)."
  24. * Alternately, this acknowledgment may appear in the software itself,
  25. * if and wherever such third-party acknowledgments normally appear.
  26. *
  27. * 4. The names "Apache" and "Apache Software Foundation" and
  28. * "Apache BCEL" must not be used to endorse or promote products
  29. * derived from this software without prior written permission. For
  30. * written permission, please contact apache@apache.org.
  31. *
  32. * 5. Products derived from this software may not be called "Apache",
  33. * "Apache BCEL", nor may "Apache" appear in their name, without
  34. * prior written permission of the Apache Software Foundation.
  35. *
  36. * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
  37. * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  38. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  39. * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
  40. * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  41. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  42. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
  43. * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  44. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  45. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
  46. * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  47. * SUCH DAMAGE.
  48. * ====================================================================
  49. *
  50. * This software consists of voluntary contributions made by many
  51. * individuals on behalf of the Apache Software Foundation. For more
  52. * information on the Apache Software Foundation, please see
  53. * <https://www.apache.org/>.
  54. */
  55. import java.io.OutputStream;
  56. import java.io.PrintWriter;
  57. import org.aspectj.apache.bcel.Constants;
  58. import org.aspectj.apache.bcel.Repository;
  59. import org.aspectj.apache.bcel.classfile.ClassParser;
  60. import org.aspectj.apache.bcel.classfile.ConstantValue;
  61. import org.aspectj.apache.bcel.classfile.Field;
  62. import org.aspectj.apache.bcel.classfile.JavaClass;
  63. import org.aspectj.apache.bcel.classfile.Method;
  64. import org.aspectj.apache.bcel.classfile.Utility;
  65. import org.aspectj.apache.bcel.generic.ArrayType;
  66. import org.aspectj.apache.bcel.classfile.ConstantPool;
  67. import org.aspectj.apache.bcel.generic.MethodGen;
  68. import org.aspectj.apache.bcel.generic.Type;
  69. /**
  70. * This class takes a given JavaClass object and converts it to a
  71. * Java program that creates that very class using BCEL. This
  72. * gives new users of BCEL a useful example showing how things
  73. * are done with BCEL. It does not cover all features of BCEL,
  74. * but tries to mimic hand-written code as close as possible.
  75. *
  76. * @version $Id: BCELifier.java,v 1.2 2008/05/28 23:53:04 aclement Exp $
  77. * @author <A HREF="mailto:markus.dahm@berlin.de">M. Dahm</A>
  78. */
  79. public class BCELifier extends org.aspectj.apache.bcel.verifier.EmptyClassVisitor {
  80. private JavaClass _clazz;
  81. private PrintWriter _out;
  82. private ConstantPool _cp;
  83. /** @param clazz Java class to "decompile"
  84. * @param out where to output Java program
  85. */
  86. public BCELifier(JavaClass clazz, OutputStream out) {
  87. _clazz = clazz;
  88. _out = new PrintWriter(out);
  89. _cp = new ConstantPool(_clazz.getConstantPool().getConstantPool());
  90. }
  91. /** Start Java code generation
  92. */
  93. public void start() {
  94. visitJavaClass(_clazz);
  95. _out.flush();
  96. }
  97. public void visitJavaClass(JavaClass clazz) {
  98. String class_name = clazz.getClassName();
  99. String super_name = clazz.getSuperclassName();
  100. String package_name = clazz.getPackageName();
  101. String inter = BCELifier.printArray(clazz.getInterfaceNames(),
  102. false, true);
  103. if(!"".equals(package_name)) {
  104. class_name = class_name.substring(package_name.length() + 1);
  105. _out.println("package " + package_name + ";\n");
  106. }
  107. _out.println("import org.aspectj.apache.bcel.generic.*;");
  108. _out.println("import org.aspectj.apache.bcel.classfile.*;");
  109. _out.println("import org.aspectj.apache.bcel.*;");
  110. _out.println("import java.io.*;\n");
  111. _out.println("public class " + class_name + "Creator implements Constants {");
  112. _out.println(" private InstructionFactory _factory;");
  113. _out.println(" private ConstantPoolGen _cp;");
  114. _out.println(" private ClassGen _cg;\n");
  115. _out.println(" public " + class_name + "Creator() {");
  116. _out.println(" _cg = new ClassGen(\"" +
  117. (("".equals(package_name))? class_name :
  118. package_name + "." + class_name) +
  119. "\", \"" + super_name + "\", " +
  120. "\"" + clazz.getSourceFileName() + "\", " +
  121. printFlags(clazz.getModifiers(), true) + ", " +
  122. "new String[] { " + inter + " });\n");
  123. _out.println(" _cp = _cg.getConstantPool();");
  124. _out.println(" _factory = new InstructionFactory(_cg, _cp);");
  125. _out.println(" }\n");
  126. printCreate();
  127. Field[] fields = clazz.getFields();
  128. if(fields.length > 0) {
  129. _out.println(" private void createFields() {");
  130. _out.println(" FieldGen field;");
  131. for(int i=0; i < fields.length; i++) {
  132. fields[i].accept(this);
  133. }
  134. _out.println(" }\n");
  135. }
  136. Method[] methods = clazz.getMethods();
  137. for(int i=0; i < methods.length; i++) {
  138. _out.println(" private void createMethod_" + i + "() {");
  139. methods[i].accept(this);
  140. _out.println(" }\n");
  141. }
  142. printMain();
  143. _out.println("}");
  144. }
  145. private void printCreate() {
  146. _out.println(" public void create(OutputStream out) throws IOException {");
  147. Field[] fields = _clazz.getFields();
  148. if(fields.length > 0) {
  149. _out.println(" createFields();");
  150. }
  151. Method[] methods = _clazz.getMethods();
  152. for(int i=0; i < methods.length; i++) {
  153. _out.println(" createMethod_" + i + "();");
  154. }
  155. _out.println(" _cg.getJavaClass().dump(out);");
  156. _out.println(" }\n");
  157. }
  158. private void printMain() {
  159. String class_name = _clazz.getClassName();
  160. _out.println(" public static void main(String[] args) throws Exception {");
  161. _out.println(" " + class_name + "Creator creator = new " +
  162. class_name + "Creator();");
  163. _out.println(" creator.create(new FileOutputStream(\"" + class_name +
  164. ".class\"));");
  165. _out.println(" }");
  166. }
  167. public void visitField(Field field) {
  168. _out.println("\n field = new FieldGen(" +
  169. printFlags(field.getModifiers()) +
  170. ", " + printType(field.getSignature()) + ", \"" +
  171. field.getName() + "\", _cp);");
  172. ConstantValue cv = field.getConstantValue();
  173. if(cv != null) {
  174. String value = cv.toString();
  175. _out.println(" field.setInitValue(" + value + ")");
  176. }
  177. _out.println(" _cg.addField(field.getField());");
  178. }
  179. public void visitMethod(Method method) {
  180. MethodGen mg = new MethodGen(method, _clazz.getClassName(), _cp);
  181. Type result_type = mg.getReturnType();
  182. Type[] arg_types = mg.getArgumentTypes();
  183. _out.println(" InstructionList il = new InstructionList();");
  184. _out.println(" MethodGen method = new MethodGen(" +
  185. printFlags(method.getModifiers()) +
  186. ", " + printType(result_type) +
  187. ", " + printArgumentTypes(arg_types) + ", " +
  188. "new String[] { " +
  189. BCELifier.printArray(mg.getArgumentNames(), false, true) +
  190. " }, \"" + method.getName() + "\", \"" +
  191. _clazz.getClassName() + "\", il, _cp);\n");
  192. BCELFactory factory = new BCELFactory(mg, _out);
  193. factory.start();
  194. _out.println(" method.setMaxStack();");
  195. _out.println(" method.setMaxLocals();");
  196. _out.println(" _cg.addMethod(method.getMethod());");
  197. _out.println(" il.dispose();");
  198. }
  199. public static final String printArray(Object[] obj, boolean braces,
  200. boolean quote) {
  201. if(obj == null)
  202. return null;
  203. StringBuffer buf = new StringBuffer();
  204. if(braces)
  205. buf.append('{');
  206. for(int i=0; i < obj.length; i++) {
  207. if(obj[i] != null) {
  208. buf.append((quote? "\"" : "") + obj[i].toString() + (quote? "\"" : ""));
  209. } else {
  210. buf.append("null");
  211. }
  212. if(i < obj.length - 1) {
  213. buf.append(", ");
  214. }
  215. }
  216. if(braces)
  217. buf.append('}');
  218. return buf.toString();
  219. }
  220. static String printFlags(int flags) {
  221. return printFlags(flags, false);
  222. }
  223. static String printFlags(int flags, boolean for_class) {
  224. if(flags == 0)
  225. return "0";
  226. StringBuffer buf = new StringBuffer();
  227. for(int i=0, pow=1; i <= Constants.MAX_ACC_FLAG; i++) {
  228. if((flags & pow) != 0) {
  229. if((pow == Constants.ACC_SYNCHRONIZED) && for_class)
  230. buf.append("ACC_SUPER | ");
  231. else
  232. buf.append("ACC_" + Constants.ACCESS_NAMES[i].toUpperCase() + " | ");
  233. }
  234. pow <<= 1;
  235. }
  236. String str = buf.toString();
  237. return str.substring(0, str.length() - 3);
  238. }
  239. static String printArgumentTypes(Type[] arg_types) {
  240. if(arg_types.length == 0)
  241. return "Type.NO_ARGS";
  242. StringBuffer args = new StringBuffer();
  243. for(int i=0; i < arg_types.length; i++) {
  244. args.append(printType(arg_types[i]));
  245. if(i < arg_types.length - 1)
  246. args.append(", ");
  247. }
  248. return "new Type[] { " + args.toString() + " }";
  249. }
  250. static String printType(Type type) {
  251. return printType(type.getSignature());
  252. }
  253. static String printType(String signature) {
  254. Type type = Type.getType(signature);
  255. byte t = type.getType();
  256. if(t <= Constants.T_VOID) {
  257. return "Type." + Constants.TYPE_NAMES[t].toUpperCase();
  258. } else if(type.toString().equals("java.lang.String")) {
  259. return "Type.STRING";
  260. } else if(type.toString().equals("java.lang.Object")) {
  261. return "Type.OBJECT";
  262. } else if(type.toString().equals("java.lang.StringBuffer")) {
  263. return "Type.STRINGBUFFER";
  264. } else if(type instanceof ArrayType) {
  265. ArrayType at = (ArrayType)type;
  266. return "new ArrayType(" + printType(at.getBasicType()) +
  267. ", " + at.getDimensions() + ")";
  268. } else {
  269. return "new ObjectType(\"" + Utility.signatureToString(signature, false) +
  270. "\")";
  271. }
  272. }
  273. /** Default main method
  274. */
  275. public static void main(String[] argv) throws Exception {
  276. JavaClass java_class;
  277. String name = argv[0];
  278. if((java_class = Repository.lookupClass(name)) == null)
  279. java_class = new ClassParser(name).parse(); // May throw IOException
  280. BCELifier bcelifier = new BCELifier(java_class, System.out);
  281. bcelifier.start();
  282. }
  283. }