Search in sources :

Example 1 with ClassVisitor

use of org.objectweb.asm.ClassVisitor in project storm by apache.

the class DefaultShader method addRemappedClass.

private void addRemappedClass(RelocatorRemapper remapper, JarOutputStream jos, String name, InputStream is) throws IOException {
    LOG.debug("Remapping class... " + name);
    if (!remapper.hasRelocators()) {
        try {
            LOG.debug("Just copy class...");
            jos.putNextEntry(new JarEntry(name));
            IOUtil.copy(is, jos);
        } catch (ZipException e) {
            LOG.info("zip exception ", e);
        }
        return;
    }
    ClassReader cr = new ClassReader(is);
    // We don't pass the ClassReader here. This forces the ClassWriter to rebuild the constant pool.
    // Copying the original constant pool should be avoided because it would keep references
    // to the original class names. This is not a problem at runtime (because these entries in the
    // constant pool are never used), but confuses some tools such as Felix' maven-bundle-plugin
    // that use the constant pool to determine the dependencies of a class.
    ClassWriter cw = new ClassWriter(0);
    final String pkg = name.substring(0, name.lastIndexOf('/') + 1);
    ClassVisitor cv = new RemappingClassAdapter(cw, remapper) {

        @Override
        public void visitSource(final String source, final String debug) {
            LOG.debug("visitSource " + source);
            if (source == null) {
                super.visitSource(source, debug);
            } else {
                final String fqSource = pkg + source;
                final String mappedSource = remapper.map(fqSource);
                final String filename = mappedSource.substring(mappedSource.lastIndexOf('/') + 1);
                LOG.debug("Remapped to " + filename);
                super.visitSource(filename, debug);
            }
        }
    };
    try {
        cr.accept(cv, ClassReader.EXPAND_FRAMES);
    } catch (Throwable ise) {
        throw new IOException("Error in ASM processing class " + name, ise);
    }
    byte[] renamedClass = cw.toByteArray();
    // Need to take the .class off for remapping evaluation
    String mappedName = remapper.map(name.substring(0, name.indexOf('.')));
    LOG.debug("Remapped class name to " + mappedName);
    try {
        // Now we put it back on so the class file is written out with the right extension.
        jos.putNextEntry(new JarEntry(mappedName + ".class"));
        jos.write(renamedClass);
    } catch (ZipException e) {
        LOG.info("zip exception ", e);
    }
}
Also used : RemappingClassAdapter(org.objectweb.asm.commons.RemappingClassAdapter) ClassReader(org.objectweb.asm.ClassReader) ZipException(java.util.zip.ZipException) ClassVisitor(org.objectweb.asm.ClassVisitor) JarEntry(java.util.jar.JarEntry) ClassWriter(org.objectweb.asm.ClassWriter)

Example 2 with ClassVisitor

use of org.objectweb.asm.ClassVisitor in project cglib by cglib.

the class DebuggingClassWriter method toByteArray.

public byte[] toByteArray() {
    return (byte[]) java.security.AccessController.doPrivileged(new java.security.PrivilegedAction() {

        public Object run() {
            byte[] b = ((ClassWriter) DebuggingClassWriter.super.cv).toByteArray();
            if (debugLocation != null) {
                String dirs = className.replace('.', File.separatorChar);
                try {
                    new File(debugLocation + File.separatorChar + dirs).getParentFile().mkdirs();
                    File file = new File(new File(debugLocation), dirs + ".class");
                    OutputStream out = new BufferedOutputStream(new FileOutputStream(file));
                    try {
                        out.write(b);
                    } finally {
                        out.close();
                    }
                    if (traceCtor != null) {
                        file = new File(new File(debugLocation), dirs + ".asm");
                        out = new BufferedOutputStream(new FileOutputStream(file));
                        try {
                            ClassReader cr = new ClassReader(b);
                            PrintWriter pw = new PrintWriter(new OutputStreamWriter(out));
                            ClassVisitor tcv = (ClassVisitor) traceCtor.newInstance(new Object[] { null, pw });
                            cr.accept(tcv, 0);
                            pw.flush();
                        } finally {
                            out.close();
                        }
                    }
                } catch (Exception e) {
                    throw new CodeGenerationException(e);
                }
            }
            return b;
        }
    });
}
Also used : ClassVisitor(org.objectweb.asm.ClassVisitor) ClassWriter(org.objectweb.asm.ClassWriter) ClassReader(org.objectweb.asm.ClassReader)

Example 3 with ClassVisitor

use of org.objectweb.asm.ClassVisitor in project pinpoint by naver.

the class JavassistVerifyErrorTest method asm_stackmapframe_check.

@Test
public void asm_stackmapframe_check() throws Exception {
    CustomURLClassLoader classLoader = new CustomURLClassLoader(new URL[] {}, Thread.currentThread().getContextClassLoader());
    final InputStream stream = classLoader.getResourceAsStream(JavaAssistUtils.javaNameToJvmName(INVALID_STACK_MAP_FRAME) + ".class");
    ClassReader cr = new ClassReader(stream);
    ClassWriter cw = new ClassWriter(cr, ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES);
    ClassVisitor cv = new BytecodeVerifyTestClassVisitor(cw);
    cr.accept(cv, ClassReader.EXPAND_FRAMES | ClassReader.SKIP_DEBUG);
    byte[] bytecode = cw.toByteArray();
    classLoader.defineClass0(INVALID_STACK_MAP_FRAME, bytecode);
    final Class<?> aClass = Class.forName(INVALID_STACK_MAP_FRAME, true, classLoader);
    Assert.assertSame(aClass.getClassLoader(), classLoader);
    final ASMBytecodeDisassembler bytecodeDisassembler = new ASMBytecodeDisassembler();
    final String dumpBytecode = bytecodeDisassembler.dumpBytecode(bytecode);
    logger.debug("dumpBytecode:{}", dumpBytecode);
    final String verify = bytecodeDisassembler.dumpVerify(bytecode, classLoader);
    logger.debug("dumpVerify:{}", verify);
//        final String dumpAsm = bytecodeDisassembler.dumpASM(bytecode);
//        logger.debug("dumpAsm :{}", dumpAsm);
}
Also used : BytecodeVerifyTestClassVisitor(bug_regression_jdk7.javassist.asm.BytecodeVerifyTestClassVisitor) InputStream(java.io.InputStream) ASMBytecodeDisassembler(com.navercorp.pinpoint.profiler.instrument.ASMBytecodeDisassembler) ClassReader(org.objectweb.asm.ClassReader) BytecodeVerifyTestClassVisitor(bug_regression_jdk7.javassist.asm.BytecodeVerifyTestClassVisitor) ClassVisitor(org.objectweb.asm.ClassVisitor) ClassWriter(org.objectweb.asm.ClassWriter) Test(org.junit.Test)

Example 4 with ClassVisitor

use of org.objectweb.asm.ClassVisitor in project android_frameworks_base by ResurrectionRemix.

the class AsmGenerator method transform.

/**
     * Transforms a class.
     * <p/>
     * There are 3 kind of transformations:
     *
     * 1- For "mock" dependencies classes, we want to remove all code from methods and replace
     * by a stub. Native methods must be implemented with this stub too. Abstract methods are
     * left intact. Modified classes must be overridable (non-private, non-final).
     * Native methods must be made non-final, non-private.
     *
     * 2- For "keep" classes, we want to rewrite all native methods as indicated above.
     * If a class has native methods, it must also be made non-private, non-final.
     *
     * Note that unfortunately static methods cannot be changed to non-static (since static and
     * non-static are invoked differently.)
     */
byte[] transform(ClassReader cr, boolean stubNativesOnly) {
    boolean hasNativeMethods = hasNativeMethods(cr);
    // Get the class name, as an internal name (e.g. com/android/SomeClass$InnerClass)
    String className = cr.getClassName();
    String newName = transformName(className);
    // transformName returns its input argument if there's no need to rename the class
    if (!newName.equals(className)) {
        mRenameCount++;
        // This class is being renamed, so remove it from the list of classes not renamed.
        mClassesNotRenamed.remove(className);
    }
    mLog.debug("Transform %s%s%s%s", className, newName.equals(className) ? "" : " (renamed to " + newName + ")", hasNativeMethods ? " -- has natives" : "", stubNativesOnly ? " -- stub natives only" : "");
    // Rewrite the new class from scratch, without reusing the constant pool from the
    // original class reader.
    ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS);
    ClassVisitor cv = cw;
    // FIXME Generify
    if ("android/content/res/Resources".equals(className)) {
        cv = new FieldInjectorAdapter(cv);
    }
    if (mReplaceMethodCallsClasses.contains(className)) {
        cv = new ReplaceMethodCallsAdapter(cv, className);
    }
    cv = new RefactorClassAdapter(cv, mRefactorClasses);
    if (!newName.equals(className)) {
        cv = new RenameClassAdapter(cv, className, newName);
    }
    String binaryNewName = newName.replace('/', '.');
    if (mInjectedMethodsMap.keySet().contains(binaryNewName)) {
        cv = new InjectMethodsAdapter(cv, mInjectedMethodsMap.get(binaryNewName));
    }
    cv = new TransformClassAdapter(mLog, mStubMethods, mDeleteReturns.get(className), newName, cv, stubNativesOnly);
    Set<String> delegateMethods = mDelegateMethods.get(className);
    if (delegateMethods != null && !delegateMethods.isEmpty()) {
        // known to have no native methods, just skip this step.
        if (hasNativeMethods || !(delegateMethods.size() == 1 && delegateMethods.contains(DelegateClassAdapter.ALL_NATIVES))) {
            cv = new DelegateClassAdapter(mLog, cv, className, delegateMethods);
        }
    }
    Set<String> promoteFields = mPromotedFields.get(className);
    if (promoteFields != null && !promoteFields.isEmpty()) {
        cv = new PromoteFieldClassAdapter(cv, promoteFields);
    }
    cr.accept(cv, 0);
    return cw.toByteArray();
}
Also used : ClassVisitor(org.objectweb.asm.ClassVisitor) ClassWriter(org.objectweb.asm.ClassWriter)

Example 5 with ClassVisitor

use of org.objectweb.asm.ClassVisitor in project android_frameworks_base by DirtyUnicorns.

the class AsmGenerator method transform.

/**
     * Transforms a class.
     * <p/>
     * There are 3 kind of transformations:
     *
     * 1- For "mock" dependencies classes, we want to remove all code from methods and replace
     * by a stub. Native methods must be implemented with this stub too. Abstract methods are
     * left intact. Modified classes must be overridable (non-private, non-final).
     * Native methods must be made non-final, non-private.
     *
     * 2- For "keep" classes, we want to rewrite all native methods as indicated above.
     * If a class has native methods, it must also be made non-private, non-final.
     *
     * Note that unfortunately static methods cannot be changed to non-static (since static and
     * non-static are invoked differently.)
     */
byte[] transform(ClassReader cr, boolean stubNativesOnly) {
    boolean hasNativeMethods = hasNativeMethods(cr);
    // Get the class name, as an internal name (e.g. com/android/SomeClass$InnerClass)
    String className = cr.getClassName();
    String newName = transformName(className);
    // transformName returns its input argument if there's no need to rename the class
    if (!newName.equals(className)) {
        mRenameCount++;
        // This class is being renamed, so remove it from the list of classes not renamed.
        mClassesNotRenamed.remove(className);
    }
    mLog.debug("Transform %s%s%s%s", className, newName.equals(className) ? "" : " (renamed to " + newName + ")", hasNativeMethods ? " -- has natives" : "", stubNativesOnly ? " -- stub natives only" : "");
    // Rewrite the new class from scratch, without reusing the constant pool from the
    // original class reader.
    ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS);
    ClassVisitor cv = cw;
    // FIXME Generify
    if ("android/content/res/Resources".equals(className)) {
        cv = new FieldInjectorAdapter(cv);
    }
    if (mReplaceMethodCallsClasses.contains(className)) {
        cv = new ReplaceMethodCallsAdapter(cv, className);
    }
    cv = new RefactorClassAdapter(cv, mRefactorClasses);
    if (!newName.equals(className)) {
        cv = new RenameClassAdapter(cv, className, newName);
    }
    String binaryNewName = newName.replace('/', '.');
    if (mInjectedMethodsMap.keySet().contains(binaryNewName)) {
        cv = new InjectMethodsAdapter(cv, mInjectedMethodsMap.get(binaryNewName));
    }
    cv = new TransformClassAdapter(mLog, mStubMethods, mDeleteReturns.get(className), newName, cv, stubNativesOnly);
    Set<String> delegateMethods = mDelegateMethods.get(className);
    if (delegateMethods != null && !delegateMethods.isEmpty()) {
        // known to have no native methods, just skip this step.
        if (hasNativeMethods || !(delegateMethods.size() == 1 && delegateMethods.contains(DelegateClassAdapter.ALL_NATIVES))) {
            cv = new DelegateClassAdapter(mLog, cv, className, delegateMethods);
        }
    }
    Set<String> promoteFields = mPromotedFields.get(className);
    if (promoteFields != null && !promoteFields.isEmpty()) {
        cv = new PromoteFieldClassAdapter(cv, promoteFields);
    }
    cr.accept(cv, 0);
    return cw.toByteArray();
}
Also used : ClassVisitor(org.objectweb.asm.ClassVisitor) ClassWriter(org.objectweb.asm.ClassWriter)

Aggregations

ClassVisitor (org.objectweb.asm.ClassVisitor)134 ClassReader (org.objectweb.asm.ClassReader)98 ClassWriter (org.objectweb.asm.ClassWriter)82 MethodVisitor (org.objectweb.asm.MethodVisitor)46 InputStream (java.io.InputStream)20 IOException (java.io.IOException)19 Type (org.objectweb.asm.Type)15 TraceClassVisitor (org.objectweb.asm.util.TraceClassVisitor)14 File (java.io.File)11 PrintWriter (java.io.PrintWriter)11 AnnotationVisitor (org.objectweb.asm.AnnotationVisitor)10 Label (org.objectweb.asm.Label)10 FileInputStream (java.io.FileInputStream)9 Test (org.junit.Test)9 FieldVisitor (org.objectweb.asm.FieldVisitor)7 FileOutputStream (java.io.FileOutputStream)6 GeneratorAdapter (org.objectweb.asm.commons.GeneratorAdapter)6 ArrayList (java.util.ArrayList)5 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)5 FieldList (net.bytebuddy.description.field.FieldList)5