Search in sources :

Example 51 with ClassVisitor

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

the class ProxySubclassGenerator method generateAndLoadSubclass.

private static Class<?> generateAndLoadSubclass(Class<?> aClass, ClassLoader loader) throws UnableToProxyException {
    LOGGER.debug(Constants.LOG_ENTRY, "generateAndLoadSubclass", new Object[] { aClass, loader });
    // set the newClassName
    String newClassName = "$" + aClass.getSimpleName() + aClass.hashCode();
    String packageName = aClass.getPackage().getName();
    if (packageName.startsWith("java.") || packageName.startsWith("javax.")) {
        packageName = "org.apache.aries.blueprint.proxy." + packageName;
    }
    String fullNewClassName = (packageName + "." + newClassName).replaceAll("\\.", "/");
    LOGGER.debug("New class name: {}", newClassName);
    LOGGER.debug("Full new class name: {}", fullNewClassName);
    Class<?> clazz = null;
    try {
        ClassReader cReader = new ClassReader(loader.getResourceAsStream(aClass.getName().replaceAll("\\.", "/") + ".class"));
        ClassWriter cWriter = new ClassWriter(ClassWriter.COMPUTE_MAXS);
        ClassVisitor dynamicSubclassAdapter = new ProxySubclassAdapter(cWriter, fullNewClassName, loader);
        byte[] byteClassData = processClass(cReader, cWriter, dynamicSubclassAdapter);
        clazz = loadClassFromBytes(loader, getBinaryName(fullNewClassName), byteClassData, aClass.getName());
    } catch (IOException ioe) {
        LOGGER.debug(Constants.LOG_EXCEPTION, ioe);
        throw new ProxyClassBytecodeGenerationException(aClass.getName(), ioe);
    } catch (TypeNotPresentException tnpe) {
        LOGGER.debug(Constants.LOG_EXCEPTION, tnpe);
        throw new ProxyClassBytecodeGenerationException(tnpe.typeName(), tnpe.getCause());
    }
    LOGGER.debug(Constants.LOG_EXIT, "generateAndLoadSubclass", clazz);
    return clazz;
}
Also used : ClassReader(org.objectweb.asm.ClassReader) ClassVisitor(org.objectweb.asm.ClassVisitor) IOException(java.io.IOException) ClassWriter(org.objectweb.asm.ClassWriter)

Example 52 with ClassVisitor

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

the class Synthesizer method main.

/**
 * This is the main method for running the Synthesizer
 *
 * @param args - String[] of file paths to class files
 * @throws Exception
 */
public static void main(String[] args) throws Exception {
    // add the synthetic modifier for each of the supplied args
    for (String arg : args) {
        FileInputStream classInStream = null;
        ClassWriter writer = null;
        try {
            // read in the class
            classInStream = new FileInputStream(arg);
            ClassReader reader = new ClassReader(classInStream);
            // make a ClassWriter constructed with the reader for speed
            // since we are mostly just copying
            // we just need to override the visit method so we can add
            // the synthetic modifier, otherwise we use the methods in
            // a standard writer
            writer = new ClassWriter(reader, 0);
            ClassVisitor cv = new CustomClassVisitor((ClassVisitor) writer);
            // call accept on the reader to start the visits
            // using the writer we created as the visitor
            reader.accept(cv, 0);
        } finally {
            if (classInStream != null)
                classInStream.close();
        }
        FileOutputStream classOutStream = null;
        try {
            // write out the new bytes of the class file
            classOutStream = new FileOutputStream(arg);
            if (writer != null)
                classOutStream.write(writer.toByteArray());
        } finally {
            // close the OutputStream if it is still around
            if (classOutStream != null)
                classOutStream.close();
        }
    }
}
Also used : FileOutputStream(java.io.FileOutputStream) ClassReader(org.objectweb.asm.ClassReader) ClassVisitor(org.objectweb.asm.ClassVisitor) FileInputStream(java.io.FileInputStream) ClassWriter(org.objectweb.asm.ClassWriter)

Example 53 with ClassVisitor

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

the class ClientWeavingHook method weave.

@Override
public void weave(WovenClass wovenClass) {
    Bundle consumerBundle = wovenClass.getBundleWiring().getBundle();
    Set<WeavingData> wd = activator.getWeavingData(consumerBundle);
    if (wd != null) {
        activator.log(Level.FINE, "Weaving class " + wovenClass.getClassName());
        ClassReader cr = new ClassReader(wovenClass.getBytes());
        ClassWriter cw = new OSGiFriendlyClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES, wovenClass.getBundleWiring().getClassLoader());
        TCCLSetterVisitor tsv = new TCCLSetterVisitor(cw, wovenClass.getClassName(), wd);
        cr.accept(tsv, ClassReader.SKIP_FRAMES);
        if (tsv.isWoven()) {
            wovenClass.setBytes(cw.toByteArray());
            if (tsv.additionalImportRequired())
                wovenClass.getDynamicImports().add(addedImport);
            if (activator.isLogEnabled(Level.FINEST)) {
                StringWriter stringWriter = new StringWriter();
                ClassReader reader = new ClassReader(wovenClass.getBytes());
                ClassVisitor tracer = new TraceClassVisitor(new PrintWriter(stringWriter));
                ClassVisitor checker = new CheckClassAdapter(tracer, true);
                reader.accept(checker, 0);
                activator.log(Level.FINEST, "Woven class bytecode: \n" + stringWriter.toString());
            }
        }
    }
}
Also used : WeavingData(org.apache.aries.spifly.WeavingData) TraceClassVisitor(org.objectweb.asm.util.TraceClassVisitor) StringWriter(java.io.StringWriter) Bundle(org.osgi.framework.Bundle) CheckClassAdapter(org.objectweb.asm.util.CheckClassAdapter) ClassReader(org.objectweb.asm.ClassReader) TraceClassVisitor(org.objectweb.asm.util.TraceClassVisitor) ClassVisitor(org.objectweb.asm.ClassVisitor) ClassWriter(org.objectweb.asm.ClassWriter) TCCLSetterVisitor(org.apache.aries.spifly.weaver.TCCLSetterVisitor) PrintWriter(java.io.PrintWriter)

Example 54 with ClassVisitor

use of org.objectweb.asm.ClassVisitor in project maven-plugins by apache.

the class DefaultShaderTest method testShaderWithRelocatedClassname.

public void testShaderWithRelocatedClassname() throws Exception {
    DefaultShader s = newShader();
    Set<File> set = new LinkedHashSet<File>();
    set.add(new File("src/test/jars/test-project-1.0-SNAPSHOT.jar"));
    set.add(new File("src/test/jars/plexus-utils-1.4.1.jar"));
    List<Relocator> relocators = new ArrayList<Relocator>();
    relocators.add(new SimpleRelocator("org/codehaus/plexus/util/", "_plexus/util/__", null, Arrays.<String>asList()));
    List<ResourceTransformer> resourceTransformers = new ArrayList<ResourceTransformer>();
    resourceTransformers.add(new ComponentsXmlResourceTransformer());
    List<Filter> filters = new ArrayList<Filter>();
    File file = new File("target/foo-relocate-class.jar");
    ShadeRequest shadeRequest = new ShadeRequest();
    shadeRequest.setJars(set);
    shadeRequest.setUberJar(file);
    shadeRequest.setFilters(filters);
    shadeRequest.setRelocators(relocators);
    shadeRequest.setResourceTransformers(resourceTransformers);
    s.shade(shadeRequest);
    URLClassLoader cl = new URLClassLoader(new URL[] { file.toURI().toURL() });
    Class<?> c = cl.loadClass("_plexus.util.__StringUtils");
    // first, ensure it works:
    Object o = c.newInstance();
    assertEquals("", c.getMethod("clean", String.class).invoke(o, (String) null));
    // now, check that its source file was rewritten:
    final String[] source = { null };
    final ClassReader classReader = new ClassReader(cl.getResourceAsStream("_plexus/util/__StringUtils.class"));
    classReader.accept(new ClassVisitor(Opcodes.ASM4) {

        @Override
        public void visitSource(String arg0, String arg1) {
            super.visitSource(arg0, arg1);
            source[0] = arg0;
        }
    }, ClassReader.SKIP_CODE);
    assertEquals("__StringUtils.java", source[0]);
}
Also used : LinkedHashSet(java.util.LinkedHashSet) ArrayList(java.util.ArrayList) ClassVisitor(org.objectweb.asm.ClassVisitor) Relocator(org.apache.maven.plugins.shade.relocation.Relocator) SimpleRelocator(org.apache.maven.plugins.shade.relocation.SimpleRelocator) SimpleRelocator(org.apache.maven.plugins.shade.relocation.SimpleRelocator) Filter(org.apache.maven.plugins.shade.filter.Filter) URLClassLoader(java.net.URLClassLoader) ComponentsXmlResourceTransformer(org.apache.maven.plugins.shade.resource.ComponentsXmlResourceTransformer) ClassReader(org.objectweb.asm.ClassReader) ResourceTransformer(org.apache.maven.plugins.shade.resource.ResourceTransformer) ComponentsXmlResourceTransformer(org.apache.maven.plugins.shade.resource.ComponentsXmlResourceTransformer) File(java.io.File)

Example 55 with ClassVisitor

use of org.objectweb.asm.ClassVisitor in project maven-plugins by apache.

the class DefaultShader method addRemappedClass.

private void addRemappedClass(RelocatorRemapper remapper, JarOutputStream jos, File jar, String name, InputStream is) throws IOException, MojoExecutionException {
    if (!remapper.hasRelocators()) {
        try {
            jos.putNextEntry(new JarEntry(name));
            IOUtil.copy(is, jos);
        } catch (ZipException e) {
            getLogger().debug("We have a duplicate " + name + " in " + jar);
        }
        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 ClassRemapper(cw, remapper) {

        @Override
        public void visitSource(final String source, final String debug) {
            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);
                super.visitSource(filename, debug);
            }
        }
    };
    try {
        cr.accept(cv, ClassReader.EXPAND_FRAMES);
    } catch (Throwable ise) {
        throw new MojoExecutionException("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('.')));
    try {
        // Now we put it back on so the class file is written out with the right extension.
        jos.putNextEntry(new JarEntry(mappedName + ".class"));
        IOUtil.copy(renamedClass, jos);
    } catch (ZipException e) {
        getLogger().debug("We have a duplicate " + mappedName + " in " + jar);
    }
}
Also used : MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) ClassReader(org.objectweb.asm.ClassReader) ZipException(java.util.zip.ZipException) ClassVisitor(org.objectweb.asm.ClassVisitor) JarEntry(java.util.jar.JarEntry) ClassRemapper(org.objectweb.asm.commons.ClassRemapper) ClassWriter(org.objectweb.asm.ClassWriter)

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