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

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

Introduction

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

Prototype

public ClassNode() 

Source Link

Document

Constructs a new ClassNode .

Usage

From source file:cuchaz.enigma.analysis.ParsedJar.java

License:Open Source License

public ParsedJar(JarInputStream jar) throws IOException {
    try {/*from ww w  .j  a v a2s  .  co m*/
        // get the jar entries that correspond to classes
        JarEntry entry;
        while ((entry = jar.getNextJarEntry()) != null) {
            // is this a class file?
            if (entry.getName().endsWith(".class")) {
                // read the ClassNode from the jar
                ClassReader reader = new ClassReader(jar);
                ClassNode node = new ClassNode();
                reader.accept(node, 0);
                String path = entry.getName().substring(0, entry.getName().length() - ".class".length());
                nodes.put(path, node);
                jar.closeEntry();
            }
        }
    } finally {
        jar.close();
    }
}

From source file:customskinloader.modfix.ModFixTransformer.java

License:GNU General Public License

@Override
public byte[] transform(String className, String transformedName, byte[] bytes) {
    if (!map.containsKey(className))
        return bytes;
    //FMLRelaunchLog.info("[ModFixTransformer] !!! "+className);
    Map<String, IMethodTransformer> transMap = map.get(className);
    ClassReader cr = new ClassReader(bytes);
    ClassNode cn = new ClassNode();
    cr.accept(cn, 0);//  w w w  . j av a 2 s. c o  m

    List<MethodNode> ml = new ArrayList<MethodNode>();
    ml.addAll(cn.methods);
    for (MethodNode mn : ml) {
        String methodName = mn.name;
        String methodDesc = mn.desc;
        //FMLRelaunchLog.info("[ModFixTransformer] ! "+methodName+" "+methodDesc);
        if (transMap.containsKey(methodName + methodDesc)) {
            try {
                FMLRelaunchLog.info("[ModFixTransformer] Transforming method %s in class %s",
                        methodName + methodDesc, className);
                transMap.get(methodName + methodDesc).transform(mn);
                FMLRelaunchLog.info("[ModFixTransformer] Successfully transformed method %s in class %s",
                        methodName + methodDesc, className);
            } catch (Exception e) {
                FMLRelaunchLog.warning(
                        "[ModFixTransformer] An error happened when transforming method %s in class %s. The whole class was not modified.",
                        methodName + methodDesc, className);
                e.printStackTrace();
                return bytes;
            }
        }
    }

    ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS);
    cn.accept(cw);
    return cw.toByteArray();
}

From source file:de.codesourcery.asm.controlflow.ControlFlowGrapher.java

License:Apache License

public void showclass(String classname) throws AnalyzerException, IOException {
    final ClassReader classReader = ASMUtil.createClassReader(classname, classPathEntries, new ILogger() {

        @Override/*w  w w . ja v a 2 s  . co m*/
        public void logVerbose(String msg) {
            ControlFlowGrapher.this.logVerbose(msg);
        }
    });
    final ClassNode cn = new ClassNode();
    classReader.accept(cn, 0);
    for (Object m : cn.methods) {
        final MethodNode mn = (MethodNode) m;
        if (isConstructor(mn)) {
            if (includeConstructors) {
                visitMethod(mn, classname);
            }
        } else {
            if (matches(mn)) {
                visitMethod(mn, classname);
            } else {
                logVerbose("Ignored method: " + mn.name + "_" + mn.desc);
            }
        }
    }
    //System.out.println(analyzer.graphmap);

    /*    for ( Object m : cn.methods ) 
        {
    final MethodNode mn= (MethodNode) m; 
    if ( isConstructor( mn ) ) 
    {
        if ( includeConstructors ) {
           MethodDOTRender( mn );
        }
    } else {
        if ( matches( mn ) ) {
           MethodDOTRender( mn );
        } else {
            logVerbose("Ignored method: "+mn.name+"_"+mn.desc);
        }
    }
        }*/
    for (Object m : cn.innerClasses) {
        final InnerClassNode icn = (InnerClassNode) m;
        if (icn.name.equals(classname))
            break;
        showclass(icn.name);
        /*        final ClassReader classReader2 = ASMUtil.createClassReader( icn.name , classPathEntries , new ILogger() {
                
        @Override
        public void logVerbose(String msg)
        {
            ControlFlowGrapher.this.logVerbose( msg );
        }
                });
                        
                final ClassNode cn2 = new ClassNode();
                classReader2.accept( cn2 , 0 );
               for ( Object m2 : cn2.methods ) 
                {
        final MethodNode mn= (MethodNode) m2; 
        if ( isConstructor( mn ) ) 
        {
            if ( includeConstructors ) {
                visitMethod( mn , icn.name );
            }
        } else {
            if ( matches( mn ) ) {
                visitMethod( mn  , icn.name );
            } else {
                logVerbose("Ignored method: "+mn.name+"_"+mn.desc);
            }
        }
                }
                //System.out.println(analyzer.graphmap);
                
                        
                for ( Object m2 : cn2.methods ) 
                {
        final MethodNode mn= (MethodNode) m2; 
        if ( isConstructor( mn ) ) 
        {
            if ( includeConstructors ) {
               MethodDOTRender( mn );
            }
        } else {
            if ( matches( mn ) ) {
               MethodDOTRender( mn );
            } else {
                logVerbose("Ignored method: "+mn.name+"_"+mn.desc);
            }
        }
                }
                //System.out.println(((InnerClassNode)cn2.innerClasses.get(0)).innerName);
            //    for(Object o : cn2.innerClasses)
              //     System.out.println(((InnerClassNode)o).innerName);*/
    }
}

From source file:de.codesourcery.asm.controlflow.ControlFlowGrapher.java

License:Apache License

public void run() throws Exception {
    if (StringUtils.isBlank(classToAnalyze)) {
        throw new IllegalStateException("Class name not set");
    }/*from  ww w  . j  av  a  2s  .  c o m*/

    if (outputDir == null) {
        throw new IllegalStateException("No output directory set");
    }

    logVerbose("Output directory: " + outputDir.getAbsolutePath());

    showclass(classToAnalyze);

    final ClassReader classReader = ASMUtil.createClassReader(classToAnalyze, classPathEntries, new ILogger() {

        @Override
        public void logVerbose(String msg) {
            ControlFlowGrapher.this.logVerbose(msg);
        }
    });

    final ClassNode cn = new ClassNode();

    classReader.accept(cn, 0);
    for (Object m : cn.methods) {
        final MethodNode mn = (MethodNode) m;
        if (isConstructor(mn)) {
            if (includeConstructors) {
                MethodDOTRender(mn, classToAnalyze);
            }
        } else {
            if (matches(mn)) {
                MethodDOTRender(mn, classToAnalyze);
            } else {
                logVerbose("Ignored method: " + mn.name + "_" + mn.desc);
            }
        }
    }
}

From source file:de.codesourcery.asm.rewrite.ProfilingRewriter.java

License:Apache License

@SuppressWarnings("unchecked")
public byte[] rewrite(IClassReaderProvider provider, IJoinpointFilter filter)
        throws IOException, AnalyzerException {
    // first pass: create control flow graphs (CFGs) for all methods and constructors
    final String classToAnalyze = provider.getClassName();
    logVerbose("Analyzing " + classToAnalyze + " ... ");

    final ClassNode cn = new ClassNode();
    provider.getClassReader().accept(cn, 0);

    final ControlFlowAnalyzer analyzer = new ControlFlowAnalyzer();

    final Map<String, ControlFlowGraph> graphs = new HashMap<>();
    for (MethodNode mn : (List<MethodNode>) cn.methods) {
        if (filter.matches(classToAnalyze, mn.name)) {
            logVerbose("Analyzing method " + mn.name);
            if (debug) {
                System.out.println(Disassembler.disassemble(mn, true, true));
            }// w  ww .j  av a 2 s. c o m
            final ControlFlowGraph graph = analyzer.analyze(classToAnalyze, mn);
            if (debug) {
                System.out.println("Method " + mn.name + "_" + mn.desc + " has the following blocks");
                for (IBlock bl : graph.getAllNodes()) {
                    if (bl.isVirtual(mn)) {
                        System.out.println(
                                bl + " with " + bl.getByteCodeInstructionCount(mn) + " instructions (virtual)");
                    } else {
                        final int first = bl.getFirstByteCodeInstructionNum(mn);
                        System.out.println(bl + " with " + bl.getByteCodeInstructionCount(mn)
                                + " instructions (first = " + first + ")");
                    }
                }
            }
            graphs.put(methodNodeToKey(mn), graph);
        } else {
            logVerbose("Ignoring method " + mn.name);
        }
    }

    // second pass: rewrite methods and constructors by inserting custom code at the start of each basic block in the control flow graph
    logVerbose("Rewriting " + classToAnalyze + " ... ");

    final ClassWriter writer;
    if (graphs.isEmpty()) {
        writer = new ClassWriter(0);
        provider.getClassReader().accept(writer, 0);
    } else {
        writer = new ClassWriter(ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS);
        provider.getClassReader().accept(new MyClassVisitor(writer, graphs), 0);
    }

    final byte[] result = writer.toByteArray();
    if (debug) {
        final ClassReader reader = new ClassReader(result);

        final ClassNode classNode = new ClassNode();
        reader.accept(classNode, 0);

        System.out.println("==== Transformed class " + classToAnalyze + " ====");

        final ListIterator<MethodNode> it = classNode.methods.listIterator();
        while (it.hasNext()) {
            final MethodNode mn = it.next();
            if (filter.matches(classToAnalyze, mn.name)) {
                System.out.println("METHOD: " + mn.name + "_" + mn.desc);
                System.out.println(Disassembler.disassemble(mn, true, true));
            }
        }
    }
    return result;
}

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 w  w .  ja  v a2  s .c o  m*/
    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.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  w w w  .j a  v  a2 s .  c  o 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.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);/*from  ww  w . ja v a  2  s  .co  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:de.unisb.cs.st.javaslicer.tracer.instrumentation.Transformer.java

License:Open Source License

private boolean checkClass(final byte[] newClassfileBuffer, final String classname,
        byte[] origClassfileBuffer) {
    final ClassNode cn = new ClassNode();
    final ClassReader cr = new ClassReader(newClassfileBuffer);
    //cr.accept(new CheckClassAdapter(cn), ClassReader.SKIP_DEBUG);
    cr.accept(new CheckClassAdapter(cn), 0);

    for (final Object methodObj : cn.methods) {
        final MethodNode method = (MethodNode) methodObj;
        final Analyzer a = new Analyzer(new BasicVerifier());
        // SimpleVerifier has problems with sub-classes, e.g. you cannot use PrintStream for Appendable and so on...
        //final Analyzer a = new Analyzer(new SimpleVerifier(
        //    Type.getObjectType(cn.name), Type.getObjectType(cn.superName),
        //    (cn.access & Opcodes.ACC_INTERFACE) != 0));
        try {/*  w  ww . j a v  a 2 s.  c  o  m*/
            a.analyze(cn.name, method);
        } catch (final AnalyzerException e) {
            System.err.println("Error in method " + classname + "." + method.name + method.desc + ": " + e);
            //e.printStackTrace(System.err);
            printMethod(a, System.err, method);
            if (newClassfileBuffer == origClassfileBuffer) {
                System.err.println("This is the original bytecode!");
            } else {
                System.err.println("original bytecode:");
                ClassReader origClassReader = new ClassReader(origClassfileBuffer);
                ClassNode origClassNode = new ClassNode();
                origClassReader.accept(origClassNode, 0);
                for (Object origMethodObj : origClassNode.methods) {
                    MethodNode origMethod = (MethodNode) origMethodObj;
                    if (origMethod.name.equals(method.name) && origMethod.desc.equals(method.desc))
                        printMethod(System.err, origMethod);

                }
            }
            return false;
        }
    }
    return true;
}

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

License:Open Source License

@SuppressWarnings("unused")
private static void printClass(final byte[] classfileBuffer, final String classname) {
    /*//from w  w w .ja v  a2s  .c o m
    final TraceClassVisitor v = new TraceClassVisitor(new PrintWriter(System.out));
    new ClassReader(classfileBuffer).accept(v, ClassReader.SKIP_DEBUG);
    */
    final ClassNode cn = new ClassNode();
    final ClassReader cr = new ClassReader(classfileBuffer);
    //cr.accept(new CheckClassAdapter(cn), ClassReader.SKIP_DEBUG);
    cr.accept(new CheckClassAdapter(cn), 0);

    for (final Object methodObj : cn.methods) {
        final MethodNode method = (MethodNode) methodObj;
        final Analyzer a = new Analyzer(new BasicVerifier());
        //final Analyzer a = new Analyzer(new SimpleVerifier());
        try {
            a.analyze(cn.name, method);
        } catch (final AnalyzerException e) {
            System.err.println("// error in method " + classname + "." + method.name + method.desc + ":" + e);
        }
        printMethod(a, System.err, method);
    }
}