Example usage for org.objectweb.asm.tree ClassNode accept

List of usage examples for org.objectweb.asm.tree ClassNode accept

Introduction

In this page you can find the example usage for org.objectweb.asm.tree ClassNode accept.

Prototype

public void accept(final ClassVisitor classVisitor) 

Source Link

Document

Makes the given class visitor visit this class.

Usage

From source file:de.enough.polish.postcompile.java5.Java5PostCompiler.java

License:Open Source License

public void postCompile(File classesDir, Device device, DirClassLoader loader, List classes)
        throws BuildException {
    int version = ((Integer) versionMap.get(this.target)).intValue();
    RetroWeaver task = new RetroWeaver(version);
    task.setStripSignatures(true);//from   w ww  .  ja v  a2  s  .  com
    boolean useDefaultPackage = this.environment.hasSymbol("polish.useDefaultPackage");
    boolean isCldc10 = this.environment.hasSymbol("polish.cldc1.0");
    if (isCldc10) {
        task.addClassTranslation("java.lang.NoClassDefFoundError", "java.lang.Throwable");
    }
    task.addClassTranslation("java.lang.NoSuchFieldError", "java.lang.Throwable");
    task.addClassTranslation("java.lang.NoSuchMethodError", "java.lang.Throwable");
    if (!useDefaultPackage) {
        task.setAutoboxClass("de.enough.polish.java5.Autobox");
        task.setEnumClass("de.enough.polish.java5.Enum");
        task.addClassTranslation("java.lang.Iterable", "de.enough.polish.util.Iterable");
        task.addClassTranslation("java.util.Iterator", "de.enough.polish.util.Iterator");
    } else {
        task.setAutoboxClass("Autobox");
        task.setEnumClass("Enum");
        task.addClassTranslation("java.lang.Iterable", "Iterable");
        task.addClassTranslation("java.util.Iterator", "Iterator");
    }
    task.setListener(new WeaveListener() {
        public void weavingStarted(String msg) {
            System.out.println(msg);
        }

        public void weavingCompleted(String msg) {
            System.out.println(msg);
        }

        public void weavingPath(String pPath) {
            if (Java5PostCompiler.this.isVerbose) {
                System.out.println("Weaving " + pPath);
            }
        }
    });

    // We use a new classes directory, so that the user does not need to make a clean build each time he makes a small update.
    File newClassesDir = new File(classesDir.getParentFile(), "classes_12");

    if (!newClassesDir.exists()) {
        newClassesDir.mkdir();
    }

    try {
        FileUtil.copyDirectoryContents(classesDir, newClassesDir, true);
        loader = DirClassLoader.createClassLoader(newClassesDir);
    } catch (IOException e) {
        e.printStackTrace();
        BuildException be = new BuildException("Unable to copy classes to temporary directory.");
        be.initCause(e);
        throw be;
    }

    device.setClassesDir(newClassesDir.getAbsolutePath());

    try {
        task.weave(newClassesDir);
    } catch (IOException e) {
        e.printStackTrace();
        throw new BuildException("Unable to transform bytecode: " + e.toString());
    }

    ASMClassLoader asmLoader = new ASMClassLoader(loader);
    EnumManager manager = EnumManager.getInstance();

    String enumClass = this.environment != null && this.environment.hasSymbol(POLISH_USE_DEFAULT_PACKAGE)
            ? CLASS_ENUM_DEFAULT
            : CLASS_ENUM;

    // Clear global EnumManager instance.
    manager.clear();

    // Find all classes implementing java.lang.Enum.
    Iterator it = classes.iterator();

    while (it.hasNext()) {
        String className = (String) it.next();

        try {
            ClassNode classNode = asmLoader.loadClass(className);

            if (enumClass.equals(classNode.superName)) {
                manager.addEnumClass(className);
            }
        } catch (ClassNotFoundException e) {
            System.out.println("Error loading class " + className);
        }
    }

    // Find all local variables with enum classes as type.
    it = classes.iterator();

    while (it.hasNext()) {
        String className = (String) it.next();

        try {
            // Load class.
            ClassNode classNode = asmLoader.loadClass(className, false);

            // Read the class and collect infos about enums.
            // TODO: Don't use a ClassWriter instance here. The stuff gets dropped
            // into nirvana anyway.
            ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS);
            Type type = Type.getType("L" + className.replace('\\', '/') + ";");
            Java5CollectorClassVisitor visitor = new Java5CollectorClassVisitor(writer, type);
            classNode.accept(visitor);
        } catch (ClassNotFoundException e) {
            System.out.println("Error loading class " + className);
        }
    }

    // Process all classes.
    it = classes.iterator();

    while (it.hasNext()) {
        String className = (String) it.next();

        try {
            // Load class.
            ClassNode classNode = asmLoader.loadClass(className);

            // Transform class. We need to write the transformed classes into another
            // ClassNode object as some transformations are done in visitEnd() methods
            // and the changes from there would be lost when writing the class directly. 
            ClassNode targetNode = new ClassNode();
            Java5ClassVisitor visitor = new Java5ClassVisitor(targetNode);
            classNode.accept(visitor);

            // Write class.
            ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS);
            targetNode.accept(writer);
            writeClass(newClassesDir, className, writer.toByteArray());
        } catch (IOException e) {
            BuildException be = new BuildException("Error writing class " + className);
            be.initCause(e);
            throw be;
        } catch (ClassNotFoundException e) {
            System.out.println("Error loading class " + className);
        }
    }
}

From source file:de.enough.polish.precompile.blackberry.ImportResolver.java

License:Open Source License

public void preCompile(File classesDir, Device device) throws BuildException {
    // Do nothing if classesDir doesn't exist yet.
    // This happens when no classes where unpacked to classesDir at this stage.
    if (!classesDir.exists()) {
        return;//from  w  w  w  . ja  v a2  s. com
    }

    // Find all classes and put their class names into the classes list.
    ArrayList classes = new ArrayList();
    String[] fileNames = FileUtil.filterDirectory(classesDir, ".class", true);
    System.out.println("Precompiling " + fileNames.length + " classes from " + classesDir.getPath());

    for (int i = 0; i < fileNames.length; i++) {
        // Cut off file extension.
        String className = fileNames[i].substring(0, fileNames[i].length() - 6);

        // Add class name to known classes.
        classes.add(className);
    }

    // Create classloader for the classesDir.
    DirClassLoader loader = DirClassLoader.createClassLoader(classesDir);

    ASMClassLoader asmLoader = new ASMClassLoader(loader);
    Iterator classesIt = classes.iterator();

    while (classesIt.hasNext()) {
        String className = (String) classesIt.next();

        try {
            ClassNode classNode = asmLoader.loadClass(className);
            ClassWriter writer = new ClassWriter(0);
            ClassRenamingClassVisitor visitor = new ClassRenamingClassVisitor(writer, this.renamingMap);
            classNode.accept(visitor);

            writeClass(classesDir, className, writer.toByteArray());
        } catch (ClassNotFoundException e) {
            System.out.println("Error loading class " + className);
        } catch (IOException e) {
            throw new BuildException(e);
        } catch (Exception e) {
            System.out.println("Error loading class " + className + ": " + e.toString());
            throw new BuildException(e);
        }
    }
}

From source file:de.enough.polish.precompiler.PolishImportResolver.java

License:Open Source License

public void preCompile(File classesDir, Device device) throws BuildException {
    // Do nothing if classesDir doesn't exist yet.
    // This happens when no classes where unpacked to classesDir at this stage.
    if (!classesDir.exists()) {
        return;/*w  ww  . j  a va2  s .  co m*/
    }

    // Find all classes and put their class names into the classes list.
    ArrayList classes = new ArrayList();
    String[] fileNames = FileUtil.filterDirectory(classesDir, ".class", true);
    boolean isSlash = File.separatorChar == '/';

    for (int i = 0; i < fileNames.length; i++) {
        // Cut off file extension.
        String fileName = fileNames[i];
        if ((isSlash && fileName.startsWith("de/enough/polish"))
                || (!isSlash && fileName.startsWith("de\\enough\\polish"))) {
            continue;
        }
        String className = fileName.substring(0, fileName.length() - 6);

        // Add class name to known classes.
        classes.add(className);
    }
    System.out.println("Precompiling " + classes.size() + " classes from " + classesDir.getPath());

    // Create classloader for the classesDir.
    DirClassLoader loader = DirClassLoader.createClassLoader(classesDir);

    ASMClassLoader asmLoader = new ASMClassLoader(loader);
    Iterator classesIt = classes.iterator();

    while (classesIt.hasNext()) {
        String className = (String) classesIt.next();

        try {
            ClassNode classNode = asmLoader.loadClass(className);
            ClassWriter writer = new ClassWriter(0);
            ClassRenamingClassVisitor visitor = new ClassRenamingClassVisitor(writer, this.renamingMap);
            classNode.accept(visitor);

            writeClass(classesDir, className, writer.toByteArray());
        } catch (ClassNotFoundException e) {
            System.out.println("Error loading class " + className);
        } catch (IOException e) {
            throw new BuildException(e);
        } catch (Exception e) {
            System.out.println("Error loading class " + className + ": " + e.toString());
            throw new BuildException(e);
        }
    }
}

From source file:de.loskutov.bco.asm.DecompilerHelper.java

License:Open Source License

public static DecompiledClass getDecompiledClass(final InputStream is, DecompilerOptions options)
        throws IOException, UnsupportedClassVersionError {
    ClassReader cr = new ClassReader(is);
    ClassNode cn = new ClassNode(Opcodes.ASM5);
    int crFlags = 0;
    if (options.modes.get(BCOConstants.F_EXPAND_STACKMAP)) {
        crFlags |= ClassReader.EXPAND_FRAMES;
    }/*from  w w  w .j  a v a2s  .  c  om*/
    cr.accept(cn, crFlags);
    ICommentedClassVisitor printer;
    if (options.modes.get(BCOConstants.F_SHOW_ASMIFIER_CODE)) {
        printer = new CommentedASMifierClassVisitor(cn, options);
    } else {
        printer = new CommentedClassVisitor(cn, options);
    }
    TraceClassVisitor dcv = new TraceClassVisitor(null, (Printer) printer, null);
    cn.accept(dcv);
    return getResult(printer, options, cn);
}

From source file:de.scoopgmbh.copper.wfrepo.AbstractWorkflowRepository.java

License:Apache License

void instrumentWorkflows(File adaptedTargetDir, Map<String, Clazz> clazzMap, Map<String, ClassInfo> classInfos,
        File compileTargetDir) throws IOException {
    logger.info("Instrumenting classfiles");
    URLClassLoader tmpClassLoader = new URLClassLoader(new URL[] { compileTargetDir.toURI().toURL() },
            Thread.currentThread().getContextClassLoader());
    for (Clazz clazz : clazzMap.values()) {
        byte[] bytes;
        FileInputStream fis = new FileInputStream(clazz.classfile);
        try {/*from www .j a v  a2s . co m*/
            ClassReader cr2 = new ClassReader(fis);
            ClassNode cn = new ClassNode();
            cr2.accept(cn, flags);

            //Now content of ClassNode can be modified and then serialized back into bytecode:
            new TryCatchBlockHandler().instrument(cn);

            ClassWriter cw2 = new ClassWriter(0);
            cn.accept(cw2);
            bytes = cw2.toByteArray();

            if (logger.isTraceEnabled()) {
                StringWriter sw = new StringWriter();
                new ClassReader(bytes).accept(new TraceClassVisitor(new PrintWriter(sw)), 0);
                logger.trace(sw.toString());
            }

            ClassReader cr = new ClassReader(bytes);
            ClassWriter cw = new ClassWriter(0);

            ScottyClassAdapter cv = new ScottyClassAdapter(cw, clazz.aggregatedInterruptableMethods);
            cr.accept(cv, flags);
            classInfos.put(clazz.classname, cv.getClassInfo());
            bytes = cw.toByteArray();

            // Recompute frames, etc.
            ClassReader cr3 = new ClassReader(bytes);
            ClassWriter cw3 = new ClassWriter(ClassWriter.COMPUTE_FRAMES);
            cr3.accept(cw3, ClassReader.SKIP_FRAMES);
            bytes = cw3.toByteArray();

            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            CheckClassAdapter.verify(new ClassReader(cw.toByteArray()), tmpClassLoader, false, pw);
            if (sw.toString().length() != 0) {
                logger.error("CheckClassAdapter.verify failed for class " + cn.name + ":\n" + sw.toString());
            } else {
                logger.info("CheckClassAdapter.verify succeeded for class " + cn.name);
            }

        } finally {
            fis.close();
        }

        File adaptedClassfileName = new File(adaptedTargetDir, clazz.classname + ".class");
        adaptedClassfileName.getParentFile().mkdirs();
        FileOutputStream fos = new FileOutputStream(adaptedClassfileName);
        try {
            fos.write(bytes);
        } finally {
            fos.close();
        }
    }
}

From source file:de.tuberlin.uebb.jbop.access.ConstructorBuilderTest.java

License:Open Source License

private Class<?> getClass(final ClassNode classNode, final Object object)
        throws JBOPClassException, ClassNotFoundException {
    final ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS);
    classNode.accept(writer);

    final byte[] bytes = writer.toByteArray();

    final ClassDescriptor classDescriptor = ClassAccessor.getClassDescriptor(object.getClass());
    classDescriptor.setClassData(bytes);
    final ClassDescriptor renamedClass = ClassAccessor.rename(classDescriptor, "WithConstructor");
    ClassAccessor.store(renamedClass);/* ww w.  j av a 2  s.  co m*/

    return Class.forName(renamedClass.getName(), true, ClassAccessor.getClassloader());
}

From source file:de.tuberlin.uebb.jbop.access.OptimizerUtils.java

License:Open Source License

/**
 * Write class and instantiate the Object.
 * The new class (classNode) has to be a subclass of the Type of input.
 * The new class is renamed to "Input name" + "suffix".
 * /* ww w.ja  v a2  s.c  o  m*/
 * @param <T>
 *          the generic type
 * @param classNode
 *          the class node
 * @param input
 *          the input
 * @param suffix
 *          the suffix
 * @return the newe Class-instance
 * @throws JBOPClassException
 *           the jBOP class exception
 */
public static <T> T createInstance(final ClassNode classNode, final T input, final String suffix)
        throws JBOPClassException {
    RemoveUnusedFields.removeUnusedFields(classNode);
    final List<Object> params = ConstructorBuilder.createConstructor(classNode, input);
    final ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS);
    classNode.accept(writer);

    final byte[] bytes = writer.toByteArray();
    final T newInstance = instanceOf(bytes, input, params, suffix);
    CACHE.put(input, newInstance);
    return newInstance;
}

From source file:de.unisb.cs.st.javaslicer.tracer.instrumentation.Transformer.java

License:Open Source License

private byte[] transform0(final String className, final String javaClassName, final byte[] classfileBuffer) {

    long startNanos = System.nanoTime();

    final ClassReader reader = new ClassReader(classfileBuffer);

    final ClassNode classNode = new ClassNode();
    reader.accept(classNode, 0);// w w  w  .j  av a  2s .c o m
    final ClassWriter writer;

    this.totalBytecodeParsingTime.addAndGet(System.nanoTime() - startNanos);

    if (this.tracer.check) {
        checkClass(classfileBuffer, className, classfileBuffer);
    }

    // we have to synchronize on System.out first.
    // otherwise it may lead to a deadlock if a thread calls removeStale() on ConcurrentReferenceHashMap
    // while he holds the lock for System.out, but another thread is inside the transformation step and
    // waits for the lock of System.out
    synchronized (System.out) {
        synchronized (this.transformationLock) {

            // register that class for later reconstruction of the trace
            List<Field> fields = classNode.fields.isEmpty() ? Collections.<Field>emptyList()
                    : new ArrayList<Field>(classNode.fields.size());

            final String javaSuperName = Type.getObjectType(classNode.superName).getClassName();
            final ReadClass readClass = new ReadClass(className, AbstractInstruction.getNextIndex(),
                    classNode.access, classNode.sourceFile, fields, javaSuperName);
            for (final Object fieldObj : classNode.fields) {
                final FieldNode f = (FieldNode) fieldObj;
                fields.add(new Field(f.name, f.desc, f.access, readClass));
            }

            long nanosBeforeTransformation = System.nanoTime();

            if (Arrays.asList(this.pauseTracingClasses).contains(javaClassName)
                    || className.startsWith("java/security/")) {
                new PauseTracingInstrumenter(readClass, this.tracer).transform(classNode);
            } else {
                if ("java/lang/Thread".equals(className))
                    new ThreadInstrumenter(readClass, this.tracer).transform(classNode);
                else
                    new TracingClassInstrumenter(readClass, this.tracer).transform(classNode);
            }

            new IdentifiableInstrumenter(readClass, this.tracer).transform(classNode);

            long nanosAfterTransformation = System.nanoTime();
            this.totalRawTransformationTime.addAndGet(nanosAfterTransformation - nanosBeforeTransformation);

            writer = new FixedClassWriter(
                    COMPUTE_FRAMES ? ClassWriter.COMPUTE_FRAMES : ClassWriter.COMPUTE_MAXS);
            ClassVisitor output = this.tracer.check ? new CheckClassAdapter(writer, false) : writer;

            classNode.accept(COMPUTE_FRAMES ? new JSRInliner(output) : output);

            this.totalBytecodeWritingTime.addAndGet(System.nanoTime() - nanosAfterTransformation);

            readClass.setInstructionNumberEnd(AbstractInstruction.getNextIndex());

            // now we can write the class out
            // NOTE: we do not write it out immediately, because this sometimes leads
            // to circular dependencies!
            //readClass.writeOut(this.readClassesOutputStream, this.readClassesStringCache);
            this.readClasses.add(readClass);

        }
    }

    final byte[] newClassfileBuffer = writer.toByteArray();

    if (this.tracer.check) {
        checkClass(newClassfileBuffer, className, classfileBuffer);
    }

    //printClass(newClassfileBuffer, Type.getObjectType(className).getClassName());
    /*
    if (className.endsWith("line/Main"))
    printClass(newClassfileBuffer, Type.getObjectType(className).getClassName());
    */

    return newClassfileBuffer;
}

From source file:forgefix.ForgeFixTransformer.java

License:LGPL

@Override
public byte[] transform(String name, String transformedName, byte[] bytes) {
    if (bytes == null)
        return bytes;

    if (transformedName.equals("com.xcompwiz.mystcraft.world.gen.structure.ComponentVillageArchivistHouse")
            || (transformedName.equals(/* w  w  w .  j  ava2  s.c om*/
                    "com.xcompwiz.mystcraft.world.gen.structure.ComponentScatteredFeatureSmallLibrary"))) {
        ClassNode classNode = new ClassNode();
        ClassReader classReader = new ClassReader(bytes);

        classReader.accept(classNode, 0);

        MethodNode vanillaMethod = null;
        for (MethodNode method : classNode.methods) {
            if (method.name.equals("generateStructureLectern")) {
                vanillaMethod = method;
            }
        }

        MethodNode moddedMethod = new MethodNode(ASM4, ACC_PROTECTED, "generateStructureLectern",
                getMethodDescriptor(BOOLEAN_TYPE), null, null);
        moddedMethod.desc = "(Lnet/minecraft/world/World;Lnet/minecraft/world/gen/structure/StructureBoundingBox;Ljava/util/Random;IIIIILnet/minecraftforge/common/ChestGenHooks;)Z";
        moddedMethod.instructions.add(new InsnNode(ICONST_0));
        moddedMethod.instructions.add(new InsnNode(IRETURN));

        if (moddedMethod != null) {
            classNode.methods.remove(vanillaMethod);
            moddedMethod.accept(classNode);

            ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS);
            classNode.accept(writer);
            return writer.toByteArray();
        }
    }

    return bytes;
}

From source file:fr.theshark34.feelcraft.FeelcraftClassTransformer.java

License:Apache License

/**
 * Patchs the Minecraft class/*w  ww  . j  av a  2  s .c o  m*/
 * 
 * @param name
 *            The class name
 * @param bytes
 *            The initial class bytes
 * @param obfuscated
 *            If the class is obfuscated
 * @return The modified bytes
 */
public byte[] patchClassASM(String name, byte[] bytes, boolean obfuscated) {
    // Starting the pre init
    Feelcraft.preInit();

    // Printing messages
    logger.info("[Feelcraft] Starting patching Minecraft");
    logger.info("[Feelcraft] Target class : " + name);

    // Getting the target method if the game is obfuscated or not
    String targetMethod;
    if (obfuscated)
        targetMethod = "ag";
    else
        targetMethod = "startGame";

    // Getting the class nod and reading the initial class
    ClassNode classNode = new ClassNode();
    ClassReader classReader = new ClassReader(bytes);
    classReader.accept(classNode, 0);

    // Just a boolean that will be true if the patch will be done to check
    // if it was done
    boolean patchDone = false;

    // Getting the class methods
    Iterator<MethodNode> methods = classNode.methods.iterator();

    // For each method in the class
    while (methods.hasNext()) {
        // Getting the method
        MethodNode m = methods.next();

        // If the method is our target method
        if ((m.name.equals(targetMethod) && m.desc.equals("()V"))) {
            // Printing a message
            logger.info("[Feelcraft] Patching method : " + m.name + m.desc);

            // Insert a line that will call Feelcraft.start at the top of
            // the method
            m.instructions.insertBefore(m.instructions.getFirst(), new MethodInsnNode(Opcodes.INVOKESTATIC,
                    "fr/theshark34/feelcraft/Feelcraft", "start", "()V", false));

            // Setting patchDone to true
            patchDone = true;

            // Stopping the loop
            break;
        }
    }

    // If the patch wasn't done
    if (!patchDone)
        // Printing a warning message
        logger.warn("[Feelcraft] Warning the patch wasn't done ! Some things will not going to work !");

    // Writing the patched class
    logger.info("[Feelcraft] Writing the patched class");
    ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES);
    classNode.accept(writer);

    // Printing a done message
    if (patchDone)
        logger.info("[Feelcraft] Successfully patched Minecraft !");
    else
        logger.info("[Feelcraft] Done");

    // Returning the modified bytes
    return writer.toByteArray();
}