org.apache.bcel.classfile.Utility Java Examples
The following examples show how to use
org.apache.bcel.classfile.Utility.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: MethodGen.java From commons-bcel with Apache License 2.0 | 6 votes |
/** * Return string representation close to declaration format, * `public static void main(String[]) throws IOException', e.g. * * @return String representation of the method. */ @Override public final String toString() { final String access = Utility.accessToString(super.getAccessFlags()); String signature = Type.getMethodSignature(super.getType(), argTypes); signature = Utility.methodSignatureToString(signature, super.getName(), access, true, getLocalVariableTable(super.getConstantPool())); final StringBuilder buf = new StringBuilder(signature); for (final Attribute a : getAttributes()) { if (!((a instanceof Code) || (a instanceof ExceptionTable))) { buf.append(" [").append(a).append("]"); } } if (throwsList.size() > 0) { for (final String throwsDescriptor : throwsList) { buf.append("\n\t\tthrows ").append(throwsDescriptor); } } return buf.toString(); }
Example #2
Source File: MethodHTML.java From commons-bcel with Apache License 2.0 | 6 votes |
/** * Print field of class. * * @param field field to print * @throws java.io.IOException */ private void writeField( final Field field ) throws IOException { final String type = Utility.signatureToString(field.getSignature()); final String name = field.getName(); String access = Utility.accessToString(field.getAccessFlags()); Attribute[] attributes; access = Utility.replace(access, " ", " "); file.print("<TR><TD><FONT COLOR=\"#FF0000\">" + access + "</FONT></TD>\n<TD>" + Class2HTML.referenceType(type) + "</TD><TD><A NAME=\"field" + name + "\">" + name + "</A></TD>"); attributes = field.getAttributes(); // Write them to the Attributes.html file with anchor "<name>[<i>]" for (int i = 0; i < attributes.length; i++) { attribute_html.writeAttribute(attributes[i], name + "@" + i); } for (int i = 0; i < attributes.length; i++) { if (attributes[i].getTag() == Const.ATTR_CONSTANT_VALUE) { // Default value final String str = ((ConstantValue) attributes[i]).toString(); // Reference attribute in _attributes.html file.print("<TD>= <A HREF=\"" + className + "_attributes.html#" + name + "@" + i + "\" TARGET=\"Attributes\">" + str + "</TD>\n"); break; } } file.println("</TR>"); }
Example #3
Source File: ClassLoader.java From commons-bcel with Apache License 2.0 | 6 votes |
/** * Override this method to create you own classes on the fly. The * name contains the special token $$BCEL$$. Everything before that * token is considered to be a package name. You can encode your own * arguments into the subsequent string. You must ensure however not * to use any "illegal" characters, i.e., characters that may not * appear in a Java class name too * <p> * The default implementation interprets the string as a encoded compressed * Java class, unpacks and decodes it with the Utility.decode() method, and * parses the resulting byte array and returns the resulting JavaClass object. * </p> * * @param class_name compressed byte code with "$$BCEL$$" in it */ protected JavaClass createClass( final String class_name ) { final int index = class_name.indexOf(BCEL_TOKEN); final String real_name = class_name.substring(index + BCEL_TOKEN.length()); JavaClass clazz = null; try { final byte[] bytes = Utility.decode(real_name, true); final ClassParser parser = new ClassParser(new ByteArrayInputStream(bytes), "foo"); clazz = parser.parse(); } catch (final IOException e) { e.printStackTrace(); return null; } // Adapt the class name to the passed value final ConstantPool cp = clazz.getConstantPool(); final ConstantClass cl = (ConstantClass) cp.getConstant(clazz.getClassNameIndex(), Const.CONSTANT_Class); final ConstantUtf8 name = (ConstantUtf8) cp.getConstant(cl.getNameIndex(), Const.CONSTANT_Utf8); name.setBytes(class_name.replace('.', '/')); return clazz; }
Example #4
Source File: Type.java From commons-bcel with Apache License 2.0 | 6 votes |
static int getTypeSize( final String signature ) throws StringIndexOutOfBoundsException { final byte type = Utility.typeOfSignature(signature); if (type <= Const.T_VOID) { return encode(BasicType.getType(type).getSize(), 1); } else if (type == Const.T_ARRAY) { int dim = 0; do { // Count dimensions dim++; } while (signature.charAt(dim) == '['); // Recurse, but just once, if the signature is ok final int consumed = consumed(getTypeSize(signature.substring(dim))); return encode(1, dim + consumed); } else { // type == T_REFERENCE final int index = signature.indexOf(';'); // Look for closing `;' if (index < 0) { throw new ClassFormatException("Invalid signature: " + signature); } return encode(1, index + 1); } }
Example #5
Source File: BCELFactory.java From commons-bcel with Apache License 2.0 | 6 votes |
private void createConstant( final Object value ) { String embed = value.toString(); if (value instanceof String) { embed = '"' + Utility.convertString(embed) + '"'; } else if (value instanceof Character) { embed = "(char)0x" + Integer.toHexString(((Character) value).charValue()); } else if (value instanceof Float) { embed += "f"; } else if (value instanceof Long) { embed += "L"; } else if (value instanceof ObjectType) { final ObjectType ot = (ObjectType) value; embed = "new ObjectType(\""+ot.getClassName()+"\")"; } _out.println("il.append(new PUSH(_cp, " + embed + "));"); }
Example #6
Source File: FieldGen.java From commons-bcel with Apache License 2.0 | 6 votes |
/** * Return string representation close to declaration format, * `public static final short MAX = 100', e.g.. * * @return String representation of field */ @Override public final String toString() { String name; String signature; String access; // Short cuts to constant pool access = Utility.accessToString(super.getAccessFlags()); access = access.isEmpty() ? "" : (access + " "); signature = super.getType().toString(); name = getName(); final StringBuilder buf = new StringBuilder(32); // CHECKSTYLE IGNORE MagicNumber buf.append(access).append(signature).append(" ").append(name); final String value = getInitValue(); if (value != null) { buf.append(" = ").append(value); } return buf.toString(); }
Example #7
Source File: JasminVisitor.java From commons-bcel with Apache License 2.0 | 6 votes |
@Override public void visitJavaClass(final JavaClass clazz) { out.println(";; Produced by JasminVisitor (BCEL)"); out.println(";; https://commons.apache.org/bcel/"); out.println(";; " + new Date() + "\n"); out.println(".source " + clazz.getSourceFileName()); out.println("." + Utility.classOrInterface(clazz.getAccessFlags()) + " " + Utility.accessToString(clazz.getAccessFlags(), true) + " " + clazz.getClassName().replace('.', '/')); out.println(".super " + clazz.getSuperclassName().replace('.', '/')); for (final String iface : clazz.getInterfaceNames()) { out.println(".implements " + iface.replace('.', '/')); } out.print("\n"); }
Example #8
Source File: BCELifier.java From commons-bcel with Apache License 2.0 | 6 votes |
@Override public void visitMethod( final Method method ) { final MethodGen mg = new MethodGen(method, _clazz.getClassName(), _cp); _out.println(" InstructionList il = new InstructionList();"); _out.println(" MethodGen method = new MethodGen(" + printFlags(method.getAccessFlags(), FLAGS.METHOD) + ", " + printType(mg.getReturnType()) + ", " + printArgumentTypes(mg.getArgumentTypes()) + ", " + "new String[] { " + Utility.printArray(mg.getArgumentNames(), false, true) + " }, \"" + method.getName() + "\", \"" + _clazz.getClassName() + "\", il, _cp);"); _out.println(); final BCELFactory factory = new BCELFactory(mg, _out); factory.start(); _out.println(" method.setMaxStack();"); _out.println(" method.setMaxLocals();"); _out.println(" _cg.addMethod(method.getMethod());"); _out.println(" il.dispose();"); }
Example #9
Source File: BCELifier.java From commons-bcel with Apache License 2.0 | 6 votes |
static String printType( final String signature ) { final Type type = Type.getType(signature); final byte t = type.getType(); if (t <= Const.T_VOID) { return "Type." + Const.getTypeName(t).toUpperCase(Locale.ENGLISH); } else if (type.toString().equals("java.lang.String")) { return "Type.STRING"; } else if (type.toString().equals("java.lang.Object")) { return "Type.OBJECT"; } else if (type.toString().equals("java.lang.StringBuffer")) { return "Type.STRINGBUFFER"; } else if (type instanceof ArrayType) { final ArrayType at = (ArrayType) type; return "new ArrayType(" + printType(at.getBasicType()) + ", " + at.getDimensions() + ")"; } else { return "new ObjectType(\"" + Utility.signatureToString(signature, false) + "\")"; } }
Example #10
Source File: JasminVisitor.java From commons-bcel with Apache License 2.0 | 5 votes |
@Override public void visitMethod(final Method method) { this._method = method; // Remember for use in subsequent visitXXX calls out.println("\n.method " + Utility.accessToString(_method.getAccessFlags()) + " " + _method.getName() + _method.getSignature()); final Attribute[] attributes = _method.getAttributes(); if ((attributes == null) || (attributes.length == 0)) { out.println(".end method"); } }
Example #11
Source File: JasminVisitor.java From commons-bcel with Apache License 2.0 | 5 votes |
@Override public void visitField(final Field field) { out.print(".field " + Utility.accessToString(field.getAccessFlags()) + " \"" + field.getName() + "\"" + field.getSignature()); if (field.getAttributes().length == 0) { out.print("\n"); } }
Example #12
Source File: MethodSymbol.java From cloud-opensource-java with Apache License 2.0 | 5 votes |
@Override public String toString() { // https://docs.oracle.com/javase/specs/jls/se8/html/jls-8.html#jls-8.4.2 String signaturePlusReturnType = Utility.methodSignatureToString(descriptor, name, ""); String signature = signaturePlusReturnType.substring(signaturePlusReturnType.indexOf(' ') + 1); return (isInterfaceMethod ? "Interface " : "") + getClassBinaryName() + "'s method " + signature; }
Example #13
Source File: Type.java From commons-bcel with Apache License 2.0 | 5 votes |
/** * Convert signature to a Type object. * @param signature signature string such as Ljava/lang/String; * @return type object */ // @since 6.0 no longer final public static Type getType( final String signature ) throws StringIndexOutOfBoundsException { final byte type = Utility.typeOfSignature(signature); if (type <= Const.T_VOID) { //corrected concurrent private static field acess wrap(consumed_chars, 1); return BasicType.getType(type); } else if (type == Const.T_ARRAY) { int dim = 0; do { // Count dimensions dim++; } while (signature.charAt(dim) == '['); // Recurse, but just once, if the signature is ok final Type t = getType(signature.substring(dim)); //corrected concurrent private static field acess // consumed_chars += dim; // update counter - is replaced by final int _temp = unwrap(consumed_chars) + dim; wrap(consumed_chars, _temp); return new ArrayType(t, dim); } else { // type == T_REFERENCE // Utility.typeSignatureToString understands how to parse generic types. final String parsedSignature = Utility.typeSignatureToString(signature, false); wrap(consumed_chars, parsedSignature.length() + 2); // "Lblabla;" `L' and `;' are removed return ObjectType.getInstance(parsedSignature.replace('/', '.')); } }
Example #14
Source File: Class2HTML.java From commons-bcel with Apache License 2.0 | 5 votes |
/** * Utility method that converts a class reference in the constant pool, * i.e., an index to a string. */ static String referenceClass( final int index ) { String str = constant_pool.getConstantString(index, Const.CONSTANT_Class); str = Utility.compactClassName(str); str = Utility.compactClassName(str, class_package + ".", true); return "<A HREF=\"" + class_name + "_cp.html#cp" + index + "\" TARGET=ConstantPool>" + str + "</A>"; }
Example #15
Source File: Class2HTML.java From commons-bcel with Apache License 2.0 | 5 votes |
static String referenceType( final String type ) { String short_type = Utility.compactClassName(type); short_type = Utility.compactClassName(short_type, class_package + ".", true); final int index = type.indexOf('['); // Type is an array? String base_type = type; if (index > -1) { base_type = type.substring(0, index); // Tack of the `[' } // test for basic type if (basic_types.contains(base_type)) { return "<FONT COLOR=\"#00FF00\">" + type + "</FONT>"; } return "<A HREF=\"" + base_type + ".html\" TARGET=_top>" + short_type + "</A>"; }
Example #16
Source File: BCELFactory.java From ApkToolPlus with Apache License 2.0 | 5 votes |
private void createConstant(Object value) { String embed = value.toString(); if(value instanceof String) embed = '"' + Utility.convertString(value.toString()) + '"'; else if(value instanceof Character) embed = "(char)0x" + Integer.toHexString(((Character)value).charValue()); _out.println("il.append(new PUSH(_cp, " + embed + "));"); }
Example #17
Source File: BCELifier.java From commons-bcel with Apache License 2.0 | 4 votes |
@Override public void visitJavaClass( final JavaClass clazz ) { String class_name = clazz.getClassName(); final String super_name = clazz.getSuperclassName(); final String package_name = clazz.getPackageName(); final String inter = Utility.printArray(clazz.getInterfaceNames(), false, true); if (!"".equals(package_name)) { class_name = class_name.substring(package_name.length() + 1); _out.println("package " + package_name + ";"); _out.println(); } _out.println("import " + BASE_PACKAGE + ".generic.*;"); _out.println("import " + BASE_PACKAGE + ".classfile.*;"); _out.println("import " + BASE_PACKAGE + ".*;"); _out.println("import java.io.*;"); _out.println(); _out.println("public class " + class_name + "Creator {"); _out.println(" private InstructionFactory _factory;"); _out.println(" private ConstantPoolGen _cp;"); _out.println(" private ClassGen _cg;"); _out.println(); _out.println(" public " + class_name + "Creator() {"); _out.println(" _cg = new ClassGen(\"" + (("".equals(package_name)) ? class_name : package_name + "." + class_name) + "\", \"" + super_name + "\", " + "\"" + clazz.getSourceFileName() + "\", " + printFlags(clazz.getAccessFlags(), FLAGS.CLASS) + ", " + "new String[] { " + inter + " });"); _out.println(" _cg.setMajor(" + clazz.getMajor() +");"); _out.println(" _cg.setMinor(" + clazz.getMinor() +");"); _out.println(); _out.println(" _cp = _cg.getConstantPool();"); _out.println(" _factory = new InstructionFactory(_cg, _cp);"); _out.println(" }"); _out.println(); printCreate(); final Field[] fields = clazz.getFields(); if (fields.length > 0) { _out.println(" private void createFields() {"); _out.println(" FieldGen field;"); for (final Field field : fields) { field.accept(this); } _out.println(" }"); _out.println(); } final Method[] methods = clazz.getMethods(); for (int i = 0; i < methods.length; i++) { _out.println(" private void createMethod_" + i + "() {"); methods[i].accept(this); _out.println(" }"); _out.println(); } printMain(); _out.println("}"); }
Example #18
Source File: Type.java From commons-bcel with Apache License 2.0 | 4 votes |
/** * @return Type string, e.g. `int[]' */ @Override public String toString() { return ((this.equals(Type.NULL) || (type >= Const.T_UNKNOWN))) ? signature : Utility .signatureToString(signature, false); }
Example #19
Source File: MethodHTML.java From commons-bcel with Apache License 2.0 | 4 votes |
private void writeMethod( final Method method, final int method_number ) { // Get raw signature final String signature = method.getSignature(); // Get array of strings containing the argument types final String[] args = Utility.methodSignatureArgumentTypes(signature, false); // Get return type string final String type = Utility.methodSignatureReturnType(signature, false); // Get method name final String name = method.getName(); String html_name; // Get method's access flags String access = Utility.accessToString(method.getAccessFlags()); // Get the method's attributes, the Code Attribute in particular final Attribute[] attributes = method.getAttributes(); /* HTML doesn't like names like <clinit> and spaces are places to break * lines. Both we don't want... */ access = Utility.replace(access, " ", " "); html_name = Class2HTML.toHTML(name); file.print("<TR VALIGN=TOP><TD><FONT COLOR=\"#FF0000\"><A NAME=method" + method_number + ">" + access + "</A></FONT></TD>"); file.print("<TD>" + Class2HTML.referenceType(type) + "</TD><TD>" + "<A HREF=" + className + "_code.html#method" + method_number + " TARGET=Code>" + html_name + "</A></TD>\n<TD>("); for (int i = 0; i < args.length; i++) { file.print(Class2HTML.referenceType(args[i])); if (i < args.length - 1) { file.print(", "); } } file.print(")</TD></TR>"); // Check for thrown exceptions for (int i = 0; i < attributes.length; i++) { attribute_html.writeAttribute(attributes[i], "method" + method_number + "@" + i, method_number); final byte tag = attributes[i].getTag(); if (tag == Const.ATTR_EXCEPTIONS) { file.print("<TR VALIGN=TOP><TD COLSPAN=2></TD><TH ALIGN=LEFT>throws</TH><TD>"); final int[] exceptions = ((ExceptionTable) attributes[i]).getExceptionIndexTable(); for (int j = 0; j < exceptions.length; j++) { file.print(constantHtml.referenceConstant(exceptions[j])); if (j < exceptions.length - 1) { file.print(", "); } } file.println("</TD></TR>"); } else if (tag == Const.ATTR_CODE) { final Attribute[] c_a = ((Code) attributes[i]).getAttributes(); for (int j = 0; j < c_a.length; j++) { attribute_html.writeAttribute(c_a[j], "method" + method_number + "@" + i + "@" + j, method_number); } } } }
Example #20
Source File: InstructionHandle.java From commons-bcel with Apache License 2.0 | 4 votes |
/** @return a (verbose) string representation of the contained instruction. */ public String toString( final boolean verbose ) { return Utility.format(i_position, 4, false, ' ') + ": " + instruction.toString(verbose); }
Example #21
Source File: ProxyCreator.java From commons-bcel with Apache License 2.0 | 4 votes |
/** * Create JavaClass object for a simple proxy for an java.awt.event.ActionListener * that just prints the passed arguments, load and use it via the class loader * mechanism. */ public static void main(final String[] argv) throws Exception { final ClassLoader loader = ProxyCreator.class.getClassLoader(); // instanceof won't work here ... // TODO this is broken; cannot ever be true now that ClassLoader has been dropped if (loader.getClass().toString().equals("class org.apache.bcel.util.ClassLoader")) { // Real class name will be set by the class loader final ClassGen cg = new ClassGen("foo", "java.lang.Object", "", Constants.ACC_PUBLIC, new String[]{"java.awt.event.ActionListener"}); // That's important, otherwise newInstance() won't work cg.addEmptyConstructor(Constants.ACC_PUBLIC); final InstructionList il = new InstructionList(); final ConstantPoolGen cp = cg.getConstantPool(); final InstructionFactory factory = new InstructionFactory(cg); final int out = cp.addFieldref("java.lang.System", "out", "Ljava/io/PrintStream;"); final int println = cp.addMethodref("java.io.PrintStream", "println", "(Ljava/lang/Object;)V"); final MethodGen mg = new MethodGen(Constants.ACC_PUBLIC, Type.VOID, new Type[]{ new ObjectType("java.awt.event.ActionEvent") }, null, "actionPerformed", "foo", il, cp); // System.out.println("actionPerformed:" + event); il.append(new GETSTATIC(out)); il.append(factory.createNew("java.lang.StringBuffer")); il.append(InstructionConstants.DUP); il.append(new PUSH(cp, "actionPerformed:")); il.append(factory.createInvoke("java.lang.StringBuffer", "<init>", Type.VOID, new Type[]{Type.STRING}, Constants.INVOKESPECIAL)); il.append(new ALOAD(1)); il.append(factory.createAppend(Type.OBJECT)); il.append(new INVOKEVIRTUAL(println)); il.append(InstructionConstants.RETURN); mg.stripAttributes(true); mg.setMaxStack(); mg.setMaxLocals(); cg.addMethod(mg.getMethod()); final byte[] bytes = cg.getJavaClass().getBytes(); System.out.println("Uncompressed class: " + bytes.length); final String s = Utility.encode(bytes, true); System.out.println("Encoded class: " + s.length()); System.out.print("Creating proxy ... "); final ActionListener a = (ActionListener) createProxy("foo.bar.", s); System.out.println("Done. Now calling actionPerformed()"); a.actionPerformed(new ActionEvent(a, ActionEvent.ACTION_PERFORMED, "hello")); } else { System.err.println("Call me with java org.apache.bcel.util.JavaWrapper ProxyCreator"); } }
Example #22
Source File: helloify.java From commons-bcel with Apache License 2.0 | 4 votes |
/** * Patch a method. */ private static Method helloifyMethod(Method m) { final Code code = m.getCode(); final int flags = m.getAccessFlags(); final String name = m.getName(); // Sanity check if (m.isNative() || m.isAbstract() || (code == null)) { return m; } // Create instruction list to be inserted at method start. final String mesg = "Hello from " + Utility.methodSignatureToString(m.getSignature(), name, Utility.accessToString(flags)); final InstructionList patch = new InstructionList(); patch.append(new GETSTATIC(out)); patch.append(new PUSH(cp, mesg)); patch.append(new INVOKEVIRTUAL(println)); final MethodGen mg = new MethodGen(m, class_name, cp); final InstructionList il = mg.getInstructionList(); final InstructionHandle[] ihs = il.getInstructionHandles(); if (name.equals("<init>")) { // First let the super or other constructor be called for (int j = 1; j < ihs.length; j++) { if (ihs[j].getInstruction() instanceof INVOKESPECIAL) { il.append(ihs[j], patch); // Should check: method name == "<init>" break; } } } else { il.insert(ihs[0], patch); } // Stack size must be at least 2, since the println method takes 2 argument. if (code.getMaxStack() < 2) { mg.setMaxStack(2); } m = mg.getMethod(); il.dispose(); // Reuse instruction handles return m; }
Example #23
Source File: InstructionHandle.java From ApkToolPlus with Apache License 2.0 | 4 votes |
/** @return a (verbose) string representation of the contained instruction. */ public String toString(boolean verbose) { return Utility.format(i_position, 4, false, ' ') + ": " + instruction.toString(verbose); }