Search in sources :

Example 76 with ClassVisitor

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

the class AsmProxyClassGenerator method generateProxyClassBytes.

private static byte[] generateProxyClassBytes(Class<?> targetClass, String proxyName, String superAccessorMethodSuffix, Class<?>[] additionalInterfaces, java.lang.reflect.Method[] delegateMethods, java.lang.reflect.Method[] interceptMethods) {
    Class<?> superClass = targetClass;
    String[] interfaces = new String[] {};
    if (targetClass.isInterface()) {
        superClass = Object.class;
        interfaces = new String[] { Type.getInternalName(targetClass) };
    }
    // add DeltaSpikeProxy as interface
    interfaces = Arrays.copyOf(interfaces, interfaces.length + 1);
    interfaces[interfaces.length - 1] = Type.getInternalName(DeltaSpikeProxy.class);
    if (additionalInterfaces != null && additionalInterfaces.length > 0) {
        interfaces = Arrays.copyOf(interfaces, interfaces.length + additionalInterfaces.length);
        for (int i = 0; i < additionalInterfaces.length; i++) {
            interfaces[(interfaces.length - 1) + i] = Type.getInternalName(additionalInterfaces[i]);
        }
    }
    Type superType = Type.getType(superClass);
    Type proxyType = Type.getObjectType(proxyName);
    Type delegateInvocationHandlerType = Type.getType(InvocationHandler.class);
    final ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS);
    cw.visit(Opcodes.V1_6, Opcodes.ACC_PUBLIC + Opcodes.ACC_SUPER, proxyType.getInternalName(), null, superType.getInternalName(), interfaces);
    defineInvocationHandlerField(cw, delegateInvocationHandlerType);
    defineDefaultConstructor(cw, proxyType, superType);
    defineDelegateInvocationHandlerConstructor(cw, proxyType, superType, delegateInvocationHandlerType);
    defineDeltaSpikeProxyMethods(cw, proxyType, delegateInvocationHandlerType);
    if (delegateMethods != null) {
        for (java.lang.reflect.Method method : delegateMethods) {
            defineMethod(cw, method, DelegateManualInvocationHandler.class);
        }
    }
    if (interceptMethods != null) {
        for (java.lang.reflect.Method method : interceptMethods) {
            defineSuperAccessorMethod(cw, method, superType, superAccessorMethodSuffix);
            defineMethod(cw, method, InterceptManualInvocationHandler.class);
        }
    }
    // copy all annotations from the source class
    try {
        // ClassVisitor to intercept all annotation visits on the class
        ClassVisitor cv = new ClassVisitor(Opcodes.ASM5) {

            @Override
            public AnnotationVisitor visitAnnotation(String desc, boolean visible) {
                return new CopyAnnotationVisitorAdapter(super.visitAnnotation(desc, visible), cw.visitAnnotation(desc, visible));
            }
        };
        // visit class to proxy with our visitor to copy all annotations from the source class to our ClassWriter
        String sourceClassFilename = targetClass.getName().replace('.', '/') + ".class";
        ClassReader cr = new ClassReader(targetClass.getClassLoader().getResourceAsStream(sourceClassFilename));
        cr.accept(cv, 0);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    return cw.toByteArray();
}
Also used : DeltaSpikeProxy(org.apache.deltaspike.proxy.spi.DeltaSpikeProxy) ClassVisitor(org.objectweb.asm.ClassVisitor) ClassWriter(org.objectweb.asm.ClassWriter) UndeclaredThrowableException(java.lang.reflect.UndeclaredThrowableException) Type(org.objectweb.asm.Type) ClassReader(org.objectweb.asm.ClassReader)

Example 77 with ClassVisitor

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

the class MetaClassImpl method getClassNode.

/**
     * Obtains a reference to the original AST for the MetaClass if it is available at runtime
     *
     * @return The original AST or null if it cannot be returned
     */
public ClassNode getClassNode() {
    if (classNode == null && GroovyObject.class.isAssignableFrom(theClass)) {
        // let's try load it from the classpath
        String groovyFile = theClass.getName();
        int idx = groovyFile.indexOf('$');
        if (idx > 0) {
            groovyFile = groovyFile.substring(0, idx);
        }
        groovyFile = groovyFile.replace('.', '/') + ".groovy";
        //System.out.println("Attempting to load: " + groovyFile);
        URL url = theClass.getClassLoader().getResource(groovyFile);
        if (url == null) {
            url = Thread.currentThread().getContextClassLoader().getResource(groovyFile);
        }
        if (url != null) {
            try {
                /**
                     * todo there is no CompileUnit in scope so class name
                     * checking won't work but that mostly affects the bytecode
                     * generation rather than viewing the AST
                     */
                CompilationUnit.ClassgenCallback search = new CompilationUnit.ClassgenCallback() {

                    public void call(ClassVisitor writer, ClassNode node) {
                        if (node.getName().equals(theClass.getName())) {
                            MetaClassImpl.this.classNode = node;
                        }
                    }
                };
                CompilationUnit unit = new CompilationUnit();
                unit.setClassgenCallback(search);
                unit.addSource(url);
                unit.compile(Phases.CLASS_GENERATION);
            } catch (Exception e) {
                throw new GroovyRuntimeException("Exception thrown parsing: " + groovyFile + ". Reason: " + e, e);
            }
        }
    }
    return classNode;
}
Also used : CompilationUnit(org.codehaus.groovy.control.CompilationUnit) ClassNode(org.codehaus.groovy.ast.ClassNode) ClassVisitor(org.objectweb.asm.ClassVisitor) URL(java.net.URL) InvokerInvocationException(org.codehaus.groovy.runtime.InvokerInvocationException) IntrospectionException(java.beans.IntrospectionException) PrivilegedActionException(java.security.PrivilegedActionException) MethodSelectionException(org.codehaus.groovy.runtime.metaclass.MethodSelectionException)

Example 78 with ClassVisitor

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

the class GroovySunClassLoader method loadAbstract.

private void loadAbstract() throws IOException {
    final InputStream asStream = GroovySunClassLoader.class.getClass().getClassLoader().getResourceAsStream(resName("org.codehaus.groovy.runtime.callsite.AbstractCallSite"));
    ClassReader reader = new ClassReader(asStream);
    final ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS);
    final ClassVisitor cv = new ClassVisitor(4, cw) {

        public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) {
            super.visit(version, access, name, signature, "sun/reflect/GroovyMagic", interfaces);
        }
    };
    reader.accept(cv, ClassWriter.COMPUTE_MAXS);
    asStream.close();
    define(cw.toByteArray(), "org.codehaus.groovy.runtime.callsite.AbstractCallSite");
}
Also used : InputStream(java.io.InputStream) ClassReader(org.objectweb.asm.ClassReader) ClassVisitor(org.objectweb.asm.ClassVisitor) ClassWriter(org.objectweb.asm.ClassWriter)

Example 79 with ClassVisitor

use of org.objectweb.asm.ClassVisitor in project webservices-axiom by apache.

the class PostProcessMojo method execute.

@Override
public void execute() throws MojoExecutionException, MojoFailureException {
    if (!classesDir.exists()) {
        return;
    }
    DirectoryScanner ds = new DirectoryScanner();
    ds.setIncludes(new String[] { "**/*.class" });
    ds.setBasedir(classesDir);
    ds.scan();
    for (String relativePath : ds.getIncludedFiles()) {
        File file = new File(classesDir, relativePath);
        ClassWriter classWriter;
        try {
            InputStream in = new FileInputStream(file);
            try {
                ClassReader classReader = new ClassReader(in);
                classWriter = new ClassWriter(classReader, ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS);
                ClassVisitor classVisitor = classWriter;
                if (relativePath.equals("org/apache/axiom/om/OMText.class")) {
                    classVisitor = new GetDataHandlerBridgeMethodInjector(classVisitor);
                }
                classVisitor = new AspectJCodeRemover(classVisitor);
                classReader.accept(classVisitor, 0);
            } finally {
                in.close();
            }
        } catch (IOException ex) {
            throw new MojoExecutionException("Failed to read " + relativePath + ": " + ex.getMessage(), ex);
        }
        try {
            OutputStream out = new FileOutputStream(file);
            try {
                out.write(classWriter.toByteArray());
            } finally {
                out.close();
            }
        } catch (IOException ex) {
            throw new MojoExecutionException("Failed to write " + relativePath + ": " + ex.getMessage(), ex);
        }
    }
}
Also used : MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) ClassVisitor(org.objectweb.asm.ClassVisitor) IOException(java.io.IOException) ClassWriter(org.objectweb.asm.ClassWriter) FileInputStream(java.io.FileInputStream) DirectoryScanner(org.codehaus.plexus.util.DirectoryScanner) FileOutputStream(java.io.FileOutputStream) ClassReader(org.objectweb.asm.ClassReader) File(java.io.File)

Example 80 with ClassVisitor

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

the class InstrumentTest method assertInstrumented.

private void assertInstrumented(File classfile) throws IOException {
    InputStream in = new FileInputStream(classfile);
    ClassReader reader = new ClassReader(in);
    in.close();
    final Set<String> fields = new HashSet<String>();
    reader.accept(new ClassVisitor(Opcodes.ASM6) {

        @Override
        public FieldVisitor visitField(int access, String name, String desc, String signature, Object value) {
            fields.add(name);
            return null;
        }
    }, 0);
    assertTrue(fields.contains("$jacocoData"));
}
Also used : FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) ClassReader(org.objectweb.asm.ClassReader) ClassVisitor(org.objectweb.asm.ClassVisitor) FieldVisitor(org.objectweb.asm.FieldVisitor) FileInputStream(java.io.FileInputStream) HashSet(java.util.HashSet)

Aggregations

ClassVisitor (org.objectweb.asm.ClassVisitor)133 ClassReader (org.objectweb.asm.ClassReader)97 ClassWriter (org.objectweb.asm.ClassWriter)80 MethodVisitor (org.objectweb.asm.MethodVisitor)45 IOException (java.io.IOException)19 InputStream (java.io.InputStream)19 Type (org.objectweb.asm.Type)14 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 FileOutputStream (java.io.FileOutputStream)6 FieldVisitor (org.objectweb.asm.FieldVisitor)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