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;
}
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();
}
}
}
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());
}
}
}
}
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]);
}
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);
}
}
Aggregations