Java Code Examples for org.apache.bcel.classfile.JavaClass#dump()

The following examples show how to use org.apache.bcel.classfile.JavaClass#dump() . 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: helloify.java    From commons-bcel with Apache License 2.0 6 votes vote down vote up
public static void main(final String[] argv) throws Exception {
    for (final String arg : argv) {
        if (arg.endsWith(".class")) {
            final JavaClass java_class = new ClassParser(arg).parse();
            final ConstantPool constants = java_class.getConstantPool();
            final String file_name = arg.substring(0, arg.length() - 6) + "_hello.class";
            cp = new ConstantPoolGen(constants);

            helloifyClassName(java_class);

            out = cp.addFieldref("java.lang.System", "out", "Ljava/io/PrintStream;");
            println = cp.addMethodref("java.io.PrintStream", "println", "(Ljava/lang/String;)V");
            // Patch all methods.
            final Method[] methods = java_class.getMethods();

            for (int j = 0; j < methods.length; j++) {
                methods[j] = helloifyMethod(methods[j]);
            }

            // Finally dump it back to a file.
            java_class.setConstantPool(cp.getFinalConstantPool());
            java_class.dump(file_name);
        }
    }
}
 
Example 2
Source File: Peephole.java    From commons-bcel with Apache License 2.0 6 votes vote down vote up
public static void main(final String[] argv) {
    try {
        // Load the class from CLASSPATH.
        final JavaClass clazz = Repository.lookupClass(argv[0]);
        final Method[] methods = clazz.getMethods();
        final ConstantPoolGen cp = new ConstantPoolGen(clazz.getConstantPool());

        for (int i = 0; i < methods.length; i++) {
            if (!(methods[i].isAbstract() || methods[i].isNative())) {
                final MethodGen mg = new MethodGen(methods[i], clazz.getClassName(), cp);
                final Method stripped = removeNOPs(mg);

                if (stripped != null) {
                    methods[i] = stripped; // Overwrite with stripped method
                }
            }
        }

        // Dump the class to <class name>_.class
        clazz.setConstantPool(cp.getFinalConstantPool());
        clazz.dump(clazz.getClassName() + "_.class");
    } catch (final Exception e) {
        e.printStackTrace();
    }
}
 
Example 3
Source File: patchclass.java    From commons-bcel with Apache License 2.0 6 votes vote down vote up
public static void main(final String[] argv) throws Exception {
    final String[] file_name = new String[argv.length];
    int files = 0;

    if (argv.length < 3) {
        System.err.println("Usage: patch <oldstring> <newstring> file1.class ...");
        System.exit(-1);
    }

    for (int i = 2; i < argv.length; i++) {
        file_name[files++] = argv[i];
    }

    for (int i = 0; i < files; i++) {
        final ClassParser parser = new ClassParser(file_name[i]);
        final JavaClass java_class = parser.parse();

        patchIt(argv[0], argv[1], java_class.getConstantPool().getConstantPool());

        // Dump the changed class to a new file
        java_class.dump("_" + file_name[i]);
        System.out.println("Results saved in: _" + file_name[i]);
    }
}
 
Example 4
Source File: FieldAnnotationsTestCase.java    From commons-bcel with Apache License 2.0 6 votes vote down vote up
/**
 * Check field AnnotationEntrys (de)serialize ok.
 */
public void testFieldAnnotationEntrysReadWrite() throws ClassNotFoundException,
        IOException
{
    final JavaClass clazz = getTestClass(PACKAGE_BASE_NAME+".data.AnnotatedFields");
    checkAnnotatedField(clazz, "i", "L"+PACKAGE_BASE_SIG+"/data/SimpleAnnotation;", "id", "1");
    checkAnnotatedField(clazz, "s", "L"+PACKAGE_BASE_SIG+"/data/SimpleAnnotation;", "id", "2");
    // Write it out
    final File tfile = createTestdataFile("AnnotatedFields.class");
    clazz.dump(tfile);
    final SyntheticRepository repos2 = createRepos(".");
    repos2.loadClass("AnnotatedFields");
    checkAnnotatedField(clazz, "i", "L"+PACKAGE_BASE_SIG+"/data/SimpleAnnotation;", "id", "1");
    checkAnnotatedField(clazz, "s", "L"+PACKAGE_BASE_SIG+"/data/SimpleAnnotation;", "id", "2");
    assertTrue(tfile.delete());
}
 
Example 5
Source File: Encoder.java    From javasdk with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * get hvm invoke payload.
 *
 * @param bean invoke bean
 * @return payload
 */
public static String encodeInvokeBeanJava(BaseInvoke bean) {
    try {
        //1. get the bean class bytes
        ClassLoaderRepository repository = new ClassLoaderRepository(Thread.currentThread().getContextClassLoader());
        JavaClass beanClass = repository.loadClass(bean.getClass());
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        beanClass.dump(baos);
        byte[] clazz = baos.toByteArray();
        if (clazz.length > 0xffff) {
            throw new IOException("the bean class is too large"); // 64k
        }
        //2. get the bean class name
        byte[] clzName = bean.getClass().getCanonicalName().getBytes(Utils.DEFAULT_CHARSET);
        if (clzName.length > 0xffff) {
            throw new IOException("the bean class name is too large"); // 64k
        }
        //3. get the bin of bean
        Gson gson = new Gson();
        byte[] beanBin = gson.toJson(bean).getBytes(Utils.DEFAULT_CHARSET);
        //4. accumulate: | class length(4B) | name length(2B) | class | class name | bin |
        //               | len(txHash)      | len("__txHash__")| txHash | "__txHash__" | bin |
        StringBuilder sb = new StringBuilder();
        sb.append(ByteUtil.toHex(ByteUtil.intToByteArray(clazz.length)));
        sb.append(ByteUtil.toHex(ByteUtil.shortToBytes((short) clzName.length)));

        sb.append(ByteUtil.toHex(clazz));
        sb.append(ByteUtil.toHex(clzName));
        sb.append(ByteUtil.toHex(beanBin));
        return sb.toString();
    } catch (ClassNotFoundException | IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example 6
Source File: ParserTest.java    From JQF with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Fuzz
public void testWithGenerator(@From(JavaClassGenerator.class) JavaClass javaClass) throws IOException {

    try {
        // Dump the javaclass to a byte stream and get an input pipe
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        javaClass.dump(out);

        ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
        testWithInputStream(in);
    } catch (ClassFormatException e) {
        throw e;
    }
}
 
Example 7
Source File: LDAPSSLSocketFactoryGenerator.java    From qpid-broker-j with Apache License 2.0 5 votes vote down vote up
/**
 * Creates the LDAPSocketFactoryImpl class (subclass of {@link AbstractLDAPSSLSocketFactory}.
 * A static method #getDefaulta, a static field _sslContent and no-arg constructor are added
 * to the class.
 *
 * @param className
 *
 * @return byte code
 */
private static byte[] createSubClassByteCode(final String className)
{
    ClassGen classGen = new ClassGen(className,
            AbstractLDAPSSLSocketFactory.class.getName(),
            "<generated>",
            ACC_PUBLIC | ACC_SUPER,
            null);
    ConstantPoolGen constantPoolGen = classGen.getConstantPool();
    InstructionFactory factory = new InstructionFactory(classGen);

    createSslContextStaticField(classGen, constantPoolGen);
    createGetDefaultStaticMethod(classGen, constantPoolGen, factory);

    classGen.addEmptyConstructor(ACC_PROTECTED);

    JavaClass javaClass = classGen.getJavaClass();
    ByteArrayOutputStream out = null;
    try
    {
        out = new ByteArrayOutputStream();
        javaClass.dump(out);
        return out.toByteArray();
    }
    catch (IOException ioex)
    {
        throw new IllegalStateException("Could not write to a ByteArrayOutputStream - should not happen", ioex);
    }
    finally
    {
        closeSafely(out);
    }
}
 
Example 8
Source File: EnclosingMethodAttributeTestCase.java    From commons-bcel with Apache License 2.0 5 votes vote down vote up
/**
 * Check that we can save and load the attribute correctly.
 */
public void testAttributeSerializtion() throws ClassNotFoundException,
        IOException
{
    final JavaClass clazz = getTestClass(PACKAGE_BASE_NAME+".data.AttributeTestClassEM02$1");
    final ConstantPool pool = clazz.getConstantPool();
    final Attribute[] encMethodAttrs = findAttribute("EnclosingMethod", clazz);
    assertTrue("Expected 1 EnclosingMethod attribute but found "
            + encMethodAttrs.length, encMethodAttrs.length == 1);
    // Write it out
    final File tfile = createTestdataFile("AttributeTestClassEM02$1.class");
    clazz.dump(tfile);
    // Read in the new version and check it is OK
    final SyntheticRepository repos2 = createRepos(".");
    final JavaClass clazz2 = repos2.loadClass("AttributeTestClassEM02$1");
    Assert.assertNotNull(clazz2); // Use the variable to avoid a warning
    final EnclosingMethod em = (EnclosingMethod) encMethodAttrs[0];
    final String enclosingClassName = em.getEnclosingClass().getBytes(pool);
    assertTrue(
            "The class is not within a method, so method_index should be null, but it is "
                    + em.getEnclosingMethodIndex(), em
                    .getEnclosingMethodIndex() == 0);
    assertTrue(
            "Expected class name to be '"+PACKAGE_BASE_SIG+"/data/AttributeTestClassEM02' but was "
                    + enclosingClassName, enclosingClassName
                    .equals(PACKAGE_BASE_SIG+"/data/AttributeTestClassEM02"));
    tfile.deleteOnExit();
}